Академический Документы
Профессиональный Документы
Культура Документы
Introduction to the
C Programming Language
Author:
Rob Ostapiuk
Microchip Technology Inc.
1421 CPL
Slide 1
Agenda
Day One - Morning
1421 CPL
Slide 2
Agenda
Day One Afternoon
1421 CPL
Slide 3
Agenda
Day Two
Arrays
Data pointers
Function pointers
Structures
Unions
Bit fields
Enumerations
Macros with #define
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 4
Using C in an Embedded
Environment
1421 CPL
Slide 5
1421 CPL
Slide 6
1421 CPL
Slide 7
1421 CPL
Slide 8
C Source Files
Compiler
Driver
Program
Assembler
y Source Files
Assembly
(.asm or .s)
Object
Files
Archiver
(Librarian)
Linker
.a
Executable
Memory Map
MPLAB IDE
Debug Tool
Linker Script
COFF
Debug File
(.lkr or .gld)
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 9
C Compiler
C Source File
.c
Preprocessor
.h
C Header File
Compiler
.s
1421 CPL
Slide 10
C Runtime Environment
C Compiler sets up a runtime environment
Allocates space for stack
Initializes stack pointer
Allocates space for heap
Copies values from Flash/ROM to variables in
RAM that were declared with initial values
Clear uninitialized RAM
Disable all interrupts
Call main() function (where your code starts)
1421 CPL
Slide 11
C Runtime Environment
Runtime environment setup code is
automatically linked into application by
most PIC MCU compiler suites
Usually comes from either:
C30: crt0.s / crt0.o (crt = C RunTime)
C18: c018.c / c018.o
1421 CPL
Slide 12
Fundamentals of C
A Simple C Program
Example
Preprocessor
Directives
Header File
#include <stdio.h>
#define PI 3.14159
int main(void)
{
float radius, area;
Constant Declaration
(Text Substitution Macro)
Variable Declarations
Function
Comment
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 13
Comments
1421 CPL
Slide 14
Comments
Definition
1421 CPL
Slide 15
Comments
Using Block Comments
Block comments:
Begin with /* and end with */
May span multiple lines
/
/********************************************************
* Program: hello.c
* Author: R. Ostapiuk
********************************************************/
#include <stdio.h
stdio.h>
>
/* Function: main() */
int main
main(
(void
void)
)
{
printf(
printf
(Hello, world!\
world!\n
n);
); /* Display Hello, world! */
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 16
Comments
Using Single Line Comments
1421 CPL
Slide 17
Comments
Nesting Comments
/*
code here
code here
*/
1421 CPL
Slide 18
Comments
Best Practices
/********************************************************
* Program: hello.c
* Author: R. Ostapiuk
********************************************************/
#include <stdio.h
stdio.h>
>
/********************************************************
* F
Function:
ti
main()
i ()
********************************************************/
int main
main(
(void
void)
)
{
/*
int i;
// Loop count variable
char *p;
// Pointer to text string
*/
printf(
printf
(Hello, world!\
world!\n
n);
); // Display Hello, world!
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 19
Variables, Identifiers
and Data Types
1421 CPL
Slide 20
#include <stdio.h>
#define PI 3.14159
Data
Types
int main(void)
{
float radius, area;
Variable Declarations
Variables
in use
1421 CPL
Slide 21
Variables
Definition
5
int myVariable;
myVariable = 5;
1421 CPL
Slide 22
Variables
Variables are names for
storage locations in
memory
int
i t warp_factor;
f t
15
4116
char first_letter;
float length;
5.74532370373175
10-44
1421 CPL
Slide 23
Variables
Variable declarations
consist of a unique
identifier (name)
15
int
i t warp_factor;
f t
4116
char first_letter;
float length;
5.74532370373175
10-44
1421 CPL
Slide 24
Variables
and a data type
Determines size
Determines how values
are interpreted
int
i t warp_factor;
f t
15
4116
char first_letter;
float length;
5.74532370373175
10-44
1421 CPL
Slide 25
Identifiers
Names given to program elements:
Variables, Functions, Arrays, Other
Elements
Example of Identifiers in a Program
#include <stdio.h>
<stdio h>
#define PI 3.14159
int main(void)
{
float radius, area;
//Calculate area of circle
radius = 12.0;
area = PI * radius * radius;
printf("Area = %f", area);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 26
Identifiers
Valid characters in identifiers:
Identifier
First Character
_ (underscore)
A to Z
a to z
g Characters
Remaining
_ (underscore)
A to Z
a to z
0 to 9
Case sensitive!
Only first 31 characters significant*
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 27
ANSI C Keywords
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
1421 CPL
Slide 28
Data Types
Fundamental Types
Type
Description
char
int
float
double
single character
Bits
integer
single precision floating point number
double precision floating point number
8
16
32
64
1421 CPL
Slide 29
Min
unsigned char
0
char, signed char
-128
unsigned short int
0
short int, signed short int -32768
unsigned int
0
int, signed int
-32768
unsigned long int
0
long int, signed long int
-231
unsigned long long int
0
long long int,
-263
signed long long int
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Max
Bits
255
127
65535
32767
16
16
65535
16
32767
232-1
16
32
231-1
264-1
32
64
263-1
64
Slide 30
Absolute Min
Absolute Max
Bits
float
~10-44.85
~1038.53
32
double (1)
~10-44.85
~1038.53
32
long double
~10-323.3
~10308.3
64
MPLAB C30:
(1)double
is equivalent to long
double if fno-short-double is used
1421 CPL
Slide 31
Variables
How to Declare a Variable
Syntax
int x, y, z;
float warpFactor
warpFactor;
;
char text_buffer[10]
text_buffer[10];
;
unsigned index
index;
;
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 32
Variables
How to Declare a Variable
type identifier
identifier;
;
One declaration on a line with an initial value
1421 CPL
Slide 33
Variables
How to Declare a Variable
Examples
unsigned int x;
unsigned y = 12
12;
;
int a, b, c;
long
g int myVar
y
= 0x12345678
0x12345678;
;
long z;
char first = 'a'
'a',
, second
second,
, third = 'c'
'c';
;
float big_number = 6.02e+23
6.02e+23;
;
It is customary for variable names to be spelled using "camel case", where the initial letter
is lower case. If the name is made up of multiple words, all words after the first will start
with an upper case letter (e.g. myLongVarName).
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 34
Variables
How to Declare a Variable
MyProgram.h
MyProgram.c
1421 CPL
Slide 35
#include Directive
Three ways to use the #include directive:
Syntax
#include <file.h>
Look for file in the compiler search path
p
p
y includes the compiler's
p
y
The compiler
search path
usually
directory
and all of its subdirectories.
For example: C:\
C:\Program Files
Files\\Microchip\
Microchip\MPLAB C30\
C30\*.*
#include file.h
Look for file in project directory only
#include c:
c:\
\MyProject
MyProject\
\file.h
Use specific path to find include file
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 36
#include Directive
main.h Header File and main.c Source File
main.h
main.c
unsigned int a;
unsigned int b;
unsigned int c;
#include "main.h"
int main(void
main(void)
)
{
a = 5;
b = 2;
c = a+b;
}
1421 CPL
Slide 37
#include Directive
Equivalent main.c File
main.c
unsigned int a;
unsigned int b;
unsigned int c;
int main(void
main(void)
)
{
a = 5;
b = 2;
c = a+b;
}
Equivalent main.c file
without #include
1421 CPL
Slide 38
Lab Exercise 1
Variables and Data Types
1421 CPL
Slide 39
Lab 01
Variables and Data Types
1421 CPL
Slide 40
Lab 01
Variables and Data Types
1421 CPL
3 Run
Halt
Slide 41
Lab 01
Variables and Data Types
1421 CPL
Slide 42
Lab 01
Variables and Data Types
1421 CPL
Slide 43
Lab 01
Variables and Data Types
16--bit Data Memory
16
0x08A9
0x08AF
0x08B1
0x08B3
0x08B5
0x08B7
0x08B9
0x08BB
Variables in Memory
0x08A8
0x08AB
0x08AD
00
00
00
00
42
00
42
00
32
32
32
32
00
48
00
48
00
0x08BD
0x08AA
0x08AC
0x08AE
0x08B0
0x08B2
0x08B4
0x08B6
0x08B8
0x08BA
char
short int
int
long int
float
double
Multi-byte values
Multistored in "Little
Endian" format
on PIC
microcontrollers
0x08BC
1421 CPL
Slide 44
Lab 01
Variables and Data Types
Declare Constant
#define
Declare Variables
int
Initialize Variables
intVariable = CONSTANT1;
Print Variable
Sizes
Loop
Forever
2010 Microchip Technology Incorporated. All Rights Reserved.
CONSTANT1
50
intVariable;
Slide 45
Lab 01
Conclusions
1421 CPL
Slide 46
Literal Constants
1421 CPL
Slide 47
A Simple C Program
Literal Constants
Example
unsigned int a;
unsigned int c;
#define b 2
Literal
void main
main(
(void
void)
)
{
a = 5;
Literal
c = a + b;
printf(
printf
("a=%d, b=%d, c=%d\
c=%d\n"
n",
, a, b, c);
}
1421 CPL
Slide 48
Literal Constants
Definition
Literals
Lit l
Are "hard coded" values
May be numbers, characters or strings
May be represented in a number of formats
(decimal, hexadecimal, binary, character, etc.)
Always represent the same value (5 always
represents the quantity five)
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 49
1421 CPL
Slide 50
Literal Constants
Four basic types of literals:
Integer
Floating Point
Character
String
1421 CPL
Slide 51
Integer Literals
Decimal (Base 10)
127
-1021
1021
65535
32,767
25.0
1 024
1421 CPL
0552
Slide 52
Integer Literals
Hexadecimal (Base 16)
0x
0 0x1
0 1
0x0A2B
0 0A2B
0xBEEF
0
BEEF
0x5.3
0EA12
1421 CPL
0xEG
53h
Slide 53
Integer Literals
Octal (Base 8)
53o
1421 CPL
Slide 54
Integer Literals
Binary (Base 2)
0b
0b1
0b0101001100001111
0b1.0
01100
0b12
10b
1421 CPL
Slide 55
Integer Literals
Qualifiers
1421 CPL
Slide 56
10f
1421 CPL
Slide 57
Character Literals
Specified within single quotes (')
May include any single printable character
May include any single non-printable
character
h
t using
i escape sequences (e.g.
(
'\0' = NUL) (also called digraphs)
Valid Characters: 'a', 'T', '\n', '5',
'@', ' ' (space)
Invalid Characters: 'me', '23', '''
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 58
String Literals
Specified within double quotes (")
May include any printable or non-printable
characters (using escape sequences)
Usually terminated by a null character \0
Valid Strings: "Microchip", "Hi\n",
"PIC", "2500","rob@microchip.com",
"He said, \"Hi\""
Invalid Strings: "He said, "Hi""
1421 CPL
Slide 59
String Literals
Declarations
char color
color[
[3] = "RED"
"RED";
;
Is stored as:
color[
color
[0] = 'R'
color[
color
[1] = 'E'
color[
color
[2] = 'D'
char color
color[]
[] = "RED"
"RED";
;
Is stored as:
color[
color
[0] = 'R'
color[
color
[1] = 'E'
color[
color
[2] = 'D'
color[
color
[3] = '\0'
1421 CPL
Slide 60
String Literals
How to Include Special Characters in Strings
Escape Sequence
\a
\b
\t
\n
\v
\f
\r
\"
\'
\?
\\
\0
ASCII Value
Character
BELL (alert)
Backspace
Horizontal Tab
Newline (Line Feed)
Vertical Tab
Form Feed
Carriage Return
Quotation Mark (")
Apostrophe/Single Quote (')
Question Mark (?)
Backslash ((\\)
Null
1421 CPL
7
8
9
10
11
12
13
34
39
63
92
0
Slide 61
String Literals
How to Include Special Characters in Strings
Example
char message
message[]
[] = "Please enter a command
command\
\n"
1421 CPL
Slide 62
Symbolic Constants
1421 CPL
Slide 63
Symbolic Constants
Definition
Constants
C
t t
Once assigned, never change their value
Make development changes easy
Eliminate the use of "magic numbers"
Two types of constants
Text Substitution Labels
Variable Constants (!!??)
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 64
Symbolic Constants
Constant Variables Using const
1421 CPL
Slide 65
Symbolic Constants
Text Substitution Labels Using #define
#define
#define
#define
#define
PI 3.14159
mol 6.02E23
MCU "PIC24FJ128GA010"
COEF 2 * PI
1421 CPL
Slide 66
Symbolic Constants
#define Gotchas
#define MyConst 5;
c = MyConst + 3;
c = 5; + 3;
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 67
Symbolic Constants
Initializing Variables When Declared
#define CONSTANT1 5
const CONSTANT2 = 10
10;
;
int variable1 = CONSTANT1
CONSTANT1;
;
int variable2
variable2;
;
// Cannot do: int variable2 = CONSTANT2
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 68
Lab Exercise 2
Symbolic Constants
1421 CPL
Slide 69
Lab 02
Symbolic Constants
1421 CPL
Slide 70
Lab 02
Symbolic Constants
1421 CPL
3 Run
Halt
Slide 71
Lab 02
Symbolic Constants
1421 CPL
Slide 72
Lab 02
Symbolic Constants
1421 CPL
Slide 73
Lab 02
Symbolic Constants
1421 CPL
Slide 74
Lab 02
Symbolic Constants
lab02.map
l b02
_CONSTANT2
__Atexit
__Closreg
__DNKfflush
__DefaultInterrupt
1421 CPL
Slide 75
Lab 02
Conclusions
1421 CPL
Slide 76
1421 CPL
Slide 77
printf()
Standard Library Function
1421 CPL
Slide 78
printf()
Standard Library Function
Syntax
printf(
printf
(ControlString
ControlString,
, arg1
arg1,
,argn
argn);
);
Everything printed verbatim within string except %d's,
which are replaced by the argument values from the list
Example
int a = 5, b = 10
10;
;
printf(
printf
("a = %d
%d\
\nb = %d
%d\
\n"
n",
, a, b);
Result:
a=5
b = 10
2010 Microchip Technology Incorporated. All Rights Reserved.
Slide 79
printf()
Conversion Characters for Control String
Conversion
Character
%c
%s
%d
%o
%
%u
%x
%X
%f
%e
%E
%g
%G
Meaning
Single character
String (all characters until '\'\0')
Signed decimal integer
Unsigned octal integer
Unsigned decimal integer
Unsigned hexadecimal integer with lowercase digits (1a5e
(1a5e))
As x, but with uppercase digits (e.g. 1A5E
1A5E))
Signed decimal value (floating point)
Signed decimal with exponent (e.g. 1.26e
1.26e-5)
As e, but uses E for exponent (e.g. 1.26E
1.26E-5)
As e or f, but depends on size and precision of value
As g, but uses E for exponent
1421 CPL
Slide 80
printf()
Gotchas
1421 CPL
Slide 81
printf()
Useful Format String Examples for Debugging
1421 CPL
Slide 82
printf()
Useful Format String Examples for Debugging
1421 CPL
Slide 83
Lab Exercise 3
printf() Library Function
1421 CPL
Slide 84
Lab 03
printf() Library Function
1421 CPL
Slide 85
Lab 03
printf() Library Function
1421 CPL
3 Run
Halt
Slide 86
Lab 03
printf() Library Function
1421 CPL
Slide 87
Lab 03
printf() Library Function
Output
printf(
printf
("25 as decimal (d): %d\
%d\n"
n",
, 25
25);
); 25
printf(
printf
("'a' as character (c): %c\
%c\n"
n",
, 'a'
'a');
); a
printf(
printf
("'a' as decimal (d): %d
%d\
\n"
n",
, 'a'
'a');
); 97
printf(
printf
("2.55 as float (f): %f\
%f\n"
n",
, 2.55
2.55);
); 2.550000
printf(
printf
("2.55 as decimal (d): %d
%d\
\n"
n",
, 2.55
2.55);
); 16419
printf(
printf
("6.02e23 as exponent (e): %e\
%e\n"
n",
, 6.02e23
6.02e23);
); 6.020000e+23
printf(
printf
("6.02e23 as decimal (d): %d
%d\
\n"
n",
, 6.02e23
6.02e23);
); 26366
printf(
printf
("'Microchip' as string (s): %s\
%s\n"
n",
, "Microchip"
"Microchip");
); Microchip
printf(
printf
("'Microchip' as decimal (d): %d
%d\
\n"
n",
, "Microchip"
"Microchip");
); -24058
1421 CPL
Slide 88
Lab 03
Conclusions
1421 CPL
Slide 89
Operators
1421 CPL
Slide 90
Operators
How to Code Arithmetic Expressions
Definition
1421 CPL
Slide 91
Operators
Arithmetic
Operator
*
/
%
+
+ (unary)
- (unary)
Operation
Example
Result
Multiplication
x * y
Product of x and y
Division
Modulo
x / y
x % y
Addition
Subtraction
x + y
x - y
Positive
Negative
+x
-x
Quotient of x and y
Remainder of x divided by y
Sum of x and y
Difference of x and y
Value of x
Negative value of x
1421 CPL
Slide 92
Operators
Division Operator
int a
int b
float
c = a
int a
float
float
c = a
= 10
10;
;
= 4;
c;
/ b;
c = 2.0
2.000000
= 10
10;
;
b = 4.0f
4.0f;
;
c;
/ b;
c = 2.5
2.500000
1421 CPL
Slide 93
Operators
Implicit Type Conversion
i t x = 10
int
10;
;
float y = 2.0
2.0,
, z;
z = x * y;
// x promoted to float
1421 CPL
Slide 94
Operators
1421 CPL
Slide 95
Operators
Arithmetic Expression Implicit Type Conversion
-x
x * -2L
x is promoted to int
x is promoted to long
because -2L is a long
x is promoted to int
x is promoted to int
x is promoted to double
because 8.0 is a double
8/x
8%x
8.0/x
1421 CPL
int
long
5
10
int
int
double
-1
3
-1.6
Slide 96
Operators
Applications of the Modulus Operator (%)
1421 CPL
Slide 97
Operators
Arithmetic: Increment and Decrement
Operator
Operation
++
Increment
--
Decrement
Example
Result
x++
++x
x--
--x
-x
Postfix Example
Prefix Example
x = 5;
y = (x++
x++)
) + 5;
// y = 10
// x = 6
x = 5;
y = (++x
(++x)
) + 5;
// y = 11
// x = 6
1421 CPL
Slide 98
Operators
How to Code Assignment Statements
Definition
1421 CPL
Slide 99
Operators
Assignment
Operator
Operation
Example
=
+=
-=
*=
/=
Assignment
x = y
x += y
x -= y
%=
&=
^=
|=
Compound
Assignment
x
x
x
x
x
x
x
x
x
x
x *= y
x /= y
<<=
>>=
2010 Microchip Technology Incorporated. All Rights Reserved.
x %= y
x &= y
x ^= y
x |= y
x <<= y
x >>= y
1421 CPL
Result
=
=
=
=
=
=
=
=
=
=
x
x
x
x
x
x
x
x
x
x
+ y
- y
* y
/ y
% y
& y
^ y
| y
<< y
>> y
Slide 100
Operators
Compound Assignment
x = x + y;
This operation may be thought of as: The new value of x will be
set equal to the current value of x plus the value of y
x += y;
1421 CPL
Slide 101
Operators
Compound Assignment
Example
int x = 2;
//Initial value of x is 2
x *= 5;
//x = x * 5
B f
Before
statement
t t
t iis executed:
t d x=2
After statement is executed: x = 10
Is equivalent to:
Evaluate right side first:
Assign result to x:
2010 Microchip Technology Incorporated. All Rights Reserved.
x
x
x
x
*= 5;
= (x * 5);
= (2 * 5);
= 10;
1421 CPL
Slide 102
Operators
Relational
Operator
Operation
Example
<
Less than
x < y
<=
Less than or
equal to
x <= y
>
Greater than
x > y
>=
Greater than
or equal to
x >= y
==
Equal to
x == y
1 if x equal to y, else 0
!=
Not equal to
x != y
1421 CPL
Slide 103
Operators
Difference Between = and ==
if (x == 5)
{
do if value of x is 5
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 104
Operators
Difference Between = and ==
void main
main(
(void
void)
)
{
int x = 2;
if (x = 5)
{
printf(
printf
("Hi!"
"Hi!");
);
}
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
//Initialize x
//If x is 5,
//display "Hi!"
Slide 105
Operators
Logical
Operator
Operation
Example
&&
Logical AND
x && y
1 if both x 0 and y 0,
else 0
||
Logical OR
x || y
0 if both x = 0 and y = 0,
else 1
Logical NOT
!x
1 if x = 0, else 0
1421 CPL
Slide 106
Operators
Bitwise
Operator
&
|
Operation
Example
Bitwise AND
x & y
1, if 1 in both x and y
0, if 0 in x or y or both
Bitwise OR
x | y
1, if 1 in x or y or both
0, if 0 in both x and y
1 if 1 in x or y but not both
1,
0, if 0 or 1 in both x and y
Bitwise XOR
x ^ y
Bitwise NOT
~x
(One's Complement)
1, if 0 in x
0, if 1 in x
1421 CPL
Slide 107
Operators
Difference Between & and &&
1421 CPL
Slide 108
Operators
Difference Between & and &&
char x = 0b1010
0b1010;
;
char y = 0b0101
0b0101;
;
if (x & y) printf
printf(
("Hi!"
"Hi!");
);
Example 2 Using A Logical AND Operator
char x = 0b1010
0b1010;
;
char y = 0b0101
0b0101;
;
if (x && y) printf
printf(
("Hi!"
"Hi!");
);
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 109
Operators
Logical Operators and Short Circuit Evaluation
expr1
0
0
1
1
expr2
X (0)
X (1)
0
1
1421 CPL
Result
0
0
0
1
Operators
Logical Operators and Short Circuit Evaluation
if !((
((z
z = x + y) && (c
(c = a + b))
{
z += 5;
c += 10
10;
;
Initial value of c may not be correct
}
It is perfectly legal in C to logically compare two assignment expressions in
this way, though it is not usually good programming practice.
A similar problem exists when using function calls in logical operations, which
is a very common practice. The second function may never be evaluated.
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 111
Operators
Shift
Operator
Operation
Example
Result
<<
Shift Left
x << y
>>
Shift Right
x >> y
x = 5;
y = x << 2;
// x = 0b00000101 = 5
// y = 0b00010100 = 20
1421 CPL
Slide 112
Operators
Shift Special Cases
x = 250;
y = x >> 2;
// x = 0b11111010 = 250
// y = 0b00111110 = 62
x = -6;
y = x >> 2;
// x = 0b11111010 = -6
// y = 0b11111110 = -2
1421 CPL
Slide 113
Operators
Power of 2 Integer Divide vs. Shift Right
y = x >> n
y = x / 2n
0 0 0 0 1 0 1 0
>>
1010
Right Shift
0 0 0 0 0 1 0 1
510
1421 CPL
Slide 114
Operators
Power of 2 Integer Divide vs. Shift in MPLAB C30
Example: Divide by 2
int x = 20
20;
;
int y;
y = x / 2;
10:
00288
0028A
0028C
0028E
00290
804000
200022
090011
D80002
884010
int x = 20
20;
;
int y;
y = x >> 1;
y = 10
y = x / 2;
mov.w 0x0800,0x0000
mov.w #0x2,0x0004
repeat #17
div.sw 0x0000,0x0004
mov.w 0x0000,0x0802
9:
00282
00284
00286
1421 CPL
804000
DE8042
884010
y = 10
y = x >> 1;
mov.w 0x0800,0x0000
asr 0x0000,#1,0x0000
mov.w 0x0000,0x0802
Slide 115
Operators
Power of 2 Integer Divide vs. Shift in MPLAB C18
Example: Divide by 2
int x = 20
20;
;
int y;
y = x / 2;
10:
0132
0134
0136
0138
013A
013C
013E
0140
0142
0144
0146
0148
014A
014C
014E
0150
0152
C08C
F08A
C08D
F08B
0E02
6E0D
6A0E
C08A
F008
C08B
F009
EC6B
F000
C008
F08A
C009
F08B
int x = 20
20;
;
int y;
y = x >> 1;
y = 10
9:
0122
0124
0126
0128
012A
012C
012E
0130
y = x / 2;
MOVFF 0x8c, 0x8a
NOP
MOVFF 0x8d, 0x8b
NOP
MOVLW 0x2
MOVWF 0xd, ACCESS
CLRF 0xe, ACCESS
MOVFF 0x8a, 0x8
NOP
MOVFF 0x8b, 0x9
NOP
CALL 0xd6, 0
NOP
MOVFF 0x8, 0x8a
NOP
MOVFF 0x9, 0x8b
NOP
C08C
F08A
C08D
F08B
0100
90D8
338B
338A
y = 10
y = x >> 1;
MOVFF 0x8c, 0x8a
NOP
MOVFF 0x8d, 0x8b
NOP
MOVLB 0
BCF 0xfd8, 0, ACCESS
RRCF 0x8b, F, BANKED
RRCF 0x8a, F, BANKED
16--bit Shift on 8
16
8--bit Architecture
1421 CPL
Slide 116
Operators
Memory Addressing
Operator
Operation
Example
Result
&
Address of
&x
Pointer to x
Indirection
*p
[]
Subscripting
x[y]
Struct / Union
Member
x.y
->
Struct / Union
Member by
Reference
p->y
1421 CPL
Slide 117
Operators
Other
Operator
Operation
Example
Result
()
Function Call
foo(x)
sizeof
Size of an
object or type
in bytes
sizeof x
(type)
Explicit type
cast
(short) x
?:
Conditional
expression
Sequential
evaluation
x, y
1421 CPL
Operators
The Conditional Operator
Syntax
(test
test-expr
expr)
) ? do
do-if
if-true : do
do-if
if-false
false;
;
Example
int x = 5;
(x % 2 != 0) ?
printf(
printf
("%d is odd\
odd\n"
n",
, x) :
printf(
printf
("%d is even\
even\n",
n", x);
Result:
5 is odd
1421 CPL
Slide 119
Operators
The Conditional Operator
) ? a : b;
;
x = (
(condition)
Example 2 (less often used)
1421 CPL
Slide 120
Operators
The Explicit Type Cast Operator
int x = 10
10;
;
float y;
int x = 10
10;
;
float y;
y = x / 4;
y = (float
float)
)x / 4;
y = 2.0
2.000000
1421 CPL
Slide 121
Operators
Precedence
Operator
( )
[ ]
.
->
+ ++ -! ~
*
&
sizeof
(type)
Description
Associativity
Parenthesized Expression
Array Subscript
Left--toLeft
to-Right
Structure Member
Structure Pointer
U
Unary
+ and
d (Positive
(P iti and
dN
Negative
ti Si
Signs))
Increment and Decrement
Logical NOT and Bitwise Complement
Dereference (Pointer)
Right--toRight
to-Left
Address of
Size of Expression or Type
Explicit Typecast
Continued on next slide
1421 CPL
Slide 122
Operators
Precedence
Operator
* / %
+ << >>
< <=
> >=
== !=
&
^
|
&&
||
?:
Description
Associativity
Left--toLeft
to-Right
Left--toLeft
to-Right
Left--toLeft
to-Right
Left--toLeft
to-Right
g
Left--toLeft
to-Right
Left--toLeft
to-Right
Bitwise AND
Left--toLeft
to-Right
Bitwise XOR
Left--toLeft
to-Right
Bitwise OR
Left--toLeft
to-Right
Logical AND
Left--toLeft
to-Right
Logical OR
Left--toLeft
to-Right
Conditional Operator
Right--toRight
to-Left
1421 CPL
Slide 123
Operators
Precedence
Operator
Description
=
+= -=
/= *=
%=
<<= >>=
Assignment
&= |=
^=
,
Associativity
Modulus Assignment
Shift Left and Shift Right
g Assignments
g
Bitwise AND and OR Assignments
Bitwise XOR Assignment
Comma Operator
LeftLeft-toto-Right
1421 CPL
Slide 124
Operators
Precedence
Effective Expression
a b * c
a (b * c)
a + ++b
a + (++b)
a + ++b * c
a + ((++b) * c)
1421 CPL
Slide 125
Operators
Associativity
Associativity
Effective Expression
x / y % z
Left-to
Leftto--Right
(x / y) % z
x = y = z
Right--to
Right
to--Left
x = (y = z)
~++x
Right--to
Right
to--Left
~(++x)
1421 CPL
Slide 126
Lab Exercise 4
Operators
1421 CPL
Slide 127
Lab 04
Operators
1421 CPL
Slide 128
Lab 04
Operators
1421 CPL
Slide 129
Lab 04
Operators
1421 CPL
Slide 130
Lab 04
Operators
Solution: Step 5
/*###########################################################################
# STEP 5: Perform the operation (longVariable2 AND 0x30) and store the result
#
back in longVariable2. Once again, the easiest way to do this is
#
to use the appropriate compound assignment operator that will
#
perform an equivalent operation to the one in the comment below.
###########################################################################*/
//longVariable2 = longVariable2 & 0x30
longVariable2 &= 0x30;
1421 CPL
Slide 131
Lab 04
Conclusions
1421 CPL
Slide 132
Expressions and
Statements
1421 CPL
Slide 133
Expressions
Represents a single data item (e.g.
character, number, etc.)
May consist of:
A single entity (a constant, variable, etc.)
A combination of entities connected by
operators (+, -, *, / and so on)
1421 CPL
Slide 134
Expressions
Examples
Example
a + b
x = y
speed = dist
dist/
/time
z = ReadInput
ReadInput()
()
c <= 7
x == 25
count++
count
++
d = a + 5
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 135
Statements
Cause an action to be carried out
Three kinds of statements in C:
p
Expression
Statements
Compound Statements
Control Statements
1421 CPL
Slide 136
Expression Statements
An expression followed by a semi-colon
Execution of the statement causes the
expression to be evaluated
Examples
i = 0;
i++;
a = 5 + i;
y = (m
(m * x) + b;
printf("Slope
printf(
"Slope = %f"
%f",
, m);
m);
;
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 137
Compound Statements
A group of individual statements enclosed
within a pair of curly braces { and }
Individual statements within may be any
statement type,
type including compound
Allows statements to be embedded within
other statements
Does NOT end with a semicolon after }
Also called Block Statements
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 138
Compound Statements
Example
Example
{
float start
start,
, finish
finish;
;
start = 0.0
0.0;
;
finish = 400.0
400.0;
;
distance = finish start
start;
;
time = 55.2
55.2;
;
speed = distance / time
time;
;
printf(
printf
("Speed = %f m/s",
m/s", speed
speed);
);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 139
Control Statements
Used for loops, branches and logical tests
Often require other statements embedded
within them
Example
1421 CPL
Slide 140
Making Decisions
1421 CPL
Slide 141
Boolean Expressions
C has no Boolean data type
Boolean expressions return integers:
0 if expression evaluates as FALSE
Non-zero if expression evaluates as TRUE
(usually returns 1, but this is not guaranteed)
int main(
main(void
void)
)
{
int x = 5, y, z;
y = (x
(x > 4);
z = (x
(x > 6);
while (1);
y = 1 (TRUE)
z = 0 (FALSE)
1421 CPL
Slide 142
Boolean Expressions
Equivalent Expressions
1421 CPL
Slide 143
if Statement
Syntax
if (expression
expression)
) statement
1421 CPL
if (expression)
{
statement1
statement2
}
Slide 144
if Statement
Flow Diagram
Syntax
if (expression
expression)
) statement
expression 0
TRUE
FALSE
expression = 0
1421 CPL
Slide 145
if Statement
Example
int x = 5;
if (x)
If x is TRUE (non(non-zero)
{
printf(
printf
("x
x = %d\
%d\n
n",
n"
, x); then
then print the value of x.
x
}
while (1);
1421 CPL
Slide 146
if Statement
Testing for TRUE
if (x) vs. if (x == 1)
if (x) only needs to test for not equal to 0
if (x == 1) needs to test for equality with 1
Remember: TRUE is defined as non-zero, FALSE is
defined as zero
Example: if (x)
Example: if (x ==1)
if (x)
8:
011B4
011B6
E208C2
320004
if (x == 1)
11:
011C0
011C2
011C4
if (x)
cp0.w 0x08c2
bra z, 0x0011c0
1421 CPL
804610
500FE1
3A0004
if (x == 1)
mov.w 0x08c2,0x0000
sub.w 0x0000,#1,[0x001e]
bra nz, 0x0011ce
Slide 148
Nested if Statements
Example
int power = 10
10;
;
float band = 2.0
2.0;
;
float frequency = 146.52
146.52;
;
if (power > 5)
{
if (band == 2.0
2.0)
)
{
if ((
((frequency
frequency > 144
144)
) && (frequency
(frequency < 148
148))
))
{
printf(
printf
("Yes, it's all true!\
true!\n"
n");
);
}
}
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 149
if-else Statement
Syntax
if (expression
expression)
) statement1
else statement2
1421 CPL
Slide 150
if-else Statement
Flow Diagram
Syntax
if (expression
expression)
) statement1
else statement2
expression 0
TRUE
FALSE
expression = 0
1421 CPL
Slide 151
if-else Statement
Example
{
float frequency = 146.52
146.52;
;
//frequency in MHz
if ((frequency
((frequency > 144.0
144.0)
) && (frequency < 148.0
148.0))
))
{
printf(
printf
("You're on the 2 meter band\
band\n"
n");
);
}
else
{
printf(
printf
("You're not on the 2 meter band\
band\n"
n");
);
}
}
1421 CPL
Slide 152
if-else if Statement
Syntax
if (expression1) statement1
else if (expression2) statement2
else statement3
1421 CPL
Slide 153
if-else if Statement
Flow Diagram
Syntax
if (expression1) statement1
else if (expression2) statement2
else statement3
TRUE
FALSE
TRUE
FALSE
1421 CPL
Slide 154
if-else if Statement
Example
if ((
((freq
freq > 144
144)
) && (freq
(freq < 148
148))
))
printf(
printf
("You're on the 2 meter band\
band\n"
n");
);
else if ((
((freq
freq > 222
222)
) && (freq
(freq < 225
225))
))
printf(
printf
("You're on the 1
1.25
25 meter band\
band\n"
n");
);
else if ((
((freq
freq > 420
420)
) && (freq
(freq < 450
450))
))
printf(
printf
("You're on the 70 centimeter band\
band\n"
n");
);
else
printf(
printf
("You're somewhere else\
else\n"
n");
);
1421 CPL
Slide 155
Lab Exercise 5
Making Decisions: if Statements
1421 CPL
Slide 156
Lab 05
Making Decisions (if)
1421 CPL
Slide 157
Lab 05
Making Decisions (if)
1421 CPL
Slide 158
Lab 05
Making Decisions (if)
Solution: Step 3
/*###########################################################################
# STEP 3: If neither of the above are true, set charVariable2 equal to 1.
#
(HINT: else)
###########################################################################*/
//Write the else condition
else
{
charVariable2 = 1;
//Set charVariable2 equal to 1
}
1421 CPL
Slide 159
Lab 05
Conclusions
1421 CPL
Slide 160
switch Statement
Syntax
switch (expression
expression)
)
{
case const
const-expr1: statements1
case const
const-exprn: statementsn
default:
default
: statementsn+1
1421 CPL
Slide 161
switch Statement
Flow Diagram (default)
START
Const-expr1= YES
expression?
statement1
NO
Const-expr2=
expression?
YES
statement2
NO
Const-exprn=
expression?
YES
statementn
NO
statementn+1
END
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 162
switch Statement
Flow Diagram (modified)
START
Const-expr1= YES
expression?
statement1
break;
NO
Const-expr2= YES
expression?
statement2
break;
NO
Const-exprn=
expression?
YES
statementn
break;
NO
Adding a break
statement to each
statement block will
eliminate fall
f
through, allowing
only one case
clause's statement
block to be executed
statementn+1
END
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 163
switch Statement
switch Example 1
switch(channel
switch(
channel)
)
{
case 2: printf
printf(
("WBBM Chicago\
Chicago\n"
n");
); break
break;
;
case 3: printf
printf(
("DVD Player\
Player\n"
n");
); break
break;
;
case 4: printf
printf(
("WTMJ Milwaukee\
Milwaukee\n"
n");
); break
break;
;
case 5: printf
printf(
i tf(
tf("WMAQ Chi
Chicago\n"
Chicago\
n");
");
) break
b
break;
k;
case 6: printf
printf(
("WITI Milwaukee\
Milwaukee\n"
n");
); break
break;
;
case 7: printf
printf(
("WLS Chicago\
Chicago\n"
n");
); break
break;
;
case 9: printf
printf(
("WGN Chicago\
Chicago\n"
n");
); break
break;
;
case 10
10:
: printf
printf(
("WMVS Milwaukee\
Milwaukee\n"
n");
); break
break;
;
case 11
11:
: printf
printf(
("WTTW Chicago\
Chicago\n"
n");
); break
break;
;
case 12
12:
: printf
printf(
("WISN Milwaukee\
Milwaukee\n"
n");
); break
break;
;
default:
default
: printf
printf(
("No Signal Available\
Available\n"
n");
);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 164
switch Statement
switch Example 2
switch(letter
switch(
letter)
)
{
case 'a'
'a':
:
printf(
printf
("Letter 'a' found.\
found.\n"
n");
);
break;
break
;
case 'b'
'b':
:
printf(
printf
("Letter 'b' found.\
found.\n"
n");
);
break;
break
;
case 'c'
'c':
:
printf(
printf
("Letter 'c' found.\
found.\n"
n");
);
break;
break
;
default:
default
:
printf(
printf
("Letter not in list.\
list.\n"
n");
);
}
1421 CPL
Slide 165
switch Statement
switch Example 3
switch(channel
switch(
channel)
)
Apply this case to channel 4, 5,
{
6, and 7
case 4 ... 7:
7:
printf(
printf
("VHF Station\
Station\n"
n");
); break
break;
;
case 9 ... 12:
12:
printf(
printf
p
("VHF Station\
Station\n"
n");
); break
break;
;
case 3:
Case 3 and 8 are allowed to fall
case 8:
through to case 13
case 13
13:
:
printf(
printf
("Weak Signal\
Signal\n"
n");
); break
break;
;
case 14 ... 69:
69:
printf(
printf
("UHF Station\
Station\n"
n");
); break
break;
;
default:
default
:
printf(
printf
("No Signal Available\
Available\n"
n");
);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 166
Lab Exercise 6
Making Decisions: switch Statements
1421 CPL
Slide 167
Lab 06
Making Decisions (switch)
1421 CPL
Slide 168
Lab 06
Making Decisions (switch)
Solution: Step 1
/*###########################################################################
# TASK:
Write a switch statement to print the network's initials with the
#
channel (based on Chicago TV stations).
#
* If channel = 2, print "CBS 2" to the output window.
#
* If channel = 5, print "NBC 5" to the output window.
#
* If channel = 7, print "ABC 7" to the output window.
#
* For all other channels
channels, print "--- #
#" to the output window
window,
#
where "#" is the channel number.
#
(HINT: Use printf(), and use the newline character '\n' at the end
#
of each string you print to the output window.)
# NOTE:
The switch statement is in a loop that will execute 9 times. Each
#
pass through the loop, 'channel' will be incremented. The output
#
window should display a line of text for channels 2 to 10.
#
# STEP 1: Open a switch statement on the variable 'channel'
###########################################################################*/
//Begin switch statement
switch(channel)
{
1421 CPL
Slide 169
Lab 06
Making Decisions (switch)
}
/*###########################################################################
# STEP 3: Write case for channel = NBC (NBC is a constant defined to equal 5)
#
This should look almost identical to step 2.
###########################################################################*/
case NBC:
//If channel = NBC (NBC = 5)
{
printf("NBC %d\n", channel); //Display string "NBC 5" followed by newline
break;
//Prevent fall through to next case
}
1421 CPL
Slide 170
Lab 06
Making Decisions (switch)
1421 CPL
Slide 171
Lab 06
Conclusions
1421 CPL
Slide 172
Loops
1421 CPL
Slide 173
for Loop
Syntax
1421 CPL
Slide 174
for Loop
Flow Diagram
Syntax
i = 0
expression1
Modify loop
variable
expression3
Test loop variable for
exit condition
i < n
i++
TRUE
expression2?
statement
FALSE
END
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 175
for Loop
Example (Code Fragment)
int i;
for (i = 0; i < 5; i++)
{
printf(
printf
("Loop
Loop iteration %d\
%d\n
n", i);
}
Expected Output:
Loop
Loop
Loop
Loop
Loop
iteration
iteration
iteration
iteration
iteration
0
1
2
3
4
1421 CPL
Slide 176
for Loop
Any or all of the three expressions may be
left blank (semi-colons must remain)
If expression1 or expression3 are
missing, their actions simply disappear
If expression2 is missing, it is assumed
to always be true
Note
Infinite Loops
A for loop without any
expressions will execute
indefinitely (can leave loop
via break statement)
2010 Microchip Technology Incorporated. All Rights Reserved.
for ( ; ; )
{
}
1421 CPL
Slide 177
while Loop
Syntax
while (expression
expression)
) statement
1421 CPL
Slide 178
while Loop
Flow Diagram
Syntax
while (expression
expression)
) statement
TRUE
FALSE
1421 CPL
Slide 179
while Loop
Example
Example (Code Fragment)
int i = 0;
Loop counter
incremented manually
inside loop
while (i < 5)
{
printf(
printf
("Loop iteration %d
%d\
\n"
n",
, i++);
}
Expected Output:
Loop
Loop
Loop
Loop
Loop
iteration
iteration
iteration
iteration
iteration
0
1
2
3
4
1421 CPL
Slide 180
while Loop
The expression must always be there,
unlike with a for loop
while is used more often than for when
implementing an infinite loop, though it is
only
l a matter
tt off personall taste
t t
Frequently used for main loop of program
Note
Infinite Loops
A while loop with
expression = 1 will execute
indefinitely (can leave loop
via break statement)
2010 Microchip Technology Incorporated. All Rights Reserved.
while (1)
{
}
1421 CPL
Slide 181
do-while Loop
Syntax
1421 CPL
Slide 182
do-while Loop
Flow Diagram
Syntax
expression?
FALSE
END
1421 CPL
Slide 183
do-while Loop
Example
Example (Code Fragment)
int i = 0;
do
{
Loop counter
incremented manually
inside loop
printf("Loop
printf(
Loop iteration %d\
%d\n
n",
n"
, i++);
} while (i < 5);
Condition checked at
end of loop iterations
Expected Output:
Loop
Loop
Loop
Loop
Loop
iteration
iteration
iteration
iteration
iteration
0
1
2
3
4
1421 CPL
Slide 184
break Statement
Syntax
break;
break
;
1421 CPL
Slide 185
break Statement
break;
break
;
TRUE
FALSE
1421 CPL
Slide 186
break Statement
Example
Example (Code Fragment)
int i = 0;
while (i < 10
10)
)
Exit from the loop when i = 5.
{
Iteration 6
6--9 will not be executed.
i++;
if (i == 5) break
break;
;
printf(
printf
("Loop iteration %d
%d\
\n"
n",
, i);
}
Expected Output:
Loop
Loop
Loop
Loop
iteration
iteration
iteration
iteration
1
2
3
4
1421 CPL
Slide 187
continue Statement
Syntax
continue;
continue
;
1421 CPL
Slide 188
continue Statement
Flow Diagram Within a while Loop
Syntax
continue;
continue
;
TRUE
FALSE
1421 CPL
Slide 189
continue Statement
Example
Example (Code Fragment)
int i = 0;
while (i < 6)
Skip remaining iteration when i = 2.
{
Iteration 2 will not be completed.
i++;
if (i == 2) continue
continue;
;
printf(
printf
("Loop iteration %d
%d\
\n"
n",
, i);
}
Expected Output:
Loop
Loop
Loop
Loop
iteration
iteration
iteration
iteration
1
3
4
5
1421 CPL
Slide 190
Lab Exercise 7
Loops
1421 CPL
Slide 191
Lab 07
Loops
1421 CPL
Slide 192
Lab 07
Loops
Solution: Step 1
/*###########################################################################
# STEP 1: Create a for loop to iterate the block of code below. The loop
#
should do the following:
#
* Initialize counter1 to 1
#
* Loop as long as counter1 is less than 5
#
* Increment counter1 on each pass of the loop
#
(HINT: for(init; test; action))
###########################################################################*/
//Write the opening line of the for loop
for( counter1 = 1 ; counter1 < 5 ; counter1++)
{
intVariable1 *= counter1;
printf("FOR: intVariable1 = %d, counter1 = %d\n", intVariable1, counter1);
}
//end of for loop block
1421 CPL
Slide 193
Lab 07
Loops
Solution: Step 2
/*###########################################################################
# STEP 2: Create a while loop to iterate the block of code below. The loop
#
should run until charVariable1 is 0.
###########################################################################*/
//Loop as long as charVariable1 is not 0
while( charVariable1 != 0)
{
charVariable1--;
charVariable2 += 5;
printf("WHILE: charVariable1 = %d, charVariable2 = %d\n",
charVariable1, charVariable2);
}
//end of while loop block
1421 CPL
Slide 194
Lab 07
Loops
Solution: Step 3
/*###########################################################################
# STEP 3: Create a do...while loop to iterate the block of code below.
#
The loop should run until counter1 is greater than 100
###########################################################################*/
###########################################################################
/
do
//Write opening line of do loop
{
counter1 += 5;
counter2 = counter1 * 3;
printf("DO: counter1 = %d, counter2 = %d\n", counter1, counter2);
} while(counter1 <= 100);
//Write closing line of loop - test counter1
//end of do...while block
1421 CPL
Slide 195
Lab 07
Conclusions
1421 CPL
Slide 196
Functions
1421 CPL
Slide 197
Functions
Program Structure
main()
{
...
eat();
...
drink();
...
}
eat()
{
...
return;
}
drink()
{
...
be_merry();
return;
}
1421 CPL
be_merry()
{
...
return;
}
Slide 198
Functions
What is a Function?
Definition
1421 CPL
Slide 199
Functions
Remember Algebra Class?
f(x) = x2 + 4
f(x
4xx +3
3
Function Parameter
1421 CPL
Slide 200
Functions
Definitions
Syntax
Data type of
return expression
Parameter List
(optional)
Name
type identifier
identifier(
(type1 arg1,,typen argn)
{
declarations
Body
statements
return expression
expression;
;
}
Header
1421 CPL
Slide 201
Functions
Function Definitions: Syntax Examples
Example
int maximum
maximum(
(int x, int y)
{
int z;
z = (x
(x >= y) ? x : y;
return
t
z;
int maximum
maximum(
(int x, int y)
{
return ((
((x
x >= y) ? x : y);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 202
Functions
Function Definitions: Return Data Type
Syntax
type identifier
identifier(
(type1 arg1,,typen argn)
{
declarations
statements
return expression
expression;
;
}
1421 CPL
Slide 203
Functions
Function Definitions: Return Data Type
int bigger(
bigger(int a, int b)
{
if (a > b)
return 1;
else
return 0;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 204
Functions
Function Definitions: Return Data Type
void identifier
identifier(
(type1 arg1,,typen argn)
{
declarations
statements
return;
return
; may be omitted if
return;
return
;
nothing is being returned
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 205
Functions
Function Definitions: Parameters
type identifier
identifier(
(type1 arg1,,typen argn)
{
declarations
Function Parameters
statements
return expression
expression;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 206
Functions
Function Definitions: Parameters
int maximum
maximum(
(int x, int y)
{
return ((
((x
x >= y) ? x : y);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 207
Functions
Function Definitions: Parameters
Example
type identifier(
identifier(void
void)
)
{
declarations
statements
return expression
expression;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 208
Functions
How to Call/Invoke a Function
Function Call Syntax
1421 CPL
Slide 209
Functions
Function Prototypes
1421 CPL
Slide 210
Functions
Function Prototypes
int maximum
maximum(
(int x, int y);
int maximum
maximum(
(int
int,
, int
int);
);
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 211
Functions
Declaration and Use: Example 1
Example 1
int a = 5, b = 10
10,
, c;
int maximum
maximum(
(int x, int y)
{
((x
x >= y) ? x : y);
return ((
}
Function is
declared and
defined before it
is used in main()
int main
main(
(void
void)
)
{
c = maximum
maximum(
(a, b);
printf(
printf
("The max is %d\
%d\n"
n",
, c)
}
1421 CPL
Slide 212
Functions
Declaration and Use: Example 2
Example 2
int a = 5, b = 10
10,
, c;
int maximum
maximum(
(int x, int y);
int main
main(
(void
void)
)
{
c = maximum
maximum(
(a, b);
printf(
printf
("The max is %d\
%d\n"
n",
, c)
}
int maximum
maximum(
(int x, int y)
{
return ((
((x
x >= y) ? x : y);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Function is
declared with
prototype before
use in main()
Function is
defined after it is
used in main()
Slide 213
Functions
Passing Parameters by Value
1421 CPL
Slide 214
Functions
Passing Parameters by Value
Example
int a, b, c;
int foo
foo(
(int x, int y)
{
x = x + (++
(++y
y);
return
t
x;
The
}
int
{
a
b
c
}
main(
main
(void
void)
)
= 5;
= 10
10;
;
= foo
foo(
(a, b);
1421 CPL
Slide 215
Functions
Recursion
1421 CPL
Slide 216
Functions
Evaluation of Recursive Functions
Evaluation of 5!
(based on code from previous slide)
Recursive
iterations of
function
Partial results
pushed on stack
Factorial term
replaced with result
of expression above
Result
evaluated from
TOS downward
1! = 1
2! = 2 * 1!
=1
=3*2=6
[3]
3! = 3 * 2!
4! = 4 * 3!
[4]
5! = 5 * 4!
= 5 * 24 = 120
[0]
[1]
[2]
=2*1=2
= 4 * 6 = 24
1421 CPL
Slide 217
int n;
long int factorial(int n){}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 218
int x, y, z;
int foo(
foo(int n)
{
int a;
1421 CPL
Slide 219
int x;
int foo
foo(
(int n)
{
int a;
return (a +=
}
int main
main(
(void
void)
)
{
x = foo
foo(
(5);
x = a;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
n);
n)
;
Slide 220
int x = 5;
int foo
foo(
(int y)
{
int z = 1;
return (x + y + z);
)
}
int main
main(
(void
void)
)
{
int a = 2;
x = foo
foo(
(a);
a = foo
foo(
(x);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 221
int n;
int n;
int foo(
foo(int n)
{
y += n;
local n
hides
}
global n
int foo(
foo(int x)
{
y += n;
1421 CPL
Slide 222
Different functions
may use the same
parameter names
The function will
only use its own
parameter by that
name
Example
int n;
int foo(
foo(int n)
{
y += n;
}
int bar(
bar(int n)
{
z *= n;
}
1421 CPL
Slide 223
#define x 2
void test(void
test(void)
)
{
#define x 5
printf(
printf
("%d
"%d\
\n"
n",
, x);
}
void main(
main(void
void)
)
{
printf(
printf
("%d
"%d\
\n"
n",
, x);
test();
test
();
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
5
5
Why?
Remember: #define is
used by the preprocessor
to do text substitution
before the code is
compiled.
Slide 224
Functions
Historical Note
1421 CPL
Slide 225
Lab Exercise 8
Functions
1421 CPL
Slide 226
Lab 08
Functions
1421 CPL
Slide 227
Lab 08
Functions
Solution: Step 1
/*############################################################################
# STEP 1: Write two function prototypes based on the following information:
#
+ Function Name: multiply_function()
#
- Parameters: int x, int y
#
- Return type: int
#
+ Function Name: divide_function()
#
- Parameters: float x, float y
#
- Return type: float
############################################################################*/
int multiply_function( int x, int y);
//multiply_function() prototype
//divide_function() prototype
1421 CPL
Slide 228
Lab 08
Functions
Solution: Step 2
/*############################################################################
# STEP 2: Call the multiply_function() and divide_function().
#
(a) Pass the variables intVariable1 and intVariable2 to the
#
multiply_function().
#
(b) Store the result of multiply_function() in the variable "product".
#
(c) Pass the variables floatVariable1 and floatVariable2 to the
#
divide_function().
#
(d) Store the result of divide_function() in the variable "quotient".
############################################################################*/
//Call multiply_function
product = multiply_function( intVariable1 , intVariable2 );
//Call divide_function
quotient = divide_function( floatVariable1 , floatVariable2 );
// intQuotient will be 0 since it is an integer
intQuotient = divide_function( floatVariable1 , floatVariable2 );
1421 CPL
Slide 229
Lab 08
Functions
1421 CPL
Slide 230
Lab 08
Conclusions
1421 CPL
Slide 231
1421 CPL
Slide 232
1421 CPL
Slide 233
1421 CPL
Slide 234
1421 CPL
Slide 235
int main(void)
{
...
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 236
1421 CPL
Slide 238
int foo(
foo(int x)
{
extern int a;
...
return a;
}
int a;
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 239
SomeFileInProject.c
extern int x;
int x;
int main(void)
{
x = 5;
...
}
int foo(void)
{
...
}
1421 CPL
Slide 240
1421 CPL
Slide 241
1421 CPL
Slide 242
SomeFileInProject.c
int foo(void);
int foo(void)
{
...
}
int main(void)
{
...
x = foo();
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 243
SomeFileInProject.c
int foo(void);
int main(void)
{
...
x = foo();
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 244
LibFile.h
INCLUDE
DECLARATIONS
Main.c
#include <LibFile.h>
int foo(void);
int x;
int main(void)
{
x = foo();
myVar = x;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
LibFile.c
int myVar;
int foo(void)
{
DEFINITIONS
USE
1421 CPL
Slide 245
Lab Exercise 9
Multi-File Projects
1421 CPL
Slide 246
Lab 09
Multi-File Projects
1421 CPL
Slide 247
Lab 09
Multi-File Projects
1421 CPL
Slide 248
Lab 09
Multi-File Projects
Solution: Step 2a and 2b (File2_09.h)
/*############################################################################
# STEP 2a: Add variable declarations to make the variables defined in
#
File2_09.c available to any C source file that includes this header
#
file.(floatVariable1, floatVariable2, quotient, intQuotient)
############################################################################*/
//Reference to externally defined "floatVariable1"
extern float floatVariable1;
//Reference to externally defined "floatVariable2"
extern float floatVariable2;
//Reference to externally defined "quotient"
extern float quotient;
//Reference to externally defined "intQuotient"
extern int intQuotient;
/*############################################################################
# STEP 2b: Add a function prototype to make divide_function() defined in
#
File2_09.c available to any C source file that includes this header
#
file.
############################################################################*/
//Function prototype for divide_function()
float divide_function(float x, float y );
1421 CPL
Slide 249
Lab 09
Conclusions
1421 CPL
Slide 250
Arrays
1421 CPL
Slide 251
Arrays
Definition
Arrays are variables that can store many items of the same
type.. The individual items known as elements
type
elements,, are stored
sequentially and are uniquely identified by the array index
(sometimes called a subscript
subscript)).
Arrays:
A
May contain any number of elements
Elements must be of the same type
The index is zero based
Array size (number of elements) must be
specified at declaration
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 252
Arrays
How to Create an Array
type arrayName
arrayName[
[size
size];
];
int a[10]
a[10];
;
char s[25]
s[25];
;
1421 CPL
Slide 253
Arrays
How to Initialize an Array at Declaration
type arrayName
arrayName[
[size
size]
] = {item
{item1,,itemn};
yp of the array
y
The items must all match the type
Example
1421 CPL
Slide 254
Arrays
How to Use an Array
arrayName[
arrayName
[index
index]
]
int i, a[10
10];
];
for(i = 0; i < 10
for(
10;
; i++) {
a[i] = 0;
//Initialize all array elements to 0
}
a[4] = 42
42;
;
//Set fifth element to 42
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 255
Arrays
Creating Multidimensional Arrays
type arrayName
arrayName[
[size1]...[
]...[size
sizen];
int a[10
10][
][10
10];
];
float b[10
10][
][10
10][
][10
10];
];
1421 CPL
Slide 256
Arrays
Initializing Multidimensional Arrays at Declaration
type arrayName
arrayName[
[size0][
][size
sizen] =
{{item
{{
item,
,,item
item},
},
{item
item,
,,item
item}};
}};
Example
char a[3][
][3
3] = {{
{{'X'
'X',
, 'O'
'O',
, 'X'
'X'},
},
{'O'
'O',
, 'O'
'O',
, 'X'
'X'},
},
{'X'
'X',
, 'X'
'X',
, 'O'
'O'}};
}};
int b[2][
][2
2][
][2
2] = {{{0
{{{0, 1},{
},{2
2, 3}},{{
}},{{4
4, 5},{
},{6
6, 7}}};
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 257
Arrays
Visualizing 2-Dimensional Arrays
Row 2
a[0][0]
a[0][1]
a[0][2]
a[1][0]
a[1][1]
a[1][2]
a[2][0]
a[2][1]
a[2][2]
=
=
=
=
=
=
=
=
=
0;
1;
2;
3;
4;
5;
6;
7;
8;
0,0
Row
Row 1
Row 0
0,1
4
1,0
0,2
5
1,1
7
2,0
1,2
8
2,1
2,2
y
1421 CPL
Slide 258
Arrays
Visualizing 3-Dimensional Arrays
=
=
=
=
=
=
=
=
0;
1;
2;
3;
4;
5;
6;
7;
0
Row
Plane 0
Plane 1
a[0][0][0]
a[0][0][1]
a[0][1][0]
a[0][1][1]
a[1][0][0]
a[1][0][1]
a[1][1][0]
a[1][1][1]
a[z][y][x]
1
y
0
2
0
5
1
3
1
1421 CPL
Slide 259
Arrays
Example of Array Processing
/**************************************************
* Print out 0 to 90 in increments of 10
**************************************************/
int main
main(
(void
void)
)
{
int i = 0;
int a[10
10]
] = {0
{0,1,2,3,4,5,6,7,8,9};
while (i < 10
10)
)
{
a[i] *= 10
10;
;
printf(
printf
("%d
"%d\
\n"
n",
, a[
a[i]);
i++;
}
while (1);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 260
Strings
Character Arrays and Strings
Definition
Strings:
S i
Are enclosed in double quotes "string"
Are terminated by a null character '\0'
Must be manipulated as arrays of characters
(treated element by element)
May be initialized with a string literal
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 261
Strings
Creating a String Character Array
char arrayName
arrayName[
[length
length];
];
length must be one larger than the length of the string
to accommodate the terminating null character '\0'
\0
A char array with n elements holds strings with n-1 char
Example
char str1
str1[
[10
10];
];
char str2
str2[
[6];
1421 CPL
Slide 262
Strings
How to Initialize a String at Declaration
char arrayName
arrayName[]
[] = "Microchip"
"Microchip";
;
char str1
str1[]
[] = "Microchip"
"Microchip";
; //10 chars "Microchip\
"Microchip\0"
char str2
str2[
[6] = "Hello"
"Hello";
;
1421 CPL
Slide 263
Strings
How to Initialize a String in Code
arrayName[0] = char1;
arrayName[
arrayName[
arrayName
[1] = char2;
arrayName[
arrayName
[n] = '\0'
0';
;
Null character '\0' must be appended manually
Example
str[0]
str[
str[
str
[1]
str[
str
[2]
str[
str
[3]
str[
str
[4]
str[
str
[5]
=
=
=
=
=
=
'H';
'H';
'e';
'e'
;
'l';
'l'
;
'l';
'l'
;
'o';
'o'
;
'\0'
0';
;
1421 CPL
Slide 264
Strings
Comparing Strings
char str
str[]
[] = "Hello"
"Hello";
;
if (!strcmp
strcmp(( str
str,
, "Hello"
"Hello"))
))
printf(
printf
("The string is \"%s
"%s\
\".
".\
\n"
n",
, str
str);
);
1421 CPL
Slide 265
Functions
Array Parameters
1421 CPL
Slide 266
Lab Exercise 10
Arrays
1421 CPL
Slide 267
Lab 10
Arrays
1421 CPL
Slide 268
Lab 10
Arrays
Solution: Step 1
/*############################################################################
# STEP 1: Create two initialized arrays with 10 elements each named array1 and
#
array2 (you may use the pre-defined constant ARRAY_SIZE as part of
#
the array declaration).
#
The arrays should be initialized with the following values:
#
+ array1: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
#
+ array2: 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#
Note: the elements are all of type int
############################################################################*/
// array1 declaration & definition
int array1[ARRAY_SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// array2 declaration & definition
int array2[ARRAY_SIZE] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
1421 CPL
Slide 269
Lab 10
Arrays
Solution: Step 2
/*############################################################################
# STEP 2: Pass the two arrays you declared above (array1 & array2) to the
#
function add_function() (see its definition below). Store the
#
result of the function call in the array result[]. The idea here is
#
to add each corresponding element of array1 and array2 and store the
#
result in result[]. In other words, add the first element of
#
array1[] to the first element of array2[] and store the result in
#
the first element of result[]. Next add the second elements
############################################################################*/
// result = sum of elements of array1 & array2
result[i] = add_function(array1[i], array2[i]);
i++;
1421 CPL
Slide 270
Lab 10
Conclusions
1421 CPL
Slide 271
Data Pointers
1421 CPL
Slide 272
Pointers
A Variable's Address versus A Variable's Value
Variable name
from C code
int x;
Value of
variable x
= 0x0123
2010 Microchip Technology Incorporated. All Rights Reserved.
005A
0123
DEAD
BEEF
F00D
0456
1421 CPL
0x0800
0x0802
0x0804
0x0806
0x0808
Address of
variable x
= 0x0802
0x080A
Slide 273
Pointers
What are Pointers?
Variable at
Address
Add
Integer Variable: x
Pointer Variable: p
FFFF
0123
FFFF
0802
FFFF
FFFF
1421 CPL
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
Slide 274
Pointers
What Do They Do?
Direct Access
via x
x = 0x0123;
*p = 0x0123;
Address
x
p
Indirect Access
via *p
2010 Microchip Technology Incorporated. All Rights Reserved.
005A
0123
DEAD
0802
F00D
0456
1421 CPL
0x0800
0x0802
0x0804
0x0806
0x0808
p points to x
0x080A
Slide 275
Pointers
Why Would I Want to Do That?
1421 CPL
Slide 276
Pointers
Why Would I Want to Do That?
Example: Data Buffer
16--bit Data Memory
16
(RAM)
Address
0123
4567
89AB
CDEF
1357
9BDF
0246
8ACE
Pseudo--code:
Pseudo
(1) Point arrow to first
address of buffer
(2) Write data from UART to
location pointed to by
arrow
(3) Move arrow to point to
next address in buffer
(4) Repeat until data from
UART is 0, or buffer is full
(arrow points to last
address of buffer)
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 277
Pointers
Where Else Are They Used?
1421 CPL
Slide 278
Pointers
How to Create a Pointer Variable
Syntax
type *ptrName
ptrName;
;
In the context of a declaration, the * merely indicates
that the variable is a pointer
yp is the type
yp of data the p
y point
p
type
pointer may
to
Pointer usually described as a pointer to type
Example
int *iPtr
iPtr;
;
float *fPtr
fPtr;
;
1421 CPL
Slide 279
Pointers
How to Create a Pointer Type with typedef
Syntax
intPtr p;
p;
No * is used
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 280
Pointers
Initialization
p = &x
& x;
This assigns the address of the variable x
to the pointer p (p now points to x)
Note: p must be declared to point to the
type of x (e.g. int x; int *p;)
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 281
Pointers
Usage
y = *p
*p;
This assigns to the variable y, the value of
what p is pointing to (x from the last slide)
Using *p, is the same as using the variable
it points to (e.g. x)
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 282
Pointers
Another Way To Look At The Syntax
Example
int x, *p;
p = &x
&x;
;
*p = 5;
1421 CPL
Slide 283
Pointers
Another Way To Look At The Syntax
Example
int x, *p;
p = &x;
*p = 5;
5;
1421 CPL
Slide 284
Pointers
How Pointers Work
Example
{
int x, y;
int *p;
Variable at
Address
x
y
p
x = 0xDEAD
0xDEAD;
;
y = 0xBEEF;
0xBEEF;
p = &x;
*p = 0x0100
0x0100;
;
p = &y;
*p = 0x0200
0x0200;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0000
0000
0000
0000
0000
0000
0000
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 286
Pointers
How Pointers Work
Example
{
int x, y;
int *p;
Variable at
Address
x
y
p
x = 0xDEAD
0xDEAD;
;
y = 0xBEEF;
0xBEEF;
p = &x;
*p = 0x0100
0x0100;
;
p = &y;
*p = 0x0200
0x0200;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
DEAD
0000
0000
0000
0000
0000
0000
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 287
Pointers
How Pointers Work
Example
{
int x, y;
int *p;
Variable at
Address
x
y
p
x = 0xDEAD
0xDEAD;
;
y = 0xBEEF;
0xBEEF;
p = &x;
*p = 0x0100
0x0100;
;
p = &y;
*p = 0x0200
0x0200;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
DEAD
BEEF
0000
0000
0000
0000
0000
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 288
Pointers
How Pointers Work
Example
{
int x, y;
int *p;
Variable at
Address
x
y
p
x = 0xDEAD
0xDEAD;
;
y = 0xBEEF;
0xBEEF;
p = &x
&x;
;
*p = 0x0100
0x0100;
;
p = &y;
*p = 0x0200
0x0200;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
DEAD
BEEF
08BC
0000
0000
0000
0000
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 289
Pointers
How Pointers Work
Example
{
int x, y;
int *p;
Variable at
Address
x
y
p
x = 0xDEAD
0xDEAD;
;
y = 0xBEEF;
0xBEEF;
p = &x;
*p = 0x0100
0x0100;
;
p = &y;
*p = 0x0200
0x0200;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0100
BEEF
08BC
0000
0000
0000
0000
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 290
Pointers
How Pointers Work
Example
{
int x, y;
int *p;
Variable at
Address
x
y
p
x = 0xDEAD
0xDEAD;
;
y = 0xBEEF;
0xBEEF;
p = &x;
*p = 0x0100
0x0100;
;
p = &y
&y;
;
*p = 0x0200
0x0200;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0100
BEEF
08BE
0000
0000
0000
0000
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 291
Pointers
How Pointers Work
Example
{
int x, y;
int *p;
Variable at
Address
x
y
p
x = 0xDEAD
0xDEAD;
;
y = 0xBEEF;
0xBEEF;
p = &x;
*p = 0x0100
0x0100;
;
p = &y;
*p = 0x0200
0x0200;
;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0100
0200
08BE
0000
0000
0000
0000
0x08BA
0x08BC
0x08BE
0x08C0
0x08C2
0x08C4
0x08C6
0x08C8
Slide 292
FFFF
0001
0002
0003
FFFF
Address
0x07FE
0x0800
0x0802
0x0804
0x0806
1421 CPL
Slide 293
1421 CPL
Slide 294
x[0]
x[1]
x[2]
p
FFFF
0001
0002
0003
FFFF
Address
0x07FE
0x0800
0x0802
0x0804
0x0806
1421 CPL
Slide 295
x[0]
x[1]
x[2]
p
FFFF
0001
0002
0003
0800
Address
0x07FE
0x0800
0x0802
0x0804
0x0806
1421 CPL
Slide 296
x[0]
x[1]
x[2]
p
FFFF
0001
0002
0003
0802
Address
0x07FE
0x0800
0x0802
0x0804
0x0806
1421 CPL
Slide 297
Pointer Arithmetic
Incrementing Pointers
1421 CPL
Slide 298
Pointer Arithmetic
Incrementing Pointers
Example
float *ptr;
0x0050
ptr = &a;
ptr++;
float a[0]
0x0052
0x0054
0x0056
float a[1]
0x0058
0x005A
float a[2]
0x005C
0 005E
0x005E
float a[3]
0x0060
float a[5]
0x0062
0x0064
0x0066
0x0068
float a[6]
0x006A
0x006C
float a[7]
0x006E
0x0070
float a[4]
0x0072
float a[8]
16-bit Data Memory Words
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0x0074
0x0076
Slide 299
Pointer Arithmetic
Larger Jumps
1421 CPL
Slide 300
Pointer Arithmetic
Larger Jumps
Example
float *ptr;
0x0050
ptr = &a;
float a[0]
0x0052
0x0054
0x0056
float a[1]
0x0058
0x005A
float a[2]
0x005C
0 005E
0x005E
float a[3]
0x0060
float a[5]
0x0062
0x0064
0x0066
0x0068
float a[6]
0x006A
0x006C
float a[7]
0x006E
0x0070
float a[4]
0x0072
float a[8]
16-bit Data Memory Words
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0x0074
0x0076
Slide 301
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
0001
0000
0002
0000
0003
0000
0800
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 302
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x
&x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
0005
0000
0002
0000
0003
0000
0800
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 303
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x
&x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
0005
0000
0002
0000
0003
0000
0804
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 304
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x
&x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
0005
0000
BEEF
DEAD
0003
0000
0804
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 305
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x
&x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
0005
0000
BEEF
DEAD
0003
0000
0808
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 306
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x
&x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
0005
0000
BEEF
DEAD
F00D
F1D0
0808
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 307
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x
&x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
0005
0000
BEEF
DEAD
F00D
F1D0
0800
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 308
Pointers
Pointer Arithmetic
Example
16--bit Data Memory
16
(RAM)
{
long x
x[
[3] = {1
{1,2,3};
long *p = &x
&x;
*p += 4;
p++;
*p = 0xDEADBEEF
0xDEADBEEF;
;
p++;
*p = 0xF1D0F00D
0xF1D0F00D;
;
p -= 2;
*p = 0xBADF00D1
0xBADF00D1;
;
Address
x[0]
x[1]
x[2]
p
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0x07FE
00D1
BADF
BEEF
DEAD
F00D
F1D0
0800
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 309
Pointers
Post-Increment/Decrement Syntax Rule
*p++
*(p++)
(*p)++
Operation
Description by Example
z = *(p
*(p++);
is equivalent to:
Post-Increment
PostPointer
z = *p;
p = p + 1;
z = (*p
(*p)++;
)++;
Post-Increment
Postdata pointed to
by Pointer
is equivalent to:
z = *p;
*p = *p + 1;
1421 CPL
Slide 310
Pointers
Post-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x;
x[0]
x[1]
y = 5 + *(p
*(p++);
x[2]
y = 5 + (*p
(*p)++;
p
}
y
Remember:
*(p++) is the same as *p++
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0002
0003
0800
0000
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 311
Pointers
Post-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(p++);
x[2]
y = 5 + (*p
(*p)++;
p
}
y
Remember:
*(p++) is the same as *p++
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0002
0003
0800
0006
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 312
Pointers
Post-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(p++
*(p++);
);
x[2]
y = 5 + (*p
(*p)++;
p
}
y
Remember:
*(p++) is the same as *p++
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0002
0003
0802
0006
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 313
Pointers
Post-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(p
*(p++);
x[2]
y = 5 + (*p
(*p)++;
)++;
p
}
y
Remember:
*(p++) is the same as *p++
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0002
0003
0802
0007
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 314
Pointers
Post-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(p
*(p++);
x[2]
y = 5 + (*p
(*p)
)++
++;
;
p
}
y
Remember:
*(p++) is the same as *p++
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0003
0003
0802
0007
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 315
Pointers
Pre-Increment/Decrement Syntax Rule
++*p
*(++p)
++(*p)
Operation
Description by Example
z = *(++p
*(++p);
is equivalent to:
Pre-Increment
PrePointer
p = p + 1;
z = *p;
z = ++(*p
++(*p);
);
Pre-Increment
Predata pointed to
by Pointer
is equivalent to:
*p = *p + 1;
z = *p;
1421 CPL
Slide 316
Pointers
Pre-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x;
x[0]
x[1]
y = 5 + *(++p
*(++p);
x[2]
y = 5 + ++(*p
++(*p);
p
}
y
Remember:
*(++p) is the same as *++p
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0002
0003
0800
0000
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 317
Pointers
Pre-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(++p
*(++p);
);
x[2]
y = 5 + ++(*p
++(*p);
p
}
y
Remember:
*(++p) is the same as *++p
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0002
0003
0802
0000
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 318
Pointers
Pre-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(++
(++p
p);
x[2]
y = 5 + ++(*p
++(*p);
p
}
y
Remember:
*(++p) is the same as *++p
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0002
0003
0802
0007
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 319
Pointers
Pre-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(++p
*(++p);
x[2]
y = 5 + ++
++(
(*p
*p);
);
p
}
y
Remember:
*(++p) is the same as *++p
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0003
0003
0802
0007
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 320
Pointers
Pre-Increment/Decrement Syntax
Example
{
int x[3] = {1
{1,2,3};
int y;
int *p = &x
&x;
;
x[0]
x[1]
y = 5 + *(++p
*(++p);
x[2]
y = 5 + ++(*p
++(*p);
);
p
}
y
Remember:
*(++p) is the same as *++p
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
0000
0001
0003
0003
0802
0008
0000
0000
0x07FE
0x0800
0x0802
0x0804
0x0806
0x0808
0x080A
0x080C
Slide 321
Pointers
Pre- and Post- Increment/Decrement Summary
1421 CPL
Slide 322
Pointers
Initialization Tip
int *p = NULL;
NUL is the character '\0' but NULL is the value of a
pointer that points to nowhere
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 323
Lab Exercise 11
Pointers and Pointer Arithmetic
1421 CPL
Slide 324
Lab 11
Pointers and Pointer Arithmetic
1421 CPL
Slide 325
Lab 11
Pointers and Pointer Arithmetic
1421 CPL
Slide 326
Lab 11
Pointers and Pointer Arithmetic
/*############################################################################
# STEP 4: Increment the value that p points to.
############################################################################*/
//Increment array element's
element s value
(*p)++;
printf("y[%d] = %d\n", i, *p);
/*############################################################################
# STEP 5: Increment the pointer p so that it points to the next item.
############################################################################*/
//Increment pointer to next array element
p++;
1421 CPL
Slide 327
Lab 11
Conclusions
1421 CPL
Slide 328
int square(
)
square(int n
n)
{
return (n * n);
}
int main(
main(void
void)
)
{
y = square
square(
(x);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
y=4
x=2
x was not changed by function
1421 CPL
Slide 329
1421 CPL
Slide 330
int foo(int *q
*q)
)
foo(p
foo(
p)
q = &x
q = p
1421 CPL
Slide 331
We know where
you live!
void swap
swap(
(int *n1
n1,
, int *n2
n2)
)
{
int temp
temp;
;
temp = *n1
*n1;
;
*n1 = *n2
*n2;
;
*n2 = temp
temp;
;
Addresses of parameters
copied to local pointer
variables: Function can
now modify the original
variables via pointers.
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 332
and y live
n1 = &x
n2 = p
swap(
swap
(&x
&x,
, p);
while(
while
(1);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
Slide 333
Address
str
I P
\0 C
1421 CPL
91C0
0x08C2
49 50
00 43
0x91C0
0x91C2
Slide 334
str += 4
Increment or add an offset to the pointer to
access subsequent characters
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 335
*(str
*(
str + 4) == 'o'
Pointer always points to "base address"
Offsets used to access subsequent chars
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 336
char
*str
"PIC";
;
h
t = "PIC"
char str
str[]
[] = "PIC"
PIC ;
"PIC";
or
char str
str[
[4] = "PIC"
"PIC";
;
1421 CPL
Slide 337
char *str
str;
;
char str
str[
[4];
str = "PIC"
"PIC";
;
str[0]
str[
str[
str
[1]
str[
str
[2]
str[
str
[3]
=
=
=
=
'P';
'P';
'I';
'I'
;
'C';
'C'
;
'\0'
0';
;
1421 CPL
Slide 338
1421 CPL
Slide 339
strcmp() prototype:
Function Prototype
int strcmp
strcmp(
(const char *s1
s1,
, const char *s2
s2);
);
1421 CPL
Slide 340
#include <string.h
string.h>
>
char *str = "Microchip"
"Microchip";
;
int main(
main(void
void)
)
{
if (0 == strcmp(str, "Microchip"))
"Microchip"))
printf(
printf
("They match!\
match!\n"
n");
);
while(
while
(1);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 341
Arrays of Pointers
Declaration
char *p[4];
This creates an array of 4 pointers to char
The array p[] itself is like any other array
The elements of p[], such as p[1], are
pointers to char
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 342
Arrays of Pointers
Array Elements are Pointers Themselves
16--bit Data Memory
16
(RAM)
91C0
p[0]
p[1]
p[2]
p[3]
0000
91C0
91C3
91C7
91CC
0000
0000
0000
O n \0
91C3
O f f \0
91C7
M a i n \0
91CC
A u x \0
1421 CPL
Slide 343
Arrays of Pointers
Initialization
p[0] = &x
&x;
Or, when working with strings:
1421 CPL
Slide 344
Arrays of Pointers
Dereferencing
y = *p[0]
p[0];
p[0]
;
*p[0];
Using *p[0] is the same as using the
object it points to, such as x or the string
literal "My String" from the previous
slide
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 345
Arrays of Pointers
Accessing Strings
Example
int i = 0;
char *str
str[]
[] = {
{"Zero"
"Zero",
, "One"
"One",
, "Two"
"Two",
,
"Three",
"Three"
, "Four"
"Four",
, "\0"};
0"};
int main(
main(void
void)
)
{
while(*
while
(*str
str[
[i] != '\0')
0')
printf(
printf
("%s
"%s\
\n"
n",
, str
str[
[i++]);
while(
while
(1);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 346
Lab Exercise 12
Pointers, Arrays, and Functions
1421 CPL
Slide 347
Lab 12
Pointers, Arrays, and Functions
1421 CPL
Slide 348
Lab 12
Pointers, Arrays, and Functions
/*############################################################################
# STEP1: Pass the variable x to the function twosComplement such that the
#
value of x itself may be changed by the function. Note: The function
#
expects a pointer (address) as its parameter.
############################################################################*/
//Perform twos complement on x
twosComplement(&x);
/*############################################################################
# STEP 2: Pass the array 'a' to the function reverse1(). Use the constant
#
ARRAY_SIZE for the second parameter.
#
See definition of function reverse1() below.
############################################################################*/
//Reverse order of elements by passing array
reverse1(a, ARRAY_SIZE);
1421 CPL
Slide 349
Lab 12
Pointers, Arrays, and Functions
1421 CPL
Slide 350
Lab 12
Conclusions
1421 CPL
Slide 351
Function Pointers
1421 CPL
Slide 352
Function Pointers
Pointers may also be used to point to
functions
Provides a more flexible way to call a
function, by providing a choice of which
function
f
ti to
t call
ll
Makes it possible to pass functions to
other functions
Not extremely common, but very useful in
the right situations
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 353
Function Pointers
Declaration
1421 CPL
Slide 354
Function Pointers
Initialization
int (*fp
(*fp)(
)(int
int x); //Function pointer
int foo
foo(
(int x);
//Function prototype
We can initialize the function pointer like this:
fp = foo
foo;
;
1421 CPL
Slide 355
Function Pointers
Calling a Function via a Function Pointer
1421 CPL
Slide 356
Function Pointers
Passing a Function to a Function
Example 1: Understanding the Mechanism
int x;
int foo(
foo(int
int a, int b);
int bar(
bar(int
int a, int b);
//Function prototype
//Function prototype
1421 CPL
Slide 357
Function Pointers
Passing a Function to a Function
Example 2: Evaluate a Definite Integral (approximation)
float integral
integral(
(float a, float b, float (*
(*f
f)(
)(float
float))
))
{
bounds of integral
function to be evaluated
float sum = 0.0
0.0;
;
b
float x;
y=
f(x) dx
a
int n;
1421 CPL
Slide 358
Lab Exercise 13
Function Pointers
1421 CPL
Slide 359
Lab 13
Function Pointers
1421 CPL
Slide 360
Lab 13
Function Pointers
1421 CPL
3 Run
Halt
Slide 361
Lab 13
Function Pointers
Results
= x2 + C [0,1]
= 0.500000
y2 = x2 dx
= x3 + C [0,1]
= 0.335000
y3 = x3 dx
= x4 + C [0,1]
= 0.252500
1421 CPL
Slide 362
Lab 13
Function Pointers
1421 CPL
Slide 363
Lab 13
Function Pointers
/*============================================================================
FUNCTION:
integral()
DESCRIPTION: Evaluates the integral of the function passed to it over the
interval a to b.
PARAMETERS:
interval end points a & b and function to integrate
RETURNS:
integral of function f over interval a to b
REQUIREMENTS: none
SOURCE:
Adapted from example at:
http://en.wikipedia.org/wiki/Function_pointer
============================================================================*/
float integral(float a, float b, float (*f)(float))
{
float sum = 0.0;
float x;
int n;
//Evaluate integral{a,b} f(x) dx
for (n = 0; n <= 100; n++)
{
x = ((n / 100.0) * (b-a)) + a;
sum += (f(x) * (b-a)) / 101.0;
}
return sum;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 364
Lab 13
Conclusions
1421 CPL
Slide 365
Structures
1421 CPL
Slide 366
Structures
Definition
Structures:
S
May contain any number of members
Members may be of any data type
Allow group of related variables to be treated
as a single unit, even if different types
Ease the organization of complicated data
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 367
Structures
How to Create a Structure Definition
Syntax
struct structName
{
type1 memberName1;
...
typen memberNamen;
}
Example
// Structure to handle complex numbers
struct complex
{
float re
re;
;
// Real part
float im
im;
;
// Imaginary part
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 368
Structures
How to Declare a Structure Variable (Method 1)
Syntax
struct structName
{
type1 memberName1;
...
typen memberNamen;
} varName
N
...,
,varName
N
1,...
n;
Example
// Structure to handle complex numbers
struct complex
{
float re
re;
;
float im
im;
;
} x, y;
y;
// Declare x and y of type complex
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 369
Structures
How to Declare a Structure Variable (Method 2)
Syntax
Example
struct complex
{
float re
re;
;
float im
im;
;
}
...
struct complex x, y;
2010 Microchip Technology Incorporated. All Rights Reserved.
Slide 370
Structures
How to Use a Structure Variable
Syntax
structVariableName.memberName
Example
struct complex
{
float re
re;
;
float im
im;
;
} x, y;
y;
int main
main(
(void
void)
)
{
x.re = 1.25
1.25;
;
x.im = 2.50
2.50;
;
y = x;
...
1421 CPL
Slide 371
Structures
How to Create a Structure Type with typedef
Syntax
1421 CPL
Slide 372
Structures
How to Declare a Structure Type Variable
Syntax
1421 CPL
Slide 373
Structures
How to Initialize a Structure Variable at Declaration
Syntax
Slide 374
Structures
Nesting Structures
Example
typedef struct
{
float x;
float y;
} point
point;
;
typedef struct
{
point a;
point b;
} line
line;
;
int main
main(
(void
void)
)
{
line m;
m;
m.a.x = 1.2
1.2;
;
m.a.y = 7.6
7.6;
;
m.b.x = 38.5
38.5;
;
m.b.y = 17.8
17.8;
;
...
2010 Microchip Technology Incorporated. All Rights Reserved.
y
(xb, yb) = (38.5, 17.8)
point
m
line
point
1421 CPL
Slide 375
Structures
Arrays and Pointers with Strings
Strings:
May be assigned directly to char array
member only at declaration
May be assigned directly to a pointer to char
member at any time
Example: Structure
struct strings
{
char a[4]
a[4];
;
char *b
*b;
;
} str
str;
;
int main(
main(void
void)
)
{
str.a[
str.a
[0] = B
B;
;
str.a[
str.a
[1] = a
a;
;
str.a[
str.a
[2] = d
d;
;
str.a[
str.a
[3] = \0
0;
;
str.b = Good
Good;
;
1421 CPL
Slide 376
Structures
How to Declare a Pointer to a Structure
typeName *ptrName
ptrName;
;
- or struct structName *ptrName
ptrName;
;
Example 1
Example 2
typedef struct
{
float re
re;
;
float im
im;
;
} complex
complex;
;
...
complex *p
*p;
;
struct complex
{
float re
re;
;
float im
im;
;
}
...
struct complex *p
*p;
;
1421 CPL
Slide 377
Structures
How to Use a Pointer to Access Structure Members
ptrNameptrName
->memberName
Pointer must first be initialized to point to the address of the
structure itself: ptrName = &structVariable
structVariable;
;
Example: Definitions
Example: Usage
typedef struct
{
float re
re;
;
float im
im;
;
} complex
complex;
; //complex type
...
complex x;
x; //complex var
complex *p
*p;
; //ptr to complex
int main
main(
(void
void)
)
{
p = &x;
&x;
//Set x.re = 1.25 via p
p->re = 1.25
1.25;
;
//Set x.im = 2.50 via p
p->im = 2.50
2.50;
;
}
1421 CPL
Slide 378
Structures
Creating Arrays of Structures
typeName arrName
arrName[
[n];
- or struct structName arrName[
arrName[n];
Example
typedef struct
{
float re
re;
;
float im
im;
;
} complex
complex;
;
...
complex a[3];
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 379
Structures
Initializing Arrays of Structures at Declaration
typeName arrName[
arrName[n] = {{
{{list
list1},
},
,{
,{list
listn}};
typedef struct
{
float re
re;
;
float im
im;
;
} complex
complex;
;
...
complex a[3] = {{1.2
{{1.2,
, 2.5
2.5},
}, {3.9
{3.9,
, 6.5
6.5},
}, {7.1
{7.1,
, 8.4
8.4}};
}};
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 380
Structures
Using Arrays of Structures
arrName[
arrName
[n].memberName
Example: Definitions
Example: Usage
typedef struct
{
float re
re;
;
float im
im;
;
} complex
complex;
;
...
complex a[
a[3];
int main
main(
(void
void)
)
{
a[0].re = 1.25
1.25;
;
a[0].im = 2.50
2.50;
;
...
}
1421 CPL
Slide 381
Structures
How to Pass Structures to Functions
Example
typedef struct
{
float re
re;
;
float im
im;
;
} complex
complex;
;
void display
display(
(complex x)
x)
{
printf(
printf
((%f + j%f)\
j%f)\n
n,
, x.re
x.re,
, x.im
x.im);
);
}
int main
main(
(void
void)
)
{
complex a = {1.2
1.2,
, 2.5};
2.5};
complex b = {3.7
3.7,
, 4.0
4.0};
};
display(a);
display(
display(
display
(b);
1421 CPL
Slide 382
Lab Exercise 14
Structures
1421 CPL
Slide 383
Lab 14
Structures
1421 CPL
Slide 384
Lab 14
Structures
1421 CPL
Slide 385
Lab 14
Conclusions
1421 CPL
Slide 386
Lab Exercise 15
Arrays of Structures
1421 CPL
Slide 387
Lab 15
Arrays of Structures
1421 CPL
Slide 388
Lab 15
Arrays of Structures
/*############################################################################
# STEP 1: Multiply the real (re) part of each array element by 10
#
HINT: Use *=
############################################################################*/
//Multiply re part of current array element by 10
x[i].re *= 10;
/*############################################################################
# STEP 2: Multiply the imaginary (im) part of each array element by 5
#
HINT: Use *=
############################################################################*/
//Multiply im part of current array element by 5
x[i].im *= 5;
1421 CPL
Slide 389
Lab 15
Conclusions
1421 CPL
Slide 390
Unions
1421 CPL
Slide 391
Unions
Definition
Unions:
U i
May contain any number of members
Members may be of any data type
Are as large as their largest member
Use exactly the same syntax as structures
except struct is replaced with union
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 392
Unions
How to Create a Union
Syntax
union unionName
{
type1 memberName1;
...
typen memberNamen;
}
Example
// Union of char, int and float
union mixedBag
{
char a;
int b;
float c;
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 393
Unions
How to Create a Union Type with typedef
Syntax
1421 CPL
Slide 394
Unions
How Unions Are Stored In Memory
Space allocated
for x is size of
float
0x800
0x802
0x804
mixedBag x;
x;
2010 Microchip Technology Incorporated. All Rights Reserved.
0x7FF
1421 CPL
Slide 395
Unions
How Unions Are Stored In Memory
x.a only
occupies the
lowest byte of
the union
0x800
0x802
0x804
mixedBag x;
x;
2010 Microchip Technology Incorporated. All Rights Reserved.
0x7FF
1421 CPL
Slide 396
Unions
How Unions Are Stored In Memory
x.b only
occupies the
lowest two
bytes of the
union
0x800
0x802
0x804
mixedBag x;
x;
2010 Microchip Technology Incorporated. All Rights Reserved.
0x7FF
1421 CPL
Slide 397
Unions
How Unions Are Stored In Memory
x.c occupies
all four bytes of
the union
0x800
0x802
0x804
mixedBag x;
x;
2010 Microchip Technology Incorporated. All Rights Reserved.
0x7FF
1421 CPL
Slide 398
Lab Exercise 16
Unions
1421 CPL
Slide 399
Lab 16
Unions
1421 CPL
Slide 400
Lab 16
Unions
/*############################################################################
# STEP 1: Set the int member of unionVar equal to 16877.
############################################################################*/
//Set intVar = 16877
unionVar.intVar = 16877;
/*############################################################################
# STEP 2: Set the float member of unionVar equal to 6.02e23.
############################################################################*/
//Set floatVar = 6.02e23
unionVar.floatVar = 6.02e23;
1421 CPL
Slide 401
Lab 16
Conclusions
1421 CPL
Slide 402
Bit Fields
1421 CPL
Slide 403
Bit Fields
Definition
Bit
Fields:
Bi Fi
ld
Are ordinary members of a structure
Have a specified bit width
Are often used in conjunction with unions to
provide bit access to a variable without
masking operations
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 404
Bit Fields
How to Create a Bit Field
Syntax
struct structName
{
unsigned int memberName1: bitWidth
bitWidth;
;
...
unsigned int memberNamen: bitWidth
bitWidth;
;
}
Example
typedef struct
{
unsigned int
unsigned int
unsigned int
unsigned int
unsigned int
} byteBits
byteBits;
;
bit0: 1;
1;
bit1to3: 3;
3;
bit4: 1;
1;
bit5: 1;
1;
bit6to7: 2;
2;
bitfield struct
may be declared
normally or as a
typedef
1421 CPL
Slide 405
Bit Fields
How to Use a Bit Field
Example
struct byteBits
{
unsigned a: 1;
1;
unsigned b: 1;
1;
unsigned c: 2;
2;
unsigned d: 1;
1;
unsigned e: 3;
3;
} x;
int main
main(
(void
void)
)
{
x.a = 1;
x.b = 0;
x.c = 0b10
0b10;
;
x.d = 0x0
0x0;
;
x.e = 7;
}
//x.a
//x.b
//x.c
//x.d
//x.e
may
may
may
may
may
contain
contain
contain
contain
contain
1421 CPL
values
values
values
values
values
from
from
from
from
from
0
0
0
0
0
to
to
to
to
to
1
1
3
1
7
Slide 406
Lab Exercise 17
Bit Fields
1421 CPL
Slide 407
Lab 17
Bit Fields
1421 CPL
Slide 408
Lab 17
Bit Fields
1421 CPL
3 Run
Halt
Slide 409
Lab 17
Bit Fields
1421 CPL
Slide 410
Lab 17
Bit Fields
Demo Results 1
bitByte.fullByte = 0x55;
1421 CPL
Slide 411
Lab 17
Bit Fields
Demo Results 2
bitByte.bitField.bit0 = 0;
1421 CPL
Slide 412
Lab 17
Bit Fields
Demo Results 3
bitByte.bitField.bit2 = 0;
1421 CPL
Slide 413
Lab 17
Bit Fields
Demo Results 4
bitByte.bitField.bit7 = 1;
1421 CPL
Slide 414
Lab 17
Conclusions
1421 CPL
Slide 415
Enumerations
1421 CPL
Slide 416
Enumerations
Definition
Enumerations:
E
i
Are unique integer data types
May only contain a specified list of values
Values are specified as symbolic constants
1421 CPL
Slide 417
Enumerations
How to Create an Enumeration Type
enum
en m typeName
t peName {label0, label1,,labeln}
Where compiler sets label0 = 0, label1 = 1, labeln = n
Example
1421 CPL
Slide 418
Enumerations
How to Create an Enumeration Type
enum
en m typeName
t peName {label0 = const0,,labeln}
Where compiler sets label0 = const0, label1 = (const
(const0 + 1), ...
Example
1421 CPL
Slide 419
Enumerations
How to Declare an Enumeration Type Variable
Declared independently:
Syntax
1421 CPL
Slide 420
Enumerations
How to Declare a Tagless Enumeration Variable
enum {const
const-list
list}
} varName1,,varNamen;
enum {SUN
SUN,
, MON
MON,
, TUE
TUE,
, WED
WED,
, THR
THR,
, FRI
FRI,
, SAT
SAT}
} today
today;
;
1421 CPL
Slide 421
Enumerations
How to Declare an Enumeration Type with typedef
1421 CPL
Slide 422
Enumerations
How to Use an Enumeration Type Variable
varName = labeln;
The labels may be used as any other symbolic constant
yp must be used in
Variables defined as enumeration types
conjunction with the types labels or equivalent integer
Example
enum weekday {SUN
SUN,
, MON
MON,
, TUE
TUE,
, WED
WED,
, THR
THR,
, FRI
FRI,
, SAT
SAT};
};
enum weekday day
day;
;
day = WED
WED;
;
day = 6;
if (day == WED
WED)
)
{
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 423
Lab Exercise 18
Enumerations
1421 CPL
Slide 424
Lab 18
Enumerations
1421 CPL
Slide 425
Lab 18
Enumerations
1421 CPL
3 Run
Halt
Slide 426
Lab 18
Enumerations
BandStopFilter();
LowPassFilter();
HighPassFilter();
BandPassFilter();
break;
break;
break;
break;
while(1);
}
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 427
Lab 18
Conclusions
1421 CPL
Slide 428
1421 CPL
Slide 429
Macros
M
Are evaluated by the preprocessor
Are not executable code themselves
Can control the generation of code before the
compilation process
Provide shortcuts
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 430
1421 CPL
Slide 431
#define label
label(
(arg1,,argn) code
The code must fit on a single line or use '\' to split lines
Text substitution used to insert arguments into code
Each instance of label() will be expanded into code
This is not the same as a C function!
Example
1421 CPL
Slide 432
Example
x = square(i++);
expands to:
x = ((i++)*(i++));
So i gets incremented twice, not
once at the end as expected.
1421 CPL
Slide 433
Lab Exercise 19
Macros with #define
1421 CPL
Slide 434
Lab 19
#define Macros
1421 CPL
Slide 435
Lab 19
#define Macros
1421 CPL
3 Run
Halt
Slide 436
Lab 19
#define Macros
/*============================================================================
FUNCTION:
main()
============================================================================*/
int main(void)
{
x = square(3);
printf("x = %d\n", x);
SPBRG = BaudRate(9600, 16);
printf("SPBRG = %d\n", SPBRG);
}
1421 CPL
Slide 437
Lab 19
Conclusions
1421 CPL
Slide 438
Resources
A Selection of C Compilers
1421 CPL
Slide 439
Resources
Books General C Language
1421 CPL
Slide 440
Resources
Books General C Language
Practical C Programming
3rd Edition (August 1, 1997)
Steve Oualline
ISBN-10: 1565923065
ISBN-13: 978-1565923065
Code Complete
2nd Edition (June 2004)
Steve McConnell
ISBN-10: 0735619670
ISBN-13: 978-0735619678
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Not about C
specifically, but a
must read for all
software engineers
Slide 441
Resources
Books PIC MCU Specific
PICmicro MCU C:
An Introduction to Programming the Microchip PIC in CCS C
2nd Edition (August 19, 2002)
Nigel Gardner
ISBN-10: 0972418105
ISBN-13: 978-0972418102
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 442
Resources
Books Compiler Specific
1421 CPL
MPLAB C30
is based on the
GCC tool chain
Slide 443
Resources
Books Compiler Specific
S
a d MPLIB Use
s Gu
de
MPASM
MPLINK and
User's
Guide
MPASM
MPLINK
MPLIB
Users Guide
1421 CPL
Slide 444
Thank You!
2010 Microchip Technology Incorporated. All Rights Reserved.
1421 CPL
Slide 445
Trademarks
The Microchip name and logo, the Microchip logo, dsPIC, KeeLoq, KeeLoq logo,
MPLAB, PIC, PICmicro, PICSTART, PIC32 logo, rfPIC and UNI/O are registered
trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor, MXDEV, MXLAB, SEEVAL
and The Embedded Control Solutions Company are registered trademarks of
Microchip Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard, dsPICDEM,
dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense, HI-TIDE,
In Circuit Serial Programming
In-Circuit
Programming, ICSP
ICSP, Mindi
Mindi, MiWi
MiWi, MPASM
MPASM, MPLAB Certified logo
logo,
MPLIB, MPLINK, mTouch, Octopus, Omniscient Code Generation, PICC,
PICC-18, PICDEM, PICDEM.net, PICkit, PICtail, REAL ICE, rfLAB, Select Mode,
Total Endurance, TSHARC, UniWinDriver, WiperLock and ZENA are trademarks of
Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
All other trademarks mentioned herein are property of their respective companies.
2010, Microchip Technology Incorporated, All Rights Reserved.
1421 CPL
Slide 446