Professional Documents
Culture Documents
IDE
Debug Tool
C Source Files
Assembly Source Files
Assembly Source Files
Object
Files
Object File Libraries
(Archives)
Linker Script
COFF
Debug File
Executable
Memory Map
Compiler
Driver
Program
Assembler
(.asm or .s)
(.lib or .a)
(.lkr or .gld)
(.asm or .s)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 10 1317 CPL
Development Tools Data Flow
C Compiler
Compiler
C Source File C Header File
Preprocessor
.s
Assembly Source File
.h .c
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 11 1317 CPL
C Runtime Environment
C Compiler sets up a runtime environment
Allocates space for stack
Initialize 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)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 12 1317 CPL
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
User modifiable if absolutely necessary
Details will be covered in compiler specific
classes
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 13 1317 CPL
Example
Fundamentals of C
A Simple C Program
#i ncl ude <st di o. h>
#def i ne PI 3. 14159
i nt mai n( voi d)
{
f l oat r adi us, ar ea;
/ / Cal cul at e ar ea of ci r cl e
r adi us = 12. 0;
ar ea = PI * r adi us * r adi us;
pr i nt f ( " Ar ea = %f ", ar ea) ;
}
Header File
Function
Variable Declarations
Constant Declaration
(Text Substitution Macro)
Comment
Preprocessor
Directives
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 14 1317 CPL
Comments
Comments
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 15 1317 CPL
Definition
Comments
Two kinds of comments may be used:
Block Comment
/* This is a comment */
Single Line Comment
// This is also a comment
Comments
Comments
are used to document a program's functionality
are used to document a program's functionality
and to explain what a particular block or line of code does.
and to explain what a particular block or line of code does.
Comments are ignored by the compiler, so you can type
Comments are ignored by the compiler, so you can type
anything you want into them.
anything you want into them.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 16 1317 CPL
Comments
Using Block Comments
Block comments:
Begin with
/*
/*
and end with
*/
*/
May span multiple lines
/******************************************************** /********************************************************
* Program: hello.c * Program: hello.c
* Author: R. Ostapiuk * Author: R. Ostapiuk
********************************************************/ ********************************************************/
#include #include < <stdio.h stdio.h> >
/* Function: main() */ /* Function: main() */
int int
main main( (void void) )
{ {
printf printf( ( Hello, world! Hello, world!\ \n n ); ); /* Display /* Display Hello, world! Hello, world!
*/ */
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 17 1317 CPL
Comments
Using Single Line Comments
Single line comments:
Begin with
//
//
and run to the end of the line
May not span multiple lines
//======================================================= //=======================================================
// Program: hello.c // Program: hello.c
// Author: R. Ostapiuk // Author: R. Ostapiuk
//======================================================= //=======================================================
#include #include < <stdio.h stdio.h> >
// Function: main() // Function: main()
int int
main main( (void void) )
{ {
printf printf( ( Hello, world! Hello, world!\ \n n ); ); // Display // Display Hello, world! Hello, world!
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 18 1317 CPL
Comments
Nesting Comments
Block comments may not be nested within
other delimited comments
Single line comments may be nested
/* /*
code here code here // Comment within a comment // Comment within a comment
*/ */
/* /*
code here code here /* Comment within a comment */ /* Comment within a comment */
code here code here /* Comment within a /* Comment within a
oops! */ oops! */
*/ */
Example: Single line comment within a delimited comment. Example: Single line comment within a delimited comment.
Example: Delimited comment within a delimited comment. Example: Delimited comment within a delimited comment.
Delimiters don Delimiters don t match up as intended! t match up as intended!
Dangling delimiter causes compile error Dangling delimiter causes compile error
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 19 1317 CPL
Comments
Best Practices
/******************************************************** /********************************************************
* Program: hello.c * Program: hello.c
* Author: R. Ostapiuk * Author: R. Ostapiuk
********************************************************/ ********************************************************/
#include #include < <stdio.h stdio.h> >
/******************************************************** /********************************************************
* Function: main() * Function: main()
********************************************************/ ********************************************************/
int int
main main( (void void) )
{ {
/* /*
int i; int i;
// Loop count variable // Loop count variable
char *p; // Pointer to text string char *p; // Pointer to text string
*/ */
printf printf( ( Hello, world! Hello, world!\ \n n ); ); // Display // Display Hello, world! Hello, world!
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 20 1317 CPL
Variables, Identifiers
and Data Types
Variables, Identifiers
and Data Types
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 21 1317 CPL
Example
Variables and Data Types
A Simple C Program
Variable Declarations
Data
Types
Variables
in use
#i ncl ude <st di o. h>
#def i ne PI 3. 14159
i nt mai n( voi d)
{
f l oat r adi us, ar ea;
/ / Cal cul at e ar ea of ci r cl e
r adi us = 12. 0;
ar ea = PI * r adi us * r adi us;
pr i nt f ( " Ar ea = %f ", ar ea) ;
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 22 1317 CPL
Variables
A variable may be thought of as a container that
can hold data used in a program
Definition
A
A
variable
variable
is a name that represents one or more
is a name that represents one or more
memory locations used to hold program data.
memory locations used to hold program data.
int
myVariable;
myVariable =
5;
m
y
V
a
r
ia
b
le
5
5
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 23 1317 CPL
41
16
41
16
Variables
5.74532370373175
5.74532370373175
10
-44
10
-44
0 15
Data Memory (RAM)
int
warp_factor;
float
length;
char
first_letter;
A
Variables are names for
storage locations in
memory
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 24 1317 CPL
float
length;
char
first_letter;
int
warp_factor;
41
16
41
16
Variables
5.74532370373175
5.74532370373175
10
-44
10
-44
0 15
Data Memory (RAM)
A
Variable declarations
consist of a unique
identifier
(name)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 25 1317 CPL
float
length;
char
first_letter;
int
warp_factor;
41
16
41
16
Variables
5.74532370373175
5.74532370373175
10
-44
10
-44
0 15
Data Memory (RAM)
A
and a data type
Determines size
Determines how values
are interpreted
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 26 1317 CPL
Example of Identifiers in a Program
Identifiers
Names given to program elements:
Variables, Functions, Arrays, Other
elements
#i ncl ude <st di o. h>
#def i ne PI 3. 14159
i nt mai n( voi d)
{
f l oat r adi us, ar ea;
/ / Cal cul at e ar ea of ci r cl e
r adi us = 12. 0;
ar ea = PI * r adi us * r adi us;
pr i nt f ( " Ar ea = %f ", ar ea) ;
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 27 1317 CPL
Identifiers
Valid characters in identifiers:
Case sensitive!
Only first 31 characters significant*
I d e n t i f i e r
First Character
_
(underscore)
A to Z
a to z
Remaining Characters
_
(underscore)
A to Z
a to z
0 to 9
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 28 1317 CPL
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
Some compiler implementations may define
additional keywords
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 29 1317 CPL
Data Types
Fundamental Types
The size of an int
varies from compiler to compiler
MPLAB
C30 int
is 16-bits
MPLAB C18 int
is 16-bits
CCS PCB, PCM & PCH int
is 8-bits
HI-TECH PICC Compiler int
is 16-bits
Type Description Bits
char
char
int
int
float
float
double
double
single character single character
integer integer
single precision floating point number single precision floating point number
double precision floating point number double precision floating point number
16 16
8 8
32 32
64 64
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 30 1317 CPL
Data Type Qualifiers
Modified Integer Types
Qualifiers: unsigned, signed, short
and long
Qualified Type Min Max Bits
unsigned
char
char, signed
char
unsigned
short
int
short
int, signed short
int
unsigned
int
int, signed
int
unsigned long
int
long
int, signed long
int
unsigned long long
int
long long
int,
signed long long
int
0
-128
0
-32768
0
-32768
0
-2
31
0
-2
63
255
127
65535
32767
65535
32767
2
31
-1
2
63
-1
2
32
-1
2
64
-1
8
8
16
16
16
16
32
64
32
64
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 31 1317 CPL
Data Type Qualifiers
Modified Floating Point Types
MPLAB
C30:
(1)
doubl e is equivalent to l ong
doubl e if f no- shor t - doubl e is used
MPLAB C30 Uses the IEEE-754 Floating Point Format
MPLAB C18 Uses a modified IEEE-754 Format
Qualified Type Absolute Min Bits
float
float
double
double
long double
long double
~10 ~10
- -44.85 44.85
~10 ~10
- -44.85 44.85
~10 ~10
- -323.3 323.3
32 32
32 32
64 64
Absolute Max
~10 ~10
38.53 38.53
~10 ~10
38.53 38.53
~10 ~10
308.3 308.3
(1) (1)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 32 1317 CPL
Variables
How to Declare a Variable
A variable must be declared before it can be
used
The compiler needs to know how much space to
allocate and how the values should be handled
Syntax
type
type
identifier
identifier
1 1
, identifier
, identifier
2 2
,
,
,identifier
,identifier
n n
;
;
Example
int
int
x
x
,
,
y
y
,
,
z
z
;
;
float
float
warpFactor
warpFactor
;
;
char
char
text_buffer[10]
text_buffer[10]
;
;
unsigned
unsigned
index
index
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 33 1317 CPL
Syntax
Variables
How to Declare a Variable
Variables may be declared in a few ways:
type
type
identifier
identifier
;
;
type
type
identifier
identifier
=
=
InitialValue
InitialValue
;
;
type
type
identifier
identifier
1 1
,
,
identifier
identifier
2 2
,
,
identifier
identifier
3 3
;
;
type
type
identifier
identifier
1 1
=
=
Value
Value
1 1
,
,
identifier
identifier
2 2
=
=
Value
Value
2 2
;
;
One declaration on a line One declaration on a line
One declaration on a line with an initial value One declaration on a line with an initial value
Multiple declarations of the same type on a line Multiple declarations of the same type on a line
Multiple declarations of the same type on a line with initial va Multiple declarations of the same type on a line with initial values lues
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 34 1317 CPL
Examples
Variables
How to Declare a Variable
unsigned int
unsigned int
x
x
;
;
unsigned
unsigned
y
y
=
=
12
12
;
;
int
int
a
a
,
,
b
b
,
,
c
c
;
;
long int
long int
myVar
myVar
=
=
0x12345678
0x12345678
;
;
long
long
z
z
;
;
char
char
first
first
=
=
'a'
'a'
,
,
second
second
,
,
third
third
=
=
'c'
'c'
;
;
float
float
big_number
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. myLongVar Name).
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 35 1317 CPL
Variables
How to Declare a Variable
Sometimes, variables (and other program
elements) are declared in a separate file
called a header file
Header file names customarily end in .h
Header files are associated
with a program through the
#include
directive
MyProgram.h
MyProgram.c
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 36 1317 CPL
#include
Directive
Three ways to use the #include
directive:
Syntax
#include
#include
<file.h>
<file.h>
Look for file in the compiler search path Look for file in the compiler search path
The compiler search path usually includes the compiler's directo The compiler search path usually includes the compiler's directory ry
and all of its subdirectories. and all of its subdirectories.
For example: C: For example: C:\ \Program Files Program Files\ \Microchip Microchip\ \MPLAB C30 MPLAB C30\ \*.* *.*
#include
#include
file.h
file.h
Look for file in project directory only Look for file in project directory only
#include
#include
c:
c:
\
\
MyProject
MyProject
\
\
file.h
file.h
Use specific path to find include file Use specific path to find include file
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 37 1317 CPL
main.h main.c
#include
Directive
main.h Header File and main.c Source File
unsigned int
unsigned int
a;
a;
unsigned int
unsigned int
b;
b;
unsigned int
unsigned int
c;
c;
#include
#include
"main.h"
"main.h"
int
int
main(
main(
void
void
)
)
{
{
a =
a =
5
5
;
;
b =
b =
2
2
;
;
c = a+b;
c = a+b;
}
}
The contents of main.h The contents of main.h
are are effectively effectively pasted into pasted into
main.c starting at the main.c starting at the
#include #include
directive directive s line s line
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 38 1317 CPL
main.c
#include
Directive
Equivalent main.c File
Equivalent main.c file Equivalent main.c file
without without #include #include
unsigned int
unsigned int
a;
a;
unsigned int
unsigned int
b;
b;
unsigned int
unsigned int
c;
c;
int
int
main(
main(
void
void
)
)
{
{
a =
a =
5
5
;
;
b =
b =
2
2
;
;
c = a+b;
c = a+b;
}
}
After the preprocessor
runs, this is how the
compiler sees the
main.c file
The contents of the
header file arent
actually copied to your
main source file, but it
will behave as if they
were copied
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 39 1317 CPL
Lab Exercise 1
Lab Exercise 1
Variables and Data Types
Variables and Data Types
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 40 1317 CPL
Lab 01
Variables and Data Types
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab01
Lab01
\
\
Lab01.mcw
Lab01.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 41 1317 CPL
Lab 01
Variables and Data Types
Compile and run the code:
2
2
Click on the
Click on the
Build All
Build All
button.
button.
Compile (Build All) Compile (Build All) Run Run 2
2
3
3
3
3 If no errors are reported,
If no errors are reported,
click on the
click on the
Run
Run
button.
button.
Halt Halt 4
4
4
4
Click on the
Click on the
Halt
Halt
button.
button.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 42 1317 CPL
Lab 01
Variables and Data Types
Expected Results (1):
5
5 The
The
SIM Uart1
SIM Uart1
window should show the text that
window should show the text that
is output by the program, indicating the sizes of
is output by the program, indicating the sizes of
C
C
\
\
n"
n"
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 63 1317 CPL
Symbolic Constants
Symbolic Constants
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 64 1317 CPL
Symbolic Constants
Constants
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 (!!??)
Definition
A
A
constant
constant
or a
or a
symbolic constant
symbolic constant
is a label that
is a label that
represents a literal. Anywhere the label is encountered
represents a literal. Anywhere the label is encountered
in code, it will be interpreted as the value of the literal it
in code, it will be interpreted as the value of the literal it
represents.
represents.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 65 1317 CPL
Some texts on C declare constants like:
This is not efficient for an embedded
system: A variable is allocated in program
memory, but it cannot be changed due to
the const
keyword
This is not the traditional use of const
In the vast majority of cases, it is better to
use #define
for constants
Symbolic Constants
Constant Variables Using const
Example
const
const
float
float
PI
PI
=
=
3.141593
3.141593
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 66 1317 CPL
Symbolic Constants
Text Substitution Labels Using #define
Defines a text substitution label
Syntax
#define
#define
label text
label text
Example
#define
#define
PI
PI
3.14159
3.14159
#define
#define
mol
mol
6.02E23
6.02E23
#define
#define
MCU
MCU
"PIC24FJ128GA010"
"PIC24FJ128GA010"
#define
#define
COEF 2 * PI
COEF 2 * PI
Each instance of label will be replaced with text by the
preprocessor unless label is inside a string
No memory is used in the microcontroller
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 67 1317 CPL
Example
Note: a #define
directive is NEVER
terminated with a semi-colon (;), unless
you want that to be part of the text
substitution.
Symbolic Constants
#define
Gotchas
#define
#define
MyConst
MyConst
5
5
;
;
c
c
=
=
MyConst
MyConst
+
+
3
3
;
;
c
c
=
=
5
5
; +
; +
3
3
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 68 1317 CPL
Example
Symbolic Constants
Initializing Variables When Declared
#define
#define
CONSTANT1
CONSTANT1
5
5
const
const
CONSTANT2
CONSTANT2
=
=
10
10
;
;
int
int
variable1
variable1
=
=
CONSTANT1
CONSTANT1
;
;
int
int
variable2
variable2
;
;
// Cannot do: int variable2 = CONSTANT2
// Cannot do: int variable2 = CONSTANT2
A constant declared with const
may not
be used to initialize a global or static
variable when it is declared (though it may
be used to initialize local variables)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 69 1317 CPL
Lab Exercise 2
Lab Exercise 2
Symbolic Constants
Symbolic Constants
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 70 1317 CPL
Lab 02
Symbolic Constants
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab02
Lab02
\
\
Lab02.mcw
Lab02.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 71 1317 CPL
Lab 02
Symbolic Constants
Compile and run the code:
2
2
Click on the
Click on the
Build All
Build All
button.
button.
Compile (Build All) Compile (Build All) Run Run 2
2
3
3
3
3 If no errors are reported,
If no errors are reported,
click on the
click on the
Run
Run
button.
button.
Halt Halt 4
4
4
4
Click on the
Click on the
Halt
Halt
button.
button.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 72 1317 CPL
Lab 02
Symbolic Constants
Expected Results (1):
5
5 The
The
SIM Uart1
SIM Uart1
window should show the text that
window should show the text that
is output by the program, indicating the values of
is output by the program, indicating the values of
the two symbolic constants in the code.
the two symbolic constants in the code.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 73 1317 CPL
Lab 02
Symbolic Constants
Expected Results (2):
6
6 The watch window should show the two symbolic
The watch window should show the two symbolic
constants declared in code.
constants declared in code.
CONSTANT1
CONSTANT1
was
was
declared with
declared with
#define
#define
, and therefore uses no
, and therefore uses no
memory.
memory.
CONSTANT2
CONSTANT2
was declared with
was declared with
const
const
and is stored as an immutable variable in flash
and is stored as an immutable variable in flash
program memory.
program memory.
CONSTANT1 CONSTANT1
has has
no no
address address
CONSTANT2 CONSTANT2
has a has a
program memory program memory
address ( ) address ( )
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 74 1317 CPL
Lab 02
Symbolic Constants
Expected Results (3):
7
7 If we look in the program memory window, we
If we look in the program memory window, we
can find
can find
CONSTANT2
CONSTANT2
which was created with
which was created with
const
const
at address 0x011D0 (as was shown in the
at address 0x011D0 (as was shown in the
watch window)
watch window)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 75 1317 CPL
Lab 02
Symbolic Constants
Expected Results (4):
8
8 If we open the map file (in the lab02 project
If we open the map file (in the lab02 project
directory), we can see that memory has been
directory), we can see that memory has been
allocated for
allocated for
CONSTANT2
CONSTANT2
at 0x011D0, but nothing
at 0x011D0, but nothing
has been allocated for
has been allocated for
CONSTANT1
CONSTANT1
.
.
External Symbols in Program Memory (by name):
0x0011d0 _CONSTANT2
0x000e16 __Atexit
0x000b9c __Closreg
0x00057c __DNKfflush
0x0012d8 __DefaultInterrupt
CONSTANT1
does not appear anywhere in the map file
lab02.map
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 76 1317 CPL
Lab 02
Conclusions
Constants make code more readable
Constants improve maintainability
#define should be used to define
constants
#define constants use no memory, so they
may be used freely
const should never be used in this context
(it has other uses)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 77 1317 CPL
printf() Library Function
printf() Library Function
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 78 1317 CPL
printf()
Standard Library Function
Used to write text to the "standard output"
Normally a computer monitor or printer
Often the UART in embedded systems
SIM Uart1 window in MPLAB
IDE SIM
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 79 1317 CPL
printf()
Standard Library Function
Syntax
printf
printf
(
(
ControlString
ControlString
,
,
arg1
arg1
,
,
argn
argn
);
);
Example
int
int
a
a
=
=
5
5
,
,
b
b
=
=
10
10
;
;
printf
printf
(
(
"a =
"a =
%d
%d
\
\
nb =
nb =
%d
%d
\
\
n"
n"
,
,
a
a
,
,
b
b
);
);
Result: Result:
a = 5
a = 5
b = 10
b = 10
Everything printed verbatim within string except %d's
which are replaced by the argument values from the list
NOTE: the 'd' in %d is the
conversion character.
(See next slide for details)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 80 1317 CPL
printf()
Conversion Characters for Control String
Conversion
Character
Meaning
%c
%c
%s
%s
%d
%d
%o
%o
%u
%u
%x
%x
%X
%X
%f
%f
%e
%e
%E
%E
%g
%g
%G
%G
Single character Single character
String (all characters until ' String (all characters until '\ \0') 0')
Signed decimal integer Signed decimal integer
Unsigned octal integer Unsigned octal integer
Unsigned decimal integer Unsigned decimal integer
Unsigned hexadecimal integer with lowercase digits ( Unsigned hexadecimal integer with lowercase digits (1a5e 1a5e) )
As As x x, but with uppercase digits (e.g. , but with uppercase digits (e.g. 1A5E 1A5E) )
Signed decimal value (floating point) Signed decimal value (floating point)
Signed decimal with exponent (e.g. Signed decimal with exponent (e.g. 1.26e 1.26e- -5 5) )
As As e e, but uses , but uses E E
for exponent (e.g. for exponent (e.g. 1.26E 1.26E- -5 5) )
As As e e
or or f f, but depends on size and precision of value , but depends on size and precision of value
As As g g, but uses , but uses E E
for exponent for exponent
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 81 1317 CPL
printf()
Gotchas
The value displayed is interpreted entirely
by the formatting string:
printf("ASCII = %d", 'a');
will output: ASCII = 97
A more problematic string:
printf("Value = %d", 6.02e23);
will output: Value = 26366
Incorrect results may be displayed if the
format type doesn't match the actual data
type of the argument
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 82 1317 CPL
printf()
Useful Format String Examples for Debugging
Print a 16-bit hexadecimal value with a
"0x" prefix and leading zeros if necessary
to fill a 4 hex digit value:
#
Specifies that a 0x or 0X should precede a hexadecimal value (has
other meanings for different conversion characters)
06
Specifies that 6 characters must be output (including 0x prefix),
zeros will be filled in at left if necessary
x
Specifies that the output value should be expressed as a
hexadecimal integer
printf("Address of x =
printf("Address of x =
%#06x
%#06x
\
\
n", x_ptr);
n", x_ptr);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 83 1317 CPL
printf()
Useful Format String Examples for Debugging
Same as previous, but force hex letters to
uppercase while leaving the 'x' in '0x'
lowercase:
04
Specifies that 4 characters must be output (no longer including 0x
prefix since that is explicitly included in the string), zeros will be
filled in at left if necessary
X
Specifies that the output value should be expressed as a
hexadecimal integer with uppercase A-F
printf("Address of x = 0x
printf("Address of x = 0x
%04X
%04X
\
\
n", x_ptr);
n", x_ptr);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 84 1317 CPL
Lab Exercise 3
Lab Exercise 3
printf() Library Function
printf() Library Function
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 85 1317 CPL
Lab 03
printf()
Library Function
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab03
Lab03
\
\
Lab03.mcw
Lab03.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 86 1317 CPL
Lab 03
printf()
Library Function
Compile and run the code:
2
2
Click on the
Click on the
Build All
Build All
button.
button.
Compile (Build All) Compile (Build All) Run Run 2
2
3
3
3
3 If no errors are reported,
If no errors are reported,
click on the
click on the
Run
Run
button.
button.
Halt Halt 4
4
4
4
Click on the
Click on the
Halt
Halt
button.
button.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 87 1317 CPL
Lab 03
printf()
Library Function
Expected Results (1):
5
5 The
The
SIM Uart1
SIM Uart1
window should show the text that
window should show the text that
is output by the program by
is output by the program by
printf()
printf()
, showing
, showing
the how values are printed based on the
the how values are printed based on the
formatting character used in the control string.
formatting character used in the control string.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 88 1317 CPL
Lab 03
printf()
Library Function
Expected Results (2):
-24058
printf printf( ("'Microchip' as decimal (d): "'Microchip' as decimal (d): %d %d\ \n" n", ,
"Microchip" "Microchip"); );
Microchip
printf printf( ("'Microchip' as string (s): %s "'Microchip' as string (s): %s\ \n" n", ,
"Microchip" "Microchip"); );
26366
printf printf( ("6.02e23 as decimal (d): "6.02e23 as decimal (d): %d %d\ \n" n", ,
6.02e23 6.02e23); );
6.020000e+23
printf printf( ("6.02e23 as exponent (e): %e "6.02e23 as exponent (e): %e\ \n" n", ,
6.02e23 6.02e23); );
16419
2.550000
97
a
25
printf printf( ("2.55 as decimal (d): "2.55 as decimal (d): %d %d\ \n" n", ,
2.55 2.55); );
printf printf( ("2.55 as float (f): %f "2.55 as float (f): %f\ \n" n", ,
2.55 2.55); );
printf printf( ("'a' as decimal (d): "'a' as decimal (d): %d %d\ \n" n", ,
'a' 'a'); );
printf printf( ("'a' as character (c): %c "'a' as character (c): %c\ \n" n", ,
'a' 'a'); );
printf printf( ("25 as decimal (d): %d "25 as decimal (d): %d\ \n" n", ,
25 25); );
Detailed Analysis:
Detailed Analysis:
Line of Code From Demo Project Line of Code From Demo Project Output Output
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 89 1317 CPL
Lab 03
Conclusions
printf() has limited use in embedded
applications themselves
It is very useful as a debugging tool
It can display data almost any way you
want
Projects that use printf() must:
Configure a heap (done in MPLAB
IDE)
Include the stdio.h header file
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 90 1317 CPL
Operators
Operators
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 91 1317 CPL
Definition
Operators
How to Code Arithmetic Expressions
Operands may be variables, constants or
functions that return a value
A microcontroller register is usually treated as
a variable
There are 9 arithmetic operators that may
be used
Binary Operators: +, -, *, /, %
Unary Operators: +, -, ++, --
An
An
arithmetic expression
arithmetic expression
is an expression that contains
is an expression that contains
one or more operands and arithmetic operators.
one or more operands and arithmetic operators.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 92 1317 CPL
Negative Negative
- -
(unary) (unary)
Subtraction Subtraction
- -
Positive Positive
+ +
(unary) (unary)
Modulo Modulo
% %
Addition Addition
+ +
Operators
Arithmetic
NOTE NOTE - -
An An int int
divided by an divided by an int int
returns an returns an int int: :
10/3 = 3 10/3 = 3
Use modulo to get the remainder: Use modulo to get the remainder:
10%3 = 1 10%3 = 1
Multiplication Multiplication
* *
Division Division
/ /
Operator Result Operation Example
- -x x
x x - -
y y
+x +x
x % y x % y
x + y x + y
x * y x * y
x / y x / y
Negative value of Negative value of x x
Difference of Difference of x x
and and y y
Value of Value of x x
Remainder of Remainder of x x
divided by divided by y y
Sum of Sum of x x
and and y y
Product of Product of x x
and and y y
Quotient of Quotient of x x
and and y y
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 93 1317 CPL
Example: Integer Divide Example: Floating Point Divide
Operators
Division Operator
If both operands are an integer type, the result
will be an integer type (int, char)
If one or both of the operands is a floating point
type, the result will be a floating point type (float,
double)
int
int
a
a
=
=
10
10
;
;
int
int
b
b
=
=
4
4
;
;
float
float
c
c
;
;
c
c
=
=
a
a
/
/
b
b
;
;
int
int
a
a
=
=
10
10
;
;
float
float
b
b
=
=
4.0f
4.0f
;
;
float
float
c
c
;
;
c
c
=
=
a / b;
a / b;
c = 2.
c = 2.
0
0
00000
00000
Because: int / int Because: int / int
int int
c = 2.
c = 2.
5
5
00000
00000
Because: float / int Because: float / int
float float
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 94 1317 CPL
Operators
Implicit Type Conversion
In many expressions, the type of one
operand will be temporarily "promoted" to
the larger type of the other operand
A smaller data type will be promoted to the
largest type in the expression for the
duration of the operation
Example
int
int
x
x
=
=
10
10
;
;
float
float
y
y
=
=
2.0
2.0
,
,
z
z
;
;
z
z
=
=
x
x
*
*
y
y
;
;
// x promoted to float
// x promoted to float
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 95 1317 CPL
Operators
Implicit Arithmetic Type Conversion Hierarchy
char
int
unsigned int
long
unsigned long
long long
unsigned long long
float
double
long double
unsigned char
S
m
a
l
l
e
r
t
y
p
e
s
c
o
n
v
e
r
t
e
d
t
o
l
a
r
g
e
s
t
t
y
p
e
i
n
e
x
p
r
e
s
s
i
o
n
short
unsigned short
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 96 1317 CPL
- -x x x x
is promoted to is promoted to int int
int int
5 5
x * x * - -2L 2L x x
is promoted to is promoted to long long
because because - -2L 2L
is a is a long long
long long
10 10
8/x 8/x x x
is promoted to is promoted to int int
int int
- -1 1
8%x 8%x x x
is promoted to is promoted to int int
int int
3 3
8.0/x 8.0/x x x
is promoted to is promoted to double double
because because 8.0 8.0
is a is a double double
double double
- -1.6 1.6
Expression Implicit Type Conversion Expression's Type
Operators
Arithmetic Expression Implicit Type Conversion
Assume x is defined as:
short x =
short x =
-
-
5;
5;
Result
Example implicit type conversions
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 97 1317 CPL
Operators
Applications of the Modulus Operator (%)
Truncation: x % 2
n
where n
is the desired word
width (e.g. 8 for 8 bits: x % 256)
Returns the value of just the lower n-bits of x
Can be used to break apart a number in any base
into its individual digits
Example
#define #define MAX_DIGITS 6 MAX_DIGITS 6
long long number = 123456 number = 123456; ;
int int i i, ,
radix = 10 radix = 10; ; char char digits digits[ [MAX_DIGITS MAX_DIGITS]; ];
for for
( (i i = =
0 0; ;
i i < <
MAX_DIGITS MAX_DIGITS; ;
i i++) ++)
{ {
if if
( (number number == ==
0 0) )
break break; ;
digits digits[ [i i] ]
= =
( (char char)( )(number number % %
radix radix); );
number number /= /=
radix radix; ;
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 98 1317 CPL
Operators
Arithmetic: Increment and Decrement
x
x
=
=
5
5
;
;
y
y
=
=
(
(
x++
x++
) +
) +
5
5
;
;
// y = 10
// y = 10
// x = 6
// x = 6
x
x
=
=
5
5
;
;
y
y
= (
= (
++x
++x
) +
) +
5
5
;
;
// y = 11
// y = 11
// x = 6
// x = 6
Operator Result Operation Example
Decrement Decrement
-- --
Increment Increment
++ ++
x x-- --
-- --x x
x++ x++
++x ++x
Use Use x x
then decrement then decrement x x
by 1 by 1
Decrement Decrement x x
by 1, then use by 1, then use x x
Use Use x x
then increment then increment x x
by 1 by 1
Increment Increment x x
by 1, then use by 1, then use x x
Postfix Example Prefix Example
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 99 1317 CPL
Definition
Operators
How to Code Assignment Statements
Two types of assignment statements
Simple assignment
variable = expression;
The expression is evaluated and the result is
assigned to the variable
Compound assignment
variable = variable op expression;
The variable appears on both sides of the =
An
An
assignment statement
assignment statement
is a statement that assigns a
is a statement that assigns a
value to a variable.
value to a variable.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 100 1317 CPL
>>= >>=
|= |=
<<= <<=
^= ^=
x >>= y x >>= y
x |= y x |= y
x <<= y x <<= y
x ^= y x ^= y
x = x >> y x = x >> y
x = x | y x = x | y
x = x << y x = x << y
x = x ^ y x = x ^ y
&= &=
/= /=
%= %=
- -= =
*= *=
Assignment Assignment
= =
+= +=
x &= y x &= y
x /= y x /= y
x %= y x %= y
x x - -= y = y
x *= y x *= y
x = y x = y
x += y x += y
x = x & y x = x & y
x = x / y x = x / y
x = x % y x = x % y
x = x x = x - -
y y
x = x * y x = x * y
Assign Assign x x
the value of the value of y y
x = x + y x = x + y
Operators
Assignment
Operator Result Operation Example
Assignment Assignment
Compound Compound
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 101 1317 CPL
Statements with the same variable on each
side of the equals sign:
May use the shortcut assignment
operators (compound assignment):
Example
Operators
Compound Assignment
x
x
=
=
x
x
+
+
y
y
;
;
Example
x
x
+=
+=
y
y
;
;
//Increment x by the value y
//Increment x by the value y
This operation may be thought of as: The new value of This operation may be thought of as: The new value of x x
will be will be
set equal to the current value of set equal to the current value of x x
plus the value of plus the value of y y
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 102 1317 CPL
Example
Operators
Compound Assignment
int
int
x
x
=
=
2
2
;
;
//Initial value of x is 2
//Initial value of x is 2
x
x
*=
*=
5
5
;
;
//x = x * 5
//x = x * 5
Before statement is executed:
Before statement is executed:
x
x
= 2
= 2
After statement is executed:
After statement is executed:
x
x
= 10
= 10
x *= 5;
x *= 5;
x = (x * 5);
x = (x * 5);
x = (2 * 5);
x = (2 * 5);
x = 10;
x = 10;
Is equivalent to: Is equivalent to:
Evaluate right side first: Evaluate right side first:
Assign result to Assign result to x x: :
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 103 1317 CPL
Operators
Relational
In conditional expressions, In conditional expressions, any non any non- -zero value zero value
is is
interpreted as TRUE. A value of 0 is always FALSE. interpreted as TRUE. A value of 0 is always FALSE.
Operator Result (FALSE = 0, TRUE
0) Operation Example
Equal to Equal to
== ==
Not equal to Not equal to != !=
Greater than Greater than
> >
Greater than Greater than
or equal to or equal to
>= >=
Less than Less than
< <
Less than or Less than or
equal to equal to
<= <=
x == y x == y
x != y x != y
x > y x > y
x >= y x >= y
x < y x < y
x <= y x <= y
1 if 1 if x x
equal to equal to y y, else 0 , else 0
1 if 1 if x x
not equal to not equal to y y, else 0 , else 0
1 if 1 if x x
greater than greater than y y, else 0 , else 0
1 if 1 if x x
greater than or equal to greater than or equal to y y, ,
else 0 else 0
1 if 1 if x x
less than less than y y, else 0 , else 0
1 if 1 if x x
less than or equal to less than or equal to y y, ,
else 0 else 0
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 104 1317 CPL
Operators
Difference Between =
and ==
=
is the assignment operator
x = 5
assigns the value 5 to the variable x
==
is the 'equals to' relational operator
x == 5
tests whether the value of x
is 5
Be careful not to confuse
Be careful not to confuse
=
=
and
and
==
==
.
.
They are not interchangeable!
They are not interchangeable!
if
if
(
(
x
x
==
==
5
5
)
)
{
{
do if value of
do if value of
x
x
is 5
is 5
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 105 1317 CPL
Example
Operators
Difference Between =
and ==
What happens when the following code is
executed?
void
void
main
main
(
(
void
void
)
)
{
{
int
int
x
x
=
=
2
2
;
;
//Initialize x
//Initialize x
if
if
(
(
x
x
=
=
5
5
)
)
//If x is 5,
//If x is 5,
{
{
printf
printf
(
(
"Hi!"
"Hi!"
);
);
//
//
display "Hi!"
display "Hi!"
}
}
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 106 1317 CPL
Operators
Logical
Logical NOT Logical NOT
! !
Logical OR Logical OR
|| ||
Logical AND Logical AND
&& &&
!x !x
x || y x || y
x && y x && y
1 if 1 if x x
= =
0 0, else 0 , else 0
0 if 0 if both both x x
= =
0 0
and and y y
= =
0 0, ,
else 1 else 1
1 if 1 if both both x x
0 0
and and y y
0 0, ,
else 0 else 0
Operator Result (FALSE = 0, TRUE
0) Operation Example
In conditional expressions, any non-zero value
is
interpreted as TRUE. A value of 0 is always FALSE.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 107 1317 CPL
Operators
Bitwise
Operator Result (for each bit position) Operation Example
Bitwise XOR Bitwise XOR
^ ^
Bitwise NOT Bitwise NOT
(One's Complement) (One's Complement)
~ ~
Bitwise AND Bitwise AND
& &
Bitwise OR Bitwise OR
| |
x ^ y x ^ y
~x ~x
x & y x & y
x | y x | y
1, if 1 in 1, if 1 in x x
or or y y
but not both but not both
0, if 0 or 1 in both 0, if 0 or 1 in both x x
and and y y
1, if 0 in 1, if 0 in x x
0, if 1 in 0, if 1 in x x
1, if 1 in both 1, if 1 in both x x
and and y y
0, if 0 in 0, if 0 in x x
or or y y
or both or both
1, if 1 in 1, if 1 in x x
or or y y
or both or both
0, if 0 in both 0, if 0 in both x x
and and y y
The operation is carried out on each bit of
the first operand with each corresponding
bit of the second operand
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 108 1317 CPL
Operators
Difference Between &
and &&
&
is the bitwise AND operator
0b1010 & 0b1101
0b1000
&&
is the logical AND operator
0b1010 && 0b1101
0b0001 (TRUE)
<Non-Zero Value> &&
<Non-Zero Value> 1
(TRUE)
Be careful not to confuse
Be careful not to confuse
&
&
and
and
&&
&&
.
.
They are not interchangeable!
They are not interchangeable!
if
if
(
(
x
x
&&
&&
y
y
)
)
{
{
do if
do if
x
x
and
and
y
y
are both TRUE (non
are both TRUE (non
-
-
zero)
zero)
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 109 1317 CPL
Operators
Difference Between &
and &&
What happens when each of these code
fragments are executed?
Example 1
Using A Bitwise AND Operator
Example 2
Using A Logical AND Operator
char
char
x
x
=
=
0b1010
0b1010
;
;
char
char
y
y
=
=
0b0101
0b0101
;
;
if
if
(
(
x
x
&&
&&
y
y
)
)
printf
printf
(
(
"Hi!"
"Hi!"
);
);
char
char
x
x
=
=
0b1010
0b1010
;
;
char
char
y
y
=
=
0b0101
0b0101
;
;
if
if
(
(
x
x
&
&
y
y
)
)
printf
printf
(
(
"Hi!"
"Hi!"
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 110 1317 CPL
Operators
Logical Operators and Short Circuit Evaluation
The evaluation of expressions in a logical
operation stops as soon as a TRUE or
FALSE result is known
Example
If we have two expressions being tested in a logical AND operati If we have two expressions being tested in a logical AND operation: on:
expr1
expr1
&&
&&
expr2
expr2
The expressions are evaluated from left to right. If The expressions are evaluated from left to right. If expr1 expr1 is 0 (FALSE), then is 0 (FALSE), then
expr2 expr2 would not be evaluated at all since the overall result is alrea would not be evaluated at all since the overall result is already known dy known
to be false. to be false.
expr1
expr1
expr2
expr2
Result
Result
0
0
X
(0)
X
(0)
0
0
0
0
X
(1)
X
(1)
0
0
1
1
0
0
0
0
1
1
1
1
1
1
Truth Table for AND (&&) Truth Table for AND (&&)
FALSE = 0 FALSE = 0
TRUE = 1 TRUE = 1
expr2 expr2 is not evaluated is not evaluated
in the first two cases in the first two cases
since its value is not since its value is not
relevant to the result. relevant to the result.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 111 1317 CPL
Example
Operators
Logical Operators and Short Circuit Evaluation
The danger of short circuit evaluation
if
if
!
!
((
((
z
z
=
=
x
x
+
+
y
y
) && (
) && (
c
c
=
=
a
a
+
+
b
b
))
))
{
{
z
z
+=
+=
5
5
;
;
c
c
+=
+=
10
10
;
;
}
}
It is perfectly legal in C to logically compare two assignment e It is perfectly legal in C to logically compare two assignment expressions in xpressions in
this way, though it is not usually good programming practice. this way, though it is not usually good programming practice.
A similar problem exists when using function calls in logical op A similar problem exists when using function calls in logical operations, which erations, which
is a very common practice. The second function may never be eva is a very common practice. The second function may never be evaluated. luated.
If If z z
= 0, then = 0, then c c
will will not not
be evaluated be evaluated
Initial value of Initial value of c c
may not be correct may not be correct
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 112 1317 CPL
Operators
Shift
Shift Left Example:
x =
5;
// x = 0b00000101 = 5
y =
x <<
2;
// y = 0b00010100 = 20
In both shift left and shift right, the bits
that are shifted out are lost
For shift left, 0's are shifted in (Zero Fill)
Operator Result Operation Example
Shift Left Shift Left
<< <<
Shift Right Shift Right
>> >>
x << y x << y
x >> y x >> y
Shift Shift x x
by by y y
bits to the left bits to the left
Shift Shift x x
by by y y
bits to the right bits to the right
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 113 1317 CPL
Logical Shift Right (Zero Fill)
Arithmetic Shift Right (Sign Extend)
Operators
Shift
Special Cases
If x is UNSIGNED (unsigned
char
in this case):
x =
250;
// x = 0b11111010 = 250
y =
x >>
2;
// y = 0b00111110 = 62
If x is SIGNED (char
in this case):
x =
-6;
// x = 0b11111010 = -6
y =
x >>
2;
// y = 0b11111110 = -2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 114 1317 CPL
0
0
0
0
0
0
0
0
Operators
Power of 2 Integer
Divide vs. Shift Right
If you are dividing by a power of 2, it will
usually be more efficient to use a right
shift instead
Works for integers or fixed point values
y = x / 2
y = x / 2
n
n
y = x >> n
y = x >> n
1
1
0
0
1
1
0
0
>>
10
10
5
10
0
0
0
0
0
0
0
0
0
0
1
1
0
0
1
1
Right Shift
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 115 1317 CPL
Operators
Power of 2 Integer
Divide vs. Shift in MPLAB
C30
Example: Divide by 2 Example: Right Shift by 1
int
int
x
x
=
=
20
20
;
;
int
int
y
y
;
;
y
y
=
=
x
x
/
/
2
2
;
;
int
int
x
x
=
=
20
20
;
;
int
int
y
y
;
;
y
y
=
=
x
x
>>
>>
1
1
;
;
10: y = x / 2; 10: y = x / 2;
00288 804000 mov.w 0x0800,0x0000 00288 804000 mov.w 0x0800,0x0000
0028A 200022 mov.w #0x2,0x0004 0028A 200022 mov.w #0x2,0x0004
0028C 090011 repeat #17 0028C 090011 repeat #17
0028E D80002 div.sw 0x0000,0x0004 0028E D80002 div.sw 0x0000,0x0004
00290 884010 mov.w 0x0000,0x0802 00290 884010 mov.w 0x0000,0x0802
9: y = x >> 1; 9: y = x >> 1;
00282 804000 mov.w 0x0800,0x0000 00282 804000 mov.w 0x0800,0x0000
00284 DE8042 asr 0x0000,#1,0x0000 00284 DE8042 asr 0x0000,#1,0x0000
00286 884010 mov.w 0x0000,0x0802 00286 884010 mov.w 0x0000,0x0802
y = 10
y = 10
y = 10
y = 10
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 116 1317 CPL
Example: Divide by 2 Example: Right Shift by 1
10: y = x / 2; 10: y = x / 2;
0132 C08C MOVFF 0x8c, 0x8a 0132 C08C MOVFF 0x8c, 0x8a
0134 F08A NOP 0134 F08A NOP
0136 C08D MOVFF 0x8d, 0x8b 0136 C08D MOVFF 0x8d, 0x8b
0138 F08B NOP 0138 F08B NOP
013A 0E02 MOVLW 0x2 013A 0E02 MOVLW 0x2
013C 6E0D MOVWF 0xd, ACCESS 013C 6E0D MOVWF 0xd, ACCESS
013E 6A0E CLRF 0xe, ACCESS 013E 6A0E CLRF 0xe, ACCESS
0140 C08A MOVFF 0x8a, 0x8 0140 C08A MOVFF 0x8a, 0x8
0142 F008 NOP 0142 F008 NOP
0144 C08B MOVFF 0x8b, 0x9 0144 C08B MOVFF 0x8b, 0x9
0146 F009 NOP 0146 F009 NOP
0148 EC6B CALL 0xd6, 0 0148 EC6B CALL 0xd6, 0
014A F000 NOP 014A F000 NOP
014C C008 MOVFF 0x8, 0x8a 014C C008 MOVFF 0x8, 0x8a
014E F08A NOP 014E F08A NOP
0150 C009 MOVFF 0x9, 0x8b 0150 C009 MOVFF 0x9, 0x8b
0152 F08B NOP 0152 F08B NOP
int
int
x
x
=
=
20
20
;
;
int
int
y
y
;
;
y
y
=
=
x
x
/
/
2
2
;
;
Operators
Power of 2 Integer
Divide vs. Shift in MPLAB
C18
9: y = x >> 1; 9: y = x >> 1;
0122 C08C MOVFF 0x8c, 0x8a 0122 C08C MOVFF 0x8c, 0x8a
0124 F08A NOP 0124 F08A NOP
0126 C08D MOVFF 0x8d, 0x8b 0126 C08D MOVFF 0x8d, 0x8b
0128 F08B NOP 0128 F08B NOP
012A 0100 MOVLB 0 012A 0100 MOVLB 0
012C 90D8 BCF 0xfd8, 0, ACCESS 012C 90D8 BCF 0xfd8, 0, ACCESS
012E 338B RRCF 0x8b, F, BANKED 012E 338B RRCF 0x8b, F, BANKED
0130 338A RRCF 0x8a, F, BANKED 0130 338A RRCF 0x8a, F, BANKED
int
int
x
x
=
=
20
20
;
;
int
int
y
y
;
;
y
y
=
=
x
x
>>
>>
1
1
;
;
y = 10
y = 10
y = 10
y = 10
16 16- -bit Shift on 8 bit Shift on 8- -bit Architecture bit Architecture
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 117 1317 CPL
Operators
Memory Addressing
These operators will be discussed later in the sections on These operators will be discussed later in the sections on
arrays, pointers, structures, and unions. They are included arrays, pointers, structures, and unions. They are included
here for reference and completeness. here for reference and completeness.
Operator Result Operation Example
Struct / Union Struct / Union
Member by Member by
Reference Reference
- -> >
Subscripting Subscripting
[] []
Struct / Union Struct / Union
Member Member
. .
Address of Address of
& &
Indirection Indirection
* *
p p- ->y >y
x[y] x[y]
x.y x.y
&x &x
*p *p
The member named The member named y y
in the in the
structure or union that structure or union that p p
points to points to
The The y y
th th
element of array element of array x x
The member named The member named y y
in the in the
structure or union structure or union x x
Pointer to Pointer to x x
The object or function that The object or function that p p
points to points to
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 118 1317 CPL
Operators
Other
() ()
sizeof sizeof
(type) (type)
?: ?:
, ,
Function Call Function Call
Size of an Size of an
object or type object or type
in bytes in bytes
Explicit type Explicit type
cast cast
Conditional Conditional
expression expression
Sequential Sequential
evaluation evaluation
Operator Result Operation Example
foo(x) foo(x)
Passes control to the Passes control to the
function with the function with the
specified arguments specified arguments
sizeof x sizeof x
The number of bytes The number of bytes x x
occupies in memory occupies in memory
(short) x (short) x
Converts the value of Converts the value of x x
to the specified type to the specified type
x ? y : z x ? y : z
The value of The value of y y
if if x x
is true, is true,
else value of else value of z z
x, y x, y
Evaluates Evaluates x x
then then y y, else , else
result is value of result is value of y y
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 119 1317 CPL
Example
Syntax
Operators
The Conditional Operator
(
(
test
test
-
-
expr
expr
) ?
) ?
do
do
-
-
if
if
-
-
true
true
:
:
do
do
-
-
if
if
-
-
false
false
;
;
5 is odd
5 is odd
Result:
Result:
int
int
x
x
=
=
5
5
;
;
(
(
x
x
%
%
2
2
!=
!=
0
0
) ?
) ?
printf
printf
(
(
"%d is odd
"%d is odd
\
\
n"
n"
,
,
x
x
) :
) :
printf
printf
(
(
"%d is even
"%d is even
\
\
n"
n"
,
,
x
x
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 120 1317 CPL
Operators
The Conditional Operator
x = a if condition is true
x = b if condition is false
Example 1 (most commonly used)
x = (condition) ? a : b;
Example 2 (less often used)
(condition) ? (x = a):(x
= b);
The conditional operator may be used to
conditionally assign a value to a variable
In both cases:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 121 1317 CPL
Operators
The Explicit Type Cast Operator
Example: Integer Divide Example: Floating Point Divide
int
int
x
x
=
=
10
10
;
;
float
float
y
y
;
;
y
y
=
=
x
x
/
/
4
4
;
;
int
int
x
x
=
=
10
10
;
;
float
float
y
y
;
;
y
y
=
=
(
(
float
float
)
)
x
x
/
/
4
4
;
;
y = 2.
y = 2.
0
0
00000
00000
Because: int / int Because: int / int
int int
y = 2.
y = 2.
5
5
00000
00000
Because: float / int Because: float / int
float float
b * c
b * c
a
a
(b * c)
(b * c)
a + ++b
a + ++b
a + (++b)
a + (++b)
a + ++b * c
a + ++b * c
a + ((++b) * c)
a + ((++b) * c)
If functions are used in an expression, there is no set order of If functions are used in an expression, there is no set order of
evaluation for the functions themselves. evaluation for the functions themselves.
e.g. e.g. x = f() + g() x = f() + g()
There is no way to know if There is no way to know if f() f()
or or g() g()
will be evaluated first. will be evaluated first.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 126 1317 CPL
If two operators have the same
precedence, their associativity determines
the order of evaluation
You can rely on these rules, but it is good
programming practice to explicitly group
elements of an expression
Operators
Associativity
Expression Effective Expression Associativity
x / y % z
x / y % z
(x / y) % z
(x / y) % z
Left Left- -to to- -Right Right
x = y = z
x = y = z
x = (y = z)
x = (y = z)
Right Right- -to to- -Left Left
~++x
~++x
~(++x)
~(++x)
Right Right- -to to- -Left Left
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 127 1317 CPL
Lab Exercise 4
Lab Exercise 4
Operators
Operators
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 128 1317 CPL
Lab 04
Operators
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab04
Lab04
\
\
Lab04.mcw
Lab04.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 129 1317 CPL
Lab 04
Operators
/ *###########################################################################
# STEP 1: Add char Var i abl e1 t o char Var i abl e2 and st or e t he r esul t i n
# char Var i abl e1. Thi s may be done i n t wo ways. One uses t he
# or di nar y addi t i on oper at or , t he ot her uses a compound assi gnment
# oper at or . Wr i t e t wo l i nes of code t o per f or mt hi s oper at i on
# t wi ce - once f or each of t he t wo met hods.
# Don' t f or get t o end each st at ement wi t h a semi - col on!
###########################################################################*/
/ / Add usi ng addi t i on oper at or
charVariable1 = charVariable1 + charVariable2;
/ / Add usi ng compound assi gnment oper at or
charVariable1 += charVariable2;
/ *###########################################################################
# STEP 2: I ncr ement char Var i abl e1. Ther e ar e sever al ways t hi s coul d be
# done. Use t he one t hat r equi r es t he l east amount of t ypi ng.
###########################################################################*/
/ / I ncr ement char Var i abl e1
charVariable1++;
Solution: Steps 1 and 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 130 1317 CPL
Lab 04
Operators
/ *###########################################################################
# STEP 3: Use t he condi t i onal oper at or t o set l ongVar i abl e1 equal t o
# i nt Var i abl e1 i f char Var i abl e1 i s l ess t han char Var i abl e2.
# Ot her wi se, set l ongVar i abl e1 equal t o i nt Var i abl e2
# NOTE: The comment s bel ow ar e br oken up i nt o 3 l i nes, but t he code you
# need t o wr i t e can f i t on a si ngl e l i ne.
###########################################################################*/
/ / I f char Var i abl e1 < char Var i abl e2, t hen
/ / l ongVar i abl e1 = i nt Var i abl e1, ot her wi se
/ / l ongVar i abl e1 = i nt Var i abl e2
longVariable1 = (charVariable1 < charVariable2) ? intVariable1 :
intVariable2;
/ *###########################################################################
# STEP 4: Shi f t l ongVar i abl e2 one bi t t o t he r i ght . Thi s can be accompl i shed
# most easi l y usi ng t he appr opr i at e compound assi gnment oper at or .
###########################################################################*/
/ / Shi f t l ongVar i abl e2 one bi t t o t he r i ght
longVariable2 >>= 1;
Solution: Steps 3 and 4
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 131 1317 CPL
Lab 04
Operators
/ *###########################################################################
# STEP 5: Per f or mt he oper at i on ( l ongVar i abl e2 AND 0x30) and st or e t he r esul t
# back i n l ongVar i abl e2. Once agai n, t he easi est way t o do t hi s i s
# t o use t he appr opr i at e compound assi gnment oper at or t hat wi l l
# per f or man equi val ent oper at i on t o t he one i n t he comment bel ow.
###########################################################################*/
/ / l ongVar i abl e2 = l ongVar i abl e2 & 0x30
longVariable2 &= 0x30;
Solution: Step 5
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 132 1317 CPL
Lab 04
Conclusions
Most operators look just like their normal
mathematical notation
C adds several shortcut operators in the
form of compound assignments
Most C programmers tend to use the
shortcut operators
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 133 1317 CPL
Expressions and Statements
Expressions and Statements
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 134 1317 CPL
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)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 135 1317 CPL
Example
Expressions
Examples
a
a
+
+
b
b
x
x
=
=
y
y
speed
speed
=
=
dist
dist
/
/
time
time
z
z
=
=
ReadInput
ReadInput
()
()
c
c
<=
<=
7
7
x
x
==
==
25
25
count
count
++
++
d
d
=
=
a
a
+
+
5
5
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 136 1317 CPL
Statements
Cause an action to be carried out
Three kinds of statements in C:
Expression Statements
Compound Statements
Control Statements
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 137 1317 CPL
Examples
Expression Statements
An expression followed by a semi-colon
Execution of the statement causes the
expression to be evaluated
i
i
=
=
0
0
;
;
i
i
++;
++;
a
a
=
=
5
5
+
+
i
i
;
;
y
y
= (
= (
m
m
*
*
x
x
) +
) +
b
b
;
;
printf(
printf(
"Slope = %f"
"Slope = %f"
, m
, m
);
);
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 138 1317 CPL
Compound Statements
A group of individual statements enclosed
within a pair of curly braces { and }
Individual statements within may be any
statement type, including compound
Allows statements to be embedded within
other statements
Does NOT end with a semicolon after }
Also called Block Statements
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 139 1317 CPL
Example
Compound Statements
Example
{
{
float
float
start
start
,
,
finish
finish
;
;
start
start
=
=
0.0
0.0
;
;
finish
finish
=
=
400.0
400.0
;
;
distance
distance
=
=
finish
finish
start
start
;
;
time
time
=
=
55.2
55.2
;
;
speed
speed
=
=
distance
distance
/
/
time
time
;
;
printf
printf
(
(
"Speed = %f m/s"
"Speed = %f m/s"
,
,
speed
speed
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 140 1317 CPL
Example
Control Statements
Used for loops, branches and logical tests
Often require other statements embedded
within them
while
while
(
(
distance
distance
<
<
400.0
400.0
)
)
{
{
printf
printf
(
(
"Keep running!"
"Keep running!"
);
);
distance
distance
+=
+=
0.1
0.1
;
;
}
}
(while syntax:
(while syntax:
while
while
expr
expr
statement
statement
)
)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 141 1317 CPL
Making Decisions
Making Decisions
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 142 1317 CPL
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)
Boolean Expressions
int
int
main
main
(
(
void
void
)
)
{
{
int
int
x
x
=
=
5
5
,
,
y
y
,
,
z
z
;
;
y
y
= (
= (
x
x
>
>
4
4
);
);
z
z
= (
= (
x
x
>
>
6
6
);
);
while
while
(
(
1
1
);
);
}
}
y = 1 (TRUE)
y = 1 (TRUE)
z = 0 (FALSE)
z = 0 (FALSE)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 143 1317 CPL
Boolean Expressions
Equivalent Expressions
If a variable, constant or function call is
used alone as the conditional expression:
(MyVar)
or (Foo())
This is the same as saying:
(MyVar !=
0)
or (Foo()
!=
0)
In either case, if MyVar
0 or Foo()
0,
then the expression evaluates as TRUE
(non-zero)
C Programmers almost always use the
first method (laziness always wins in C)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 144 1317 CPL
Note
Syntax
if
Statement
expression is evaluated for boolean
TRUE (0) or FALSE (=0)
If TRUE, then statement is executed
if
if
(
(
expression
expression
)
)
statement
statement
if
(expression)
{
statement
1
statement
2
}
Whenever you see statement in
a syntax guide, it may be replaced
by a compound (block) statement.
Remember: spaces and new lines
are not significant.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 145 1317 CPL
Syntax
if
Statement
Flow Diagram
if
if
(
(
expression
expression
)
)
statement
statement
TRUE
FALSE
expression = 0
expression
0
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 146 1317 CPL
Example
{
{
int
int
x
x
=
=
5
5
;
;
if
if
(
(
x
x
)
)
{
{
printf
printf
(
(
"x = %d
"x = %d
\
\
n"
n"
,
,
x
x
);
);
}
}
while
while
(
(
1
1
);
);
}
}
if
Statement
If x is TRUE (non If x is TRUE (non- -zero) zero)
then print the value of x. then print the value of x.
What will print if x = 5?
if x = 0?
if x = -82?
if x = 65536?
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 148 1317 CPL
if
Statement
Testing for TRUE
Example: if (x) Example: if (x ==1)
if
(x) if
(x == 1)
8: if (x)
011B4 E208C2 cp0.w 0x08c2
011B6 320004 bra z, 0x0011c0
11: if (x == 1)
011C0 804610 mov.w 0x08c2,0x0000
011C2 500FE1 sub.w 0x0000,#1,[0x001e]
011C4 3A0004 bra nz, 0x0011ce
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
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 149 1317 CPL
Example
Nested if
Statements
int
int
power
power
=
=
10
10
;
;
float
float
band
band
=
=
2.0
2.0
;
;
float
float
frequency
frequency
=
=
146.52
146.52
;
;
if
if
(
(
power
power
>
>
5
5
)
)
{
{
if
if
(
(
band
band
==
==
2.0
2.0
)
)
{
{
if
if
((
((
frequency
frequency
>
>
144
144
) && (
) && (
frequency
frequency
<
<
148
148
))
))
{
{
printf
printf
(
(
"Yes, it's all true!
"Yes, it's all true!
\
\
n"
n"
);
);
}
}
}
}
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 150 1317 CPL
Syntax
if-else
Statement
expression is evaluated for boolean
TRUE (0) or FALSE (=0)
If TRUE, then statement
1
is executed
If FALSE, then statement
2
is executed
if
if
(
(
expression
expression
)
)
statement
statement
1 1
else
else
statement
statement
2 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 151 1317 CPL
if-else
Statement
Flow Diagram
TRUE
FALSE
expression = 0
expression
0
Syntax
if
if
(
(
expression
expression
)
)
statement
statement
1 1
else
else
statement
statement
2 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 152 1317 CPL
Example
if-else
Statement
{
{
float frequency
float frequency
=
=
146.52
146.52
;
;
//frequency in MHz
//frequency in MHz
if
if
((
((
frequency
frequency
>
>
144.0
144.0
)
)
&&
&&
(
(
frequency
frequency
<
<
148.0
148.0
))
))
{
{
printf
printf
(
(
"You're on the 2 meter band
"You're on the 2 meter band
\
\
n"
n"
);
);
}
}
else
else
{
{
printf
printf
(
(
"You're not on the 2 meter band
"You're not on the 2 meter band
\
\
n"
n"
);
);
}
}
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 153 1317 CPL
Syntax
if-else if
Statement
expression
1
is evaluated for boolean TRUE (0)
or FALSE (=0)
If TRUE, then statement
1
is executed
If FALSE, then expression
2
is evaluated
If TRUE, then statement
2
is executed
If FALSE, then statement
3
is executed
if
if
(
(
expression
expression
1 1
)
)
statement
statement
1 1
else if
else if
(
(
expression
expression
2 2
)
)
statement
statement
2 2
else
else
statement
statement
3 3
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 154 1317 CPL
if-else if
Statement
Flow Diagram
TRUE
FALSE
FALSE
TRUE
Syntax
if
if
(
(
expression
expression
1 1
)
)
statement
statement
1 1
else if
else if
(
(
expression
expression
2 2
)
)
statement
statement
2 2
else
else
statement
statement
3 3
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 155 1317 CPL
Example
if-else if
Statement
if
if
((
((
freq
freq
>
>
144
144
) && (
) && (
freq
freq
<
<
148
148
))
))
printf
printf
(
(
"You're on the 2 meter band
"You're on the 2 meter band
\
\
n"
n"
);
);
else if
else if
((
((
freq
freq
>
>
222
222
) && (
) && (
freq
freq
<
<
225
225
))
))
printf
printf
(
(
"You're on the 1.25 meter band
"You're on the 1.25 meter band
\
\
n"
n"
);
);
else if
else if
((
((
freq
freq
>
>
420
420
) && (
) && (
freq
freq
<
<
450
450
))
))
printf
printf
(
(
"You're on the 70 centimeter band
"You're on the 70 centimeter band
\
\
n"
n"
);
);
else
else
printf
printf
(
(
"You're somewhere else
"You're somewhere else
\
\
n"
n"
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 156 1317 CPL
Lab Exercise 5
Lab Exercise 5
Making Decisions: if
Statements
Making Decisions: if
Statements
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 157 1317 CPL
Lab 05
Making Decisions (if)
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab05
Lab05
\
\
Lab05.mcw
Lab05.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 158 1317 CPL
Lab 05
Making Decisions (if)
/ *###########################################################################
# STEP 1: I ncr ement i nt Var i abl e1 i f BOTH t he f ol l owi ng condi t i ons ar e t r ue:
# * f l oat Var i abl e2 i s gr eat er t han or equal t o f l oat Var i abl e1
# * char Var i abl e2 i s gr eat er t han or equal t o char Var i abl e1
# Remember t o use par ent heses t o gr oup l ogi cal oper at i ons.
###########################################################################*/
/ / Wr i t e t he i f condi t i on
if((floatVariable2 >= floatVariable1) && (charVariable2 >= charVariable1))
{
intVariable1++;
/ / I ncr ement i nt Var i abl e1
}
/ *###########################################################################
# STEP 2: I f t he above i s not t r ue, and f l oat Var i abl e1 i s gr eat er t han 50
# t hen decr ement i nt Var i abl e2. ( HI NT: el se i f )
###########################################################################*/
/ / Wr i t e t he el se i f condi t i on
else if(floatVariable1 > 50)
{
intVariable2--;
/ / Decr ement i nt Var i abl e2
}
Solution: Steps 1 and 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 159 1317 CPL
Lab 05
Making Decisions (if)
/ *###########################################################################
# STEP 3: I f nei t her of t he above ar e t r ue, set char Var i abl e2 equal t o 1.
# ( HI NT: el se)
###########################################################################*/
/ / Wr i t e t he el se condi t i on
else
{
charVariable2 = 1;
/ / Set char Var i abl e2 equal t o 1
}
Solution: Step 3
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 160 1317 CPL
Lab 05
Conclusions
if statements make it possible to
conditionally execute a line or block of
code based on a logic equation
else if / else statements make it possible to
present follow-up conditions if the first
one proves to be false
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 161 1317 CPL
Syntax
switch
Statement
expression is evaluated and tested for a
match with the const-expr in each case
clause
The statements in the matching case
clause is executed
switch
switch
(
(
expression
expression
)
)
{
{
case
case
const
const
-
-
expr
expr
1 1
:
:
statements
statements
1 1
case
case
const
const
-
-
expr
expr
n n
:
:
statements
statements
n n
default
default
:
:
statements
statements
n+1 n+1
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 162 1317 CPL
switch
Statement
Flow Diagram (default)
Const-expr
1
=
expression?
START
END
statement
2
statement
1
Const-expr
2
=
expression?
statement
n+1
Const-expr
n
=
expression?
statement
n
Const-expr
1
=
expression?
START
END
statement
2
statement
1
Const-expr
2
=
expression?
statement
n+1
Const-expr
n
=
expression?
statement
n
Notice that each
statement falls
through to the next
This is the default
behavior of the
switch
statement
YES
YES
YES
NO
NO
NO
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 163 1317 CPL
Const-expr
1
=
expression?
START
END
Const-expr
2
=
expression?
statement
n+1
Const-expr
n
=
expression?
statement
1
break;
statement
2
break;
statement
n
break;
Const-expr
1
=
expression?
START
END
Const-expr
2
=
expression?
statement
n+1
Const-expr
n
=
expression?
statement
1
break;
statement
2
break;
statement
n
break;
switch
Statement
Flow Diagram (modified)
Adding a break
statement to each
statement block will
eliminate fall
through, allowing
only one case
clause's statement
block to be executed
YES
YES
YES
NO
NO
NO
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 164 1317 CPL
switch
Example 1
switch
Statement
switch
switch
(
(
channel
channel
)
)
{
{
case
case
2
2
:
:
printf
printf
(
(
"WBBM Chicago
"WBBM Chicago
\
\
n"
n"
);
);
break
break
;
;
case
case
3
3
:
:
printf
printf
(
(
"DVD Player
"DVD Player
\
\
n"
n"
);
);
break
break
;
;
case
case
4
4
:
:
printf
printf
(
(
"WTMJ Milwaukee
"WTMJ Milwaukee
\
\
n"
n"
);
);
break
break
;
;
case
case
5
5
:
:
printf
printf
(
(
"WMAQ
"WMAQ
Chicago
Chicago
\
\
n"
n"
);
);
break
break
;
;
case
case
6
6
:
:
printf
printf
(
(
"WITI
"WITI
Milwaukee
Milwaukee
\
\
n"
n"
);
);
break
break
;
;
case
case
7
7
:
:
printf
printf
(
(
"WLS
"WLS
Chicago
Chicago
\
\
n"
n"
);
);
break
break
;
;
case
case
9
9
:
:
printf
printf
(
(
"WGN
"WGN
Chicago
Chicago
\
\
n"
n"
);
);
break
break
;
;
case
case
10
10
:
:
printf
printf
(
(
"WMVS
"WMVS
Milwaukee
Milwaukee
\
\
n"
n"
);
);
break
break
;
;
case
case
11
11
:
:
printf
printf
(
(
"WTTW
"WTTW
Chicago
Chicago
\
\
n"
n"
);
);
break
break
;
;
case
case
12
12
:
:
printf
printf
(
(
"WISN
"WISN
Milwaukee
Milwaukee
\
\
n"
n"
);
);
break
break
;
;
default
default
:
:
printf
printf
(
(
"No
"No
Signal Available
Signal Available
\
\
n"
n"
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 165 1317 CPL
switch
Example 2
switch
Statement
switch
switch
(
(
letter
letter
)
)
{
{
case
case
'a'
'a'
:
:
printf
printf
(
(
"Letter
"Letter
'a' found.
'a' found.
\
\
n"
n"
);
);
break
break
;
;
case
case
'b'
'b'
:
:
printf
printf
(
(
"Letter
"Letter
'b' found.
'b' found.
\
\
n"
n"
);
);
break
break
;
;
case
case
'c'
'c'
:
:
printf
printf
(
(
"Letter
"Letter
'c' found.
'c' found.
\
\
n"
n"
);
);
break
break
;
;
default
default
:
:
printf
printf
(
(
"Letter
"Letter
not in list.
not in list.
\
\
n"
n"
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 166 1317 CPL
switch
Example 3
switch
Statement
switch
switch
(
(
channel
channel
)
)
{
{
case
case
4 ... 7
4 ... 7
:
:
printf
printf
(
(
"VHF
"VHF
Station
Station
\
\
n"
n"
);
);
break
break
;
;
case
case
9 ... 12
9 ... 12
:
:
printf
printf
(
(
"VHF
"VHF
Station
Station
\
\
n"
n"
);
);
break
break
;
;
case
case
3
3
:
:
case
case
8
8
:
:
case
case
13
13
:
:
printf
printf
(
(
"Weak
"Weak
Signal
Signal
\
\
n"
n"
);
);
break
break
;
;
case
case
14 ... 69
14 ... 69
:
:
printf
printf
(
(
"UHF
"UHF
Station
Station
\
\
n"
n"
);
);
break
break
;
;
default
default
:
:
printf
printf
(
(
"No
"No
Signal Available
Signal Available
\
\
n"
n"
);
);
}
}
Case 3 and 8 are allowed to fall Case 3 and 8 are allowed to fall
through to case 13 through to case 13
Apply this case to Apply this case to channel channel
4, 5, 4, 5,
6, and 7 6, and 7
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 167 1317 CPL
Lab Exercise 6
Lab Exercise 6
Making Decisions: switch
Statements
Making Decisions: switch
Statements
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 168 1317 CPL
Lab 06
Making Decisions (switch)
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab06
Lab06
\
\
Lab06.mcw
Lab06.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 169 1317 CPL
Lab 06
Making Decisions (switch)
/ *###########################################################################
# TASK: Wr i t e a swi t ch st at ement t o pr i nt t he net wor k' s i ni t i al s wi t h t he
# channel ( based on Chi cago TV st at i ons) .
# * I f channel = 2, pr i nt " CBS 2" t o t he out put wi ndow.
# * I f channel = 5, pr i nt " NBC 5" t o t he out put wi ndow.
# * I f channel = 7, pr i nt " ABC 7" t o t he out put wi ndow.
# * For al l ot her channel s, pr i nt " - - - #" t o t he out put wi ndow,
# wher e " #" i s t he channel number .
# ( HI NT: Use pr i nt f ( ) , and use t he newl i ne char act er ' \ n' at t he end
# of each st r i ng you pr i nt t o t he out put wi ndow. )
# NOTE: The swi t ch st at ement i s i n a l oop t hat wi l l execut e 9 t i mes. Each
# pass t hr ough t he l oop, ' channel ' wi l l be i ncr ement ed. The out put
# wi ndow shoul d di spl ay a l i ne of t ext f or channel s 2 t o 10.
#
# STEP 1: Open a swi t ch st at ement on t he var i abl e ' channel '
###########################################################################*/
/ / Begi n swi t ch st at ement
switch(channel)
{
Solution: Step 1
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 170 1317 CPL
Lab 06
Making Decisions (switch)
/ *###########################################################################
# STEP 2: Wr i t e case f or channel = CBS ( CBS i s a const ant def i ned t o equal 2)
###########################################################################*/
case CBS: / / I f channel = CBS ( CBS = 2)
{
printf("CBS
%d\n", channel); / / Di spl ay st r i ng " CBS 2" f ol l owed by newl i ne
break;
/ / Pr event f al l t hr ough t o next case
}
/ *###########################################################################
# STEP 3: Wr i t e case f or channel = NBC ( NBC i s a const ant def i ned t o equal 5)
# Thi s shoul d l ook al most i dent i cal t o st ep 2.
###########################################################################*/
case NBC:
/ / I f channel = NBC ( NBC = 5)
{
printf("NBC
%d\n", channel); / / Di spl ay st r i ng " NBC 5" f ol l owed by newl i ne
break; / / Pr event f al l t hr ough t o next case
}
Solution: Steps 2 and 3
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 171 1317 CPL
Lab 06
Making Decisions (switch)
/ *###########################################################################
# STEP 4: Wr i t e case f or channel = ABC ( ABC i s a const ant def i ned t o equal 7)
# Thi s shoul d l ook al most i dent i cal t o st ep 2.
###########################################################################*/
case ABC: / / I f channel = ABC ( ABC = 7)
{
printf("ABC
%d\n", channel);
/ / Di spl ay st r i ng " ABC 7" f ol l owed by newl i ne
break;
/ / Pr event f al l t hr ough t o next case
}
/ *###########################################################################
# STEP 5: Wr i t e def aul t case. I f channel i s anyt hi ng ot her t han t hose
# l i st ed above, t hi s i s what shoul d be done. For t hese cases, you
# need t o pr i nt t he st r i ng " - - - #" wher e " #" i s t he channel number .
# For exampl e, i f channel = 6, you shoul d pr i nt " - - - 6" .
###########################################################################*/
default:
/ / For al l ot her channel s
{
printf("---
%d\n", channel); / / Di spl ay st r i ng "- - - #" f ol l owed by newl i ne
}
Solution: Steps 4 and 5
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 172 1317 CPL
Lab 06
Conclusions
switch
provides a more elegant decision
making structure than if
for multiple
conditions (if
else if
else if
else if)
The drawback is that the conditions may
only be constants (match a variable's state
to a particular value)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 173 1317 CPL
Loops
Loops
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 174 1317 CPL
Syntax
for
Loop
expression
1
initializes a loop count
variable once at start of loop (e.g. i = 0)
expression
2
is the test condition
the
loop will continue while this is true
(e.g. i <= 10)
expression
3
is executed at the end of
each iteration
usually to modify the loop
count variable (e.g. i++)
for
for
(
(
expression
expression
1 1
;
;
expression
expression
2 2
;
;
expression
expression
3 3
)
)
statement
statement
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 175 1317 CPL
Syntax
for
Loop
Flow Diagram
for
for
(
(
expression
expression
1 1
; expression
; expression
2 2
; expression
; expression
3 3
)
)
statement
statement
expression
2
?
expression
1
statement
expression
3
expression
2
?
expression
1
statement
expression
3
TRUE
FALSE
i =
0
i <
n
i++
Initialize loop
variable
Test loop variable for
exit condition
Modify loop
variable
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 176 1317 CPL
Example (Code Fragment)
for
Loop
int
int
i
i
;
;
for
for
(
(
i
i
=
=
0
0
;
;
i
i
<
<
5
5
;
;
i
i
++)
++)
{
{
printf
printf
(
(
"Loop
"Loop
iteration %d
iteration %d
\
\
n"
n"
,
,
i
i
);
);
}
}
Loop iteration 0 Loop iteration 0
Loop iteration 1 Loop iteration 1
Loop iteration 2 Loop iteration 2
Loop iteration 3 Loop iteration 3
Loop iteration 4 Loop iteration 4
Expected Output: Expected Output:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 177 1317 CPL
Note
for
Loop
Any or all of the three expressions may be
left blank (semi-colons must remain)
If expression
1
or expression
3
are
missing, their actions simply disappear
If expression
2
is missing, it is assumed
to always be true
for
for
( ; ; )
( ; ; )
{
{
}
}
Infinite Loops Infinite Loops
A A for for
loop without any loop without any
expressions will execute expressions will execute
indefinitely (can leave indefinitely (can leave
loop via loop via break break
statement) statement)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 178 1317 CPL
Syntax
while
Loop
If expression is true, statement will be
executed and then expression will be re-
evaluated to determine whether or not to
execute statement again
It is possible that statement will never
execute if expression is false when it is
first evaluated
while
while
(
(
expression
expression
)
)
statement
statement
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 179 1317 CPL
Syntax
while
Loop
Flow Diagram
while
while
(
(
expression
expression
)
)
statement
statement
TRUE
FALSE
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 180 1317 CPL
Example (Code Fragment)
while
Loop
Example
int
int
i
i
=
=
0
0
;
;
while
while
(
(
i
i
<
<
5
5
)
)
{
{
printf
printf
(
(
"Loop
"Loop
iteration %d
iteration %d
\
\
n"
n"
,
,
i
i
++);
++);
}
}
Loop iteration 0 Loop iteration 0
Loop iteration 1 Loop iteration 1
Loop iteration 2 Loop iteration 2
Loop iteration 3 Loop iteration 3
Loop iteration 4 Loop iteration 4
Expected Output: Expected Output:
Loop counter initialized Loop counter initialized
outside of loop outside of loop
Loop counter Loop counter
incremented manually incremented manually
inside loop inside loop
Condition checked at Condition checked at
start of loop iterations start of loop iterations
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 181 1317 CPL
Note
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 a matter of personal taste
Frequently used for main loop of program
while
while
(
(
1
1
)
)
{
{
}
}
Infinite Loops Infinite Loops
A A while while
loop with loop with
expression expression = = 1 1
will will
execute indefinitely (can execute indefinitely (can
leave loop via leave loop via break break
statement) statement)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 182 1317 CPL
Syntax
do-while
Loop
statement is executed and then
expression is evaluated to determine
whether or not to execute statement
again
statement will always execute at least
once, even if the expression is false when
the loop starts
do
do
statement
statement
while
while
(
(
expression
expression
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 183 1317 CPL
Syntax
do-while
Loop
Flow Diagram
do
do
statement
statement
while
while
(
(
expression
expression
);
);
TRUE
FALSE
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 184 1317 CPL
Example (Code Fragment)
do-while
Loop
Example
int
int
i
i
=
=
0
0
;
;
do
do
{
{
printf
printf
(
(
"Loop
"Loop
iteration %d
iteration %d
\
\
n"
n"
,
,
i
i
++);
++);
}
}
while
while
(
(
i
i
<
<
5
5
);
);
Loop iteration 0 Loop iteration 0
Loop iteration 1 Loop iteration 1
Loop iteration 2 Loop iteration 2
Loop iteration 3 Loop iteration 3
Loop iteration 4 Loop iteration 4
Expected Output: Expected Output:
Loop counter initialized Loop counter initialized
outside of loop outside of loop
Loop counter Loop counter
incremented manually incremented manually
inside loop inside loop
Condition checked at Condition checked at
end of loop iterations end of loop iterations
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 185 1317 CPL
Syntax
break
Statement
Causes immediate termination of a loop
even if the exit condition hasn't been met
Exits from a switch
statement so that
execution doesn't fall through to next case
clause
break
break
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 186 1317 CPL
Syntax
break
Statement
Flow Diagram Within a while
Loop
break
break
;
;
TRUE
FALSE
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 187 1317 CPL
Example (Code Fragment)
break
Statement
Example
int
int
i
i
=
=
0
0
;
;
while
while
(
(
i
i
<
<
10
10
)
)
{
{
i
i
++;
++;
if
if
(
(
i
i
==
==
5
5
)
)
break
break
;
;
printf
printf
(
(
"Loop
"Loop
iteration %d
iteration %d
\
\
n"
n"
,
,
i
i
);
);
}
}
Loop iteration 1 Loop iteration 1
Loop iteration 2 Loop iteration 2
Loop iteration 3 Loop iteration 3
Loop iteration 4 Loop iteration 4
Expected Output: Expected Output:
Exit from the loop when i = 5. Exit from the loop when i = 5.
Iteration 6 Iteration 6- -9 will not be executed. 9 will not be executed.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 188 1317 CPL
Syntax
continue
Statement
Causes program to jump back to the
beginning of a loop without completing the
current iteration
continue
continue
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 189 1317 CPL
Syntax
continue
Statement
Flow Diagram Within a while
Loop
continue
continue
;
;
TRUE
FALSE
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 190 1317 CPL
Example (Code Fragment)
continue
Statement
Example
int
int
i
i
=
=
0
0
;
;
while
while
(
(
i
i
<
<
6
6
)
)
{
{
i
i
++;
++;
if
if
(
(
i
i
==
==
2
2
)
)
continue
continue
;
;
printf
printf
(
(
"Loop
"Loop
iteration %d
iteration %d
\
\
n"
n"
,
,
i
i
);
);
}
}
Loop iteration 1 Loop iteration 1
Loop iteration 3 Loop iteration 3
Loop iteration 4 Loop iteration 4
Loop iteration 5 Loop iteration 5
Expected Output: Expected Output:
Skip remaining iteration when i = 2. Skip remaining iteration when i = 2.
Iteration 2 will not be completed. Iteration 2 will not be completed.
Iteration 2 does not print Iteration 2 does not print
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 191 1317 CPL
Lab Exercise 7
Lab Exercise 7
Loops
Loops
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 192 1317 CPL
Lab 07
Loops
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab07
Lab07
\
\
Lab07.mcw
Lab07.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 193 1317 CPL
Lab 07
Loops
/ *###########################################################################
# STEP 1: Cr eat e a f or l oop t o i t er at e t he bl ock of code bel ow. The l oop
# shoul d do t he f ol l owi ng:
# * I ni t i al i ze count er 1 t o 1
# * Loop as l ong as count er 1 i s l ess t han 5
# * I ncr ement count er 1 on each pass of t he l oop
# ( HI NT: f or ( i ni t ; t est ; act i on) )
###########################################################################*/
/ / Wr i t e t he openi ng l i ne of t he f or l oop
for( counter1 = 1 ; counter1 < 5 ; counter1++)
{
i nt Var i abl e1 *= count er 1;
pr i nt f ( " FOR: i nt Var i abl e1 = %d, count er 1 = %d\ n" , i nt Var i abl e1, count er 1) ;
}
/ / end of f or l oop bl ock
Solution: Step 1
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 194 1317 CPL
Lab 07
Loops
/ *###########################################################################
# STEP 2: Cr eat e a whi l e l oop t o i t er at e t he bl ock of code bel ow. The l oop
# shoul d r un unt i l char Var i abl e1 i s 0.
###########################################################################*/
/ / Loop as l ong as char Var i abl e1 i s not 0
while( charVariable1 != 0)
{
char Var i abl e1- - ;
char Var i abl e2 += 5;
pr i nt f ( " WHI LE: char Var i abl e1 = %d, char Var i abl e2 = %d\ n" ,
char Var i abl e1, char Var i abl e2) ;
}
/ / end of whi l e l oop bl ock
Solution: Step 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 195 1317 CPL
Lab 07
Loops
/ *###########################################################################
# STEP 3: Cr eat e a do. . . whi l e l oop t o i t er at e t he bl ock of code bel ow.
# The l oop shoul d r un unt i l count er 1 i s gr eat er t han 100
###########################################################################*/
do / / Wr i t e openi ng l i ne of do l oop
{
count er 1 += 5;
count er 2 = count er 1 * 3;
pr i nt f ( " DO: count er 1 = %d, count er 2 = %d\ n" , count er 1, count er 2) ;
} while(counter1 <= 100);
/ / Wr i t e cl osi ng l i ne of l oop - t est count er 1
/ / end of do. . . whi l e bl ock
Solution: Step 3
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 196 1317 CPL
Lab 07
Conclusions
C Provides three basic looping structures
for
checks loop condition at top,
automatically executes iterator
at bottom
while
checks loop condition at top, you must
create iterator
if needed
dowhile
checks loop condition at bottom,
you must create iterator
if needed
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 197 1317 CPL
Functions
Functions
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 198 1317 CPL
drink()
{
...
be_merry();
return;
}
be_merry()
{
...
return;
}
eat()
{
...
return;
}
main()
{
...
eat();
...
drink();
...
}
Functions
Program Structure
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 199 1317 CPL
Definition
Functions
What is a Function?
Functions
Functions
are self contained program segments designed
are self contained program segments designed
to perform a specific, well defined task.
to perform a specific, well defined task.
All C programs have one or more functions
The main()
function is required
Functions can accept parameters from the
code that calls them
Functions usually return a single value
Functions help to organize a program into
logical, manageable segments
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 200 1317 CPL
Functions in C are conceptually like an
algebraic function from math class
If you pass a value of 7 to the function:
f(7), the value 7 gets "copied" into x and
used everywhere that x exists within the
function definition: f(7) = 7
2
+ 4*7 + 3 = 80
Functions
Remember Algebra Class?
f(
f(
x
x
) =
) =
x
x
2
2
+ 4
+ 4
x
x
+3
+3
Function Name Function Name
Function Parameter Function Parameter
Function Definition Function Definition
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 201 1317 CPL
Syntax
Functions
Definitions
type
type
identifier
identifier
(
(
type
type
1 1
arg
arg
1 1
,
,
,
,
type
type
n n
arg
arg
n n
)
)
{
{
declarations
declarations
statements
statements
return
return
expression
expression
;
;
}
}
Data type of Data type of
return return expression expression
Name Name
Parameter List Parameter List
(optional) (optional)
Return Value (optional) Return Value (optional)
Header Header
Body Body
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 202 1317 CPL
Example
A more efficient version
Example
Functions
Function Definitions: Syntax Examples
int
int
maximum
maximum
(
(
int
int
x
x
,
,
int
int
y
y
)
)
{
{
int
int
z
z
;
;
z
z
= (
= (
x
x
>=
>=
y
y
) ?
) ?
x
x
:
:
y
y
;
;
return
return
z
z
;
;
}
}
int
int
maximum
maximum
(
(
int
int
x
x
,
,
int
int
y
y
)
)
{
{
return
return
((
((
x
x
>=
>=
y
y
) ?
) ?
x
x
:
:
y
y
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 203 1317 CPL
Syntax
Functions
Function Definitions: Return Data Type
A function's type must match the type of
data in the return expression
type
type
identifier
identifier
(
(
type
type
1 1
arg
arg
1 1
,
,
,
,
type
type
n n
arg
arg
n n
)
)
{
{
declarations
declarations
statements
statements
return
return
expression
expression
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 204 1317 CPL
Example
Functions
Function Definitions: Return Data Type
A function may have multiple return
statements, but only one will be executed
and they must all be of the same type
int
int
bigger
bigger
(
(
int
int
a
a
,
,
int
int
b
b
)
)
{
{
if
if
(
(
a
a
>
>
b
b
)
)
return
return
1
1
;
;
else
else
return
return
0
0
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 205 1317 CPL
Example
void
void
identifier
identifier
(
(
type
type
1 1
arg
arg
1 1
,
,
,
,
type
type
n n
arg
arg
n n
)
)
{
{
declarations
declarations
statements
statements
return
return
;
;
}
}
return return; ;
may be omitted if may be omitted if
nothing is being returned nothing is being returned
Functions
Function Definitions: Return Data Type
The function type is void
if:
The return
statement has no expression
The return
statement is not present at all
This is sometimes called a procedure
function since nothing is returned
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 206 1317 CPL
Syntax
type
type
identifier
identifier
(
(
type
type
1 1
arg
arg
1 1
,
,
,
,
type
type
n n
arg
arg
n n
)
)
{
{
declarations
declarations
statements
statements
return
return
expression
expression
;
;
}
}
Functions
Function Definitions: Parameters
A function's parameters are declared just
like ordinary variables, but in a comma
delimited list inside the parentheses
The parameter names are only valid inside
the function (local to the function)
Function Parameters Function Parameters
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 207 1317 CPL
Functions
Function Definitions: Parameters
Parameter list may mix data types
int
foo(int
x,
float
y,
char
z)
Parameters of the same type must be
declared separately
in other words:
int
maximum(int
x,
y)
will not
work
int
maximum(int
x,
int
y)
is correct
Example
int int
maximum maximum( (int int
x x, ,
int int
y y) )
{ {
return return
(( ((x x >= >=
y y) ? ) ?
x x : :
y y); );
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 208 1317 CPL
Functions
Function Definitions: Parameters
If no parameters are required, use the
keyword void
in place of the parameter
list when defining the function
Example
type type identifier identifier( (void void) )
{ {
declarations declarations
statements statements
return return expression expression; ;
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 209 1317 CPL
Function Call Syntax
Functions
How to Call/Invoke a Function
No parameters and no return value
No parameters and no return value
foo
foo
();
();
No parameters, but with a return value
No parameters, but with a return value
x
x
=
=
foo
foo
();
();
With parameters, but no return value
With parameters, but no return value
foo
foo
(
(
a
a
,
,
b
b
);
);
With parameters and a return value
With parameters and a return value
x
x
=
=
foo
foo
(
(
a
a
,
,
b
b
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 210 1317 CPL
Functions
Function Prototypes
Just like variables, a function must be
declared before it may be used
Declaration must occur before main() or
other functions that use it
Declaration may take two forms:
The entire function definition
Just a function prototype
the function
definition itself may then be placed anywhere
in the program
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 211 1317 CPL
Function prototypes may be take on two
different formats:
An exact copy of the function header:
Like the function header, but without the
parameter names
only the types need be
present for each parameter:
Functions
Function Prototypes
Example
Function Prototype 1
int
int
maximum
maximum
(
(
int
int
x
x
,
,
int
int
y
y
);
);
Example
Function Prototype 2
int
int
maximum
maximum
(
(
int
int
,
,
int
int
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 212 1317 CPL
Example 1
Functions
Declaration and Use: Example 1
int
int
a
a
=
=
5
5
,
,
b
b
=
=
10
10
,
,
c
c
;
;
int
int
maximum
maximum
(
(
int
int
x
x
,
,
int
int
y
y
)
)
{
{
return
return
((
((
x
x
>=
>=
y
y
) ?
) ?
x
x
:
:
y
y
);
);
}
}
int
int
main
main
(
(
void
void
)
)
{
{
c
c
=
=
maximum
maximum
(
(
a
a
,
,
b
b
);
);
printf
printf
(
(
"The
"The
max is %d
max is %d
\
\
n"
n"
,
,
c
c
)
)
}
}
Function is
Function is
declared
declared
and
and
defined
defined
before
before
it
it
is used in main()
is used in main()
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 213 1317 CPL
Example 2
Functions
Declaration and Use: Example 2
int
int
a
a
=
=
5
5
,
,
b
b
=
=
10
10
,
,
c
c
;
;
int
int
maximum
maximum
(
(
int
int
x
x
,
,
int
int
y
y
);
);
int
int
main
main
(
(
void
void
)
)
{
{
c
c
=
=
maximum
maximum
(
(
a
a
,
,
b
b
);
);
printf
printf
(
(
"The
"The
max is %d
max is %d
\
\
n"
n"
,
,
c
c
)
)
}
}
int
int
maximum
maximum
(
(
int
int
x
x
,
,
int
int
y
y
)
)
{
{
return
return
((
((
x
x
>=
>=
y
y
) ?
) ?
x
x
:
:
y
y
);
);
}
}
Function is
Function is
defined
defined
after
after
it is
it is
used in main()
used in main()
Function is
Function is
declared
declared
with
with
prototype
prototype
before
before
use in main()
use in main()
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 214 1317 CPL
Functions
Passing Parameters by Value
Parameters passed to a function are
passed by value
Values passed to a function are copied
into the local parameter variables
The original variable that is passed to a
function cannot be modified by the
function since only a copy of its value was
passed
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 215 1317 CPL
Example
Functions
Passing Parameters by Value
The
The
value
value
of
of
a
a
is
is
copied
copied
into
into
x
x
.
.
The
The
value
value
of
of
b
b
is
is
copied
copied
into
into
y
y
.
.
The function does not change
The function does not change
the value of
the value of
a
a
or
or
b
b
.
.
int
int
a
a
,
,
b
b
,
,
c
c
;
;
int
int
foo
foo
(
(
int
int
x
x
,
,
int
int
y
y
)
)
{
{
x
x
=
=
x
x
+
+
(++
(++
y
y
);
);
return
return
x
x
;
;
}
}
int
int
main
main
(
(
void
void
)
)
{
{
a
a
=
=
5
5
;
;
b
b
=
=
10
10
;
;
c
c
=
=
foo
foo
(
(
a
a
,
,
b
b
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 216 1317 CPL
Example
Functions
Recursion
A function can call itself repeatedly
Useful for iterative computations (each
action stated in terms of previous result)
Example: Factorials (5! = 5 * 4 * 3 * 2 * 1)
long int
long int
factorial(
factorial(
int
int
n
n
)
)
{
{
if
if
(
(
n
n
<=
<=
1
1
)
)
return
return
(
(
1
1
);
);
else
else
return
return
(
(
n
n
*
*
factorial(
factorial(
n
n
-
-
1
1
)
)
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 217 1317 CPL
Functions
Evaluation of Recursive Functions
Evaluation of 5!
(based on code from previous slide)
1
1 [0]
1! = = 1
2 * 1!
2 * 1! [1]
2! = = 2 * 1 = 2
3 * 2!
3 * 2! [2]
3! = = 3 * 2 = 6
4 * 3!
4 * 3! [3]
4! = = 4 * 6 = 24
5 * 4!
5 * 4! [4]
5! = = 5 * 24 = 120
Recursive
iterations of
function
Result
evaluated from
TOS downward
Partial results
pushed on stack
Factorial term
replaced with result
of expression above
Conceptual evaluation of recursive function
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 218 1317 CPL
Functions and Scope
Parameters
A function's parameters are local to the
function
they have no meaning outside
the function itself
Parameter names may have the same
identifier as a variable declared outside
the function
the parameter names will
take precedence inside the function
int
n;
long int
factorial(int
n){}
These are not the same n.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 219 1317 CPL
Example
Functions and Scope
Variables Declared Within a Function
Variables declared within a function block
are local to the function
int
int
x
x
,
,
y
y
,
,
z
z
;
;
int
int
foo
foo
(
(
int
int
n
n
)
)
{
{
int
int
a
a
;
;
a
a
+=
+=
n
n
;
;
}
}
The
The
n
n
refers to the function parameter
refers to the function parameter
n
n
The
The
a
a
refers to the
refers to the
a
a
declared locally
declared locally
within the function body
within the function body
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 220 1317 CPL
Example
Functions and Scope
Variables Declared Within a Function
Variables declared within a function block
are not accessible outside the function
This will generate an error. This will generate an error.
a
a
may not may not
be accessed outside of the function be accessed outside of the function
where it was declared. where it was declared.
int
int
x
x
;
;
int
int
foo
foo
(
(
int
int
n
n
)
)
{
{
int
int
a
a
;
;
return
return
(
(
a
a
+=
+=
n)
n)
;
;
}
}
int
int
main
main
(
(
void
void
)
)
{
{
x
x
=
=
foo
foo
(
(
5
5
);
);
x
x
=
=
a
a
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 221 1317 CPL
Example
Functions and Scope
Global versus Local Variables
int
int
x
x
=
=
5
5
;
;
int
int
foo
foo
(
(
int
int
y
y
)
)
{
{
int
int
z
z
=
=
1
1
;
;
return
return
(
(
x
x
+
+
y
y
+
+
z
z
);
);
}
}
int
int
main
main
(
(
void
void
)
)
{
{
int
int
a
a
=
=
2
2
;
;
x
x
=
=
foo
foo
(
(
a
a
);
);
a
a
=
=
foo
foo
(
(
x
x
);
);
}
}
x
can be seen by everybody
x x
can be seen by everybody can be seen by everybody
foo's
local parameter is y
foo's
local variable is z
foo
cannot see main's a
foo
can see x
foo foo's 's
local parameter is local parameter is y y
foo foo's 's
local variable is local variable is z z
foo foo
cannot see cannot see main main's 's a a
foo foo
can see can see x x
main's local variable is a
main
cannot see foo's
y
or z
main
can see x
main main's local variable is 's local variable is a a
main main
cannot see cannot see foo foo's 's
y y
or or z z
main main
can see can see x x
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 222 1317 CPL
Functions and Scope
Parameters
"Overloading" variable names:
A locally defined identifier takes precedence over a
globally defined identifier.
int
int
n
n
;
;
int
int
foo
foo
(
(
int
int
n
n
)
)
{
{
y
y
+=
+=
n
n
;
;
}
}
n
Declared Locally and Globally n
Declared Globally Only
int
int
n
n
;
;
int
int
foo
foo
(
(
int
int
x
x
)
)
{
{
y
y
+=
+=
n
n
;
;
}
}
local local n n
hides hides
global global n n
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 223 1317 CPL
Example
int
int
n
n
;
;
int
int
foo
foo
(
(
int
int
n
n
)
)
{
{
y
y
+=
+=
n
n
;
;
}
}
int
int
bar
bar
(
(
int
int
n
n
)
)
{
{
z
z
*=
*=
n
n
;
;
}
}
Functions and Scope
Parameters
Different functions
may use the same
parameter names
The function will
only use its own
parameter by that
name
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 224 1317 CPL
Functions and Scope
#define
Within a Function
Running this code will
result in the following
output in the Uart1 IO
window:
Why?
Remember: #define
is
used by the preprocessor
to do text substitution
before the code is
compiled.
#define
#define
x
x
2
2
void
void
test(
test(
void
void
)
)
{
{
#define
#define
x
x
5
5
printf
printf
(
(
"%d
"%d
\
\
n"
n"
,
,
x
x
);
);
}
}
void
void
main
main
(
(
void
void
)
)
{
{
printf
printf
(
(
"%d
"%d
\
\
n"
n"
,
,
x
x
);
);
test
test
();
();
}
}
Example
5
5
5
5
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 225 1317 CPL
Functions
Historical Note
C originally defined functions like this:
Do not use the old method
use the new
one only:
int
int
maximum
maximum
(
(
x
x
,
,
y
y
)
)
int
int
x
x
,
,
int
int
y
y
{
{
return
return
((
((
x
x
>=
>=
y
y
) ?
) ?
x
x
:
:
y
y
);
);
}
}
int
int
maximum
maximum
(
(
int
int
x
x
,
,
int
int
y
y
)
)
{
{
return
return
((
((
x
x
>=
>=
y
y
) ?
) ?
x
x
:
:
y
y
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 226 1317 CPL
Lab Exercise 8
Lab Exercise 8
Functions
Functions
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 227 1317 CPL
Lab 08
Functions
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab08
Lab08
\
\
Lab08.mcw
Lab08.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 228 1317 CPL
Lab 08
Functions
/ *############################################################################
# STEP 1: Wr i t e t wo f unct i on pr ot ot ypes based on t he f ol l owi ng i nf or mat i on:
# + Funct i on Name: mul t i pl y_f unct i on( )
# - Par amet er s: i nt x, i nt y
# - Ret ur n t ype: i nt
# + Funct i on Name: di vi de_f unct i on( )
# - Par amet er s: f l oat x, f l oat y
# - Ret ur n t ype: f l oat
############################################################################*/
int multiply_function( int x, int y); / / mul t i pl y_f unct i on( ) pr ot ot ype
float divide_function( float x, float y ); / / di vi de_f unct i on( ) pr ot ot ype
Solution: Step 1
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 229 1317 CPL
Lab 08
Functions
/ *############################################################################
# STEP 2: Cal l t he mul t i pl y_f unct i on( ) and di vi de_f unct i on( ) .
# ( a) Pass t he var i abl es i nt Var i abl e1 and i nt Var i abl e2 t o t he
# mul t i pl y_f unct i on( ) .
# ( b) St or e t he r esul t of mul t i pl y_f unct i on( ) i n t he var i abl e " pr oduct " .
# ( c) Pass t he var i abl es f l oat Var i abl e1 and f l oat Var i abl e2 t o t he
# di vi de_f unct i on( ) .
# ( d) St or e t he r esul t of di vi de_f unct i on( ) i n t he var i abl e " quot i ent " .
############################################################################*/
/ / Cal l mul t i pl y_f unct i on
product = multiply_function( intVariable1 , intVariable2 );
/ / Cal l di vi de_f unct i on
quotient = divide_function( floatVariable1 , floatVariable2 );
/ / i nt Quot i ent wi l l be 0 si nce i t i s an i nt eger
i nt Quot i ent = di vi de_f unct i on( f l oat Var i abl e1 , f l oat Var i abl e2 ) ;
Solution: Step 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 230 1317 CPL
Lab 08
Functions
/ *############################################################################
# STEP 3: Wr i t e t he f unct i on mul t i pl y_f unct i on( ) . Use t he f unct i on pr ot ot ype
# you wr ot e i n STEP 1 as t he f unct i on header . I n t he body, al l you
# need t o do i s r et ur n t he pr oduct of t he t wo i nput par amet er s ( x * y)
############################################################################*/
/ / Funct i on Header
int multiply_function( int x, int y)
{
return (x * y); / / Funct i on Body
}
/ *############################################################################
# STEP 4: Wr i t e t he f unct i on di vi de_f unct i on( ) . Use t he f unct i on pr ot ot ype
# you wr ot e i n STEP 1 as t he f unct i on header . I n t he body, al l you
# need t o do i s r et ur n t he quot i ent of t he t wo i nput par amet er s ( x / y)
############################################################################*/
/ / Funct i on Header
float divide_function( float x, float y )
{
return (x / y); / / Funct i on Body
}
Solution: Steps 3 and 4
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 231 1317 CPL
Lab 08
Conclusions
Functions provide a way to modularize
code
Functions make code easier to maintain
Functions promote code reuse
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 232 1317 CPL
Multi-File Projects and
Storage Class Specifiers
Multi-File Projects and
Storage Class Specifiers
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 233 1317 CPL
Storage Class Specifiers
Scope and Lifetime of Variables
Scope and lifetime of a variable depends
on its storage class:
Automatic Variables
Static Variables
External Variables
Register Variables
Scope refers to where in a program a
variable may be accessed
Lifetime refers to how long a variable will
exist or retain its value
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 234 1317 CPL
Storage Class Specifiers
Automatic Variables
Local variables declared inside a function
Created when function called
Destroyed when exiting from function
auto
keyword usually not required
local
variables are automatically automatic*
Typically created on the stack
int
foo(int
x,
int
y)
{
int
a,
b;
...
Automatic Variables
*Except when the compiler provides an option to make parameters and locals static by default.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 235 1317 CPL
Storage Class Specifiers
auto
Keyword with Variables
auto
is almost never used
Many books claim it has no use at all
Some compilers still use auto
to explicitly
specify that a variable should be allocated
on the stack when a different method of
parameter passing is used by default
int
foo(auto
int
x,
auto
int
y)
{
...
;
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 236 1317 CPL
int
x;
int
main(void)
{
...
Storage Class Specifiers
Static Variables
Given a permanent address in memory
Exist for the entire life of the program
Created when program starts
Destroyed when program ends
Global variables are always
static (cannot
be made automatic using auto)
Global variable is always static
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 237 1317 CPL
Storage Class Specifiers
static
Keyword with Variables
A variable declared as static
inside a
function retains its value between function
calls (not destroyed when exiting function)
Function parameters cannot be static
with some compilers (MPLAB-C30)
a
will remember its value
from the last time the
function was called.
If given an initial value, it
is only initialized when
first created
not during
each function call
int
foo(int
x)
{
static int
a =
0;
...
a
+=
x;
return
a;
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 238 1317 CPL
Storage Class Specifiers
External Variables
Variables that are defined outside the
scope where they are used
Still need to be declared within the scope
where they are used
extern
keyword used to tell compiler that
a variable defined elsewhere will be used
within the current scope
extern type identifier;
extern int
x;
External Variable
Declaration Syntax:
External Variable
Declaration Example:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 239 1317 CPL
Example
Storage Class Specifiers
External Variables
A variable declared as extern
within a
function is analogous to a function
prototype
the variable may be defined
outside the function after it is used
int int
foo foo( (int int
x x) )
{ {
extern int extern int
a a; ;
... ...
return return
a a; ;
} }
int int
a a; ;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 240 1317 CPL
SomeFileInProject.c Main.c
Storage Class Specifiers
External Variables
A variable declared as extern
outside of
any function is used to indicate that the
variable is defined in another source file
memory only allocated when it's defined
extern int
x;
int
main(void)
{
x
=
5;
...
}
int
x;
int
foo(void)
{
...
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 241 1317 CPL
Storage Class Specifiers
Register Variables
register
variables are placed in a processor's
"hardware registers" for higher speed access
than with external RAM (mostly used for
microprocessors)
Doesn't usually make sense in embedded
microcontroller system where RAM is integrated
into processor package
May be done with PIC
MCUs/dsPIC
DSCs, but it
is architecture/compiler specific
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 242 1317 CPL
Storage Class Specifiers
Scope of Functions
Scope of a function depends on its
storage class:
Static Functions
External Functions
Scope of a function is either local to the
file where it is defined (static) or globally
available to any file in a project (external)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 243 1317 CPL
Main.c SomeFileInProject.c
Storage Class Specifiers
External Functions
Functions by default have global scope
within a project
extern
keyword not required, but function
prototype is required in calling file (or .h)
int
foo(void);
int
main(void)
{
...
x =
foo();
}
int
foo(void)
{
...
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 244 1317 CPL
SomeFileInProject.c Main.c
Storage Class Specifiers
Static Functions
If a function is declared as static, it will
only be available within the file where it
was declared (makes it a local function)
int
foo(void);
int
main(void)
{
...
x =
foo();
}
static int
foo(void)
{
...
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 245 1317 CPL
Storage Class Specifiers
Library Files and Header Files
#include <LibFile.h>
int
x;
int
main(void)
{
x =
foo();
myVar
=
x;
}
Main.c
int
myVar;
int
foo(void)
{
}
LibFile.c
extern int
myVar;
int
foo(void);
LibFile.h
DEFINITIONS
DEFINITIONS
DECLARATIONS
DECLARATIONS
USE
USE
INCLUDE
DECLARATIONS
INCLUDE
DECLARATIONS
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 246 1317 CPL
Lab Exercise 9
Lab Exercise 9
Multi-File Projects
Multi-File Projects
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 247 1317 CPL
Lab 09
Multi-File Projects
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab09
Lab09
\
\
Lab09.mcw
Lab09.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 248 1317 CPL
Lab 09
Multi-File Projects
/ *############################################################################
# STEP 1a: Add var i abl e decl ar at i ons t o make t he var i abl es def i ned i n
# Fi l e1_09. c avai l abl e t o any C sour ce f i l e t hat i ncl udes t hi s
# header f i l e. ( i nt Var i abl e1, i nt Var i abl e2, pr oduct )
############################################################################*/
/ / Ref er ence t o ext er nal l y def i ned " i nt Var i abl e1"
extern int
intVariable1;
/ / Ref er ence t o ext er nal l y def i ned " i nt Var i abl e2"
extern int
intVariable2;
/ / Ref er ence t o ext er nal l y def i ned " pr oduct "
extern int
product;
/ *###############################################################################
# STEP 1b: Add a f unct i on pr ot ot ype t o make mul t i pl y_f unct i on( ) def i ned i n
# Fi l e1_09. c avai l abl e t o any C sour ce f i l e t hat i ncl udes t hi s header
# f i l e.
###############################################################################*/
/ / Funct i on pr ot ot ype f or mul t i pl y_f unct i on( )
int
multiply_function(int
x, int
y);
Solution: Step 1a and 1b (File1_09.h)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 249 1317 CPL
Lab 09
Multi-File Projects
/ *############################################################################
# STEP 2a: Add var i abl e decl ar at i ons t o make t he var i abl es def i ned i n
# Fi l e2_09. c avai l abl e t o any C sour ce f i l e t hat i ncl udes t hi s header
# f i l e. ( f l oat Var i abl e1, f l oat Var i abl e2, quot i ent , i nt Quot i ent )
############################################################################*/
/ / Ref er ence t o ext er nal l y def i ned " f l oat Var i abl e1"
extern float
floatVariable1;
/ / Ref er ence t o ext er nal l y def i ned " f l oat Var i abl e2"
extern float
floatVariable2;
/ / Ref er ence t o ext er nal l y def i ned " quot i ent "
extern float
quotient;
/ / Ref er ence t o ext er nal l y def i ned " i nt Quot i ent "
extern int
intQuotient;
/ *############################################################################
# STEP 2b: Add a f unct i on pr ot ot ype t o make di vi de_f unct i on( ) def i ned i n
# Fi l e2_09. c avai l abl e t o any C sour ce f i l e t hat i ncl udes t hi s header
# f i l e.
############################################################################*/
/ / Funct i on pr ot ot ype f or di vi de_f unct i on( )
float
divide_function(float
x, float
y );
Solution: Step 2a and 2b (File2_09.h)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 250 1317 CPL
Lab 09
Conclusions
Multi-file projects take the concept of
functions further, by providing an
additional level of modularization
Globally declared variables and all normal
functions are externally available if extern
declarations and function prototypes are
available
Static functions are not available
externally
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 251 1317 CPL
Arrays
Arrays
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 252 1317 CPL
Definition
Arrays
Arrays:
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
Arrays
Arrays
are variables that can store many items of the same
are variables that can store many items of the same
type. The individual items known as
type. The individual items known as
elements
elements
, are stored
, are stored
sequentially and are uniquely identified by the array
sequentially and are uniquely identified by the array
index
index
(sometimes called a
(sometimes called a
subscript
subscript
).
).
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 253 1317 CPL
Syntax
Example
size refers to the number of elements
size must be a constant integer
Arrays
How to Create an Array
int int
a[10] a[10]; ; // An array that can hold 10 integers // An array that can hold 10 integers
char char
s[25] s[25]; ; // An array that can hold 25 characters // An array that can hold 25 characters
type
type
arrayName
arrayName
[
[
size
size
];
];
Arrays are declared much like ordinary variables:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 254 1317 CPL
Syntax
Example
Arrays
How to Initialize an Array at Declaration
int int
a a[ [5 5] = ] =
{ {10 10, ,
20 20, ,
30 30, ,
40 40, ,
50 50}; };
char char
b b[ [5 5] = ] =
{ {'a' 'a', ,
'b' 'b', ,
'c' 'c', ,
'd' 'd', ,
'e' 'e'}; };
type
type
arrayName
arrayName
[
[
size
size
] = {
] = {
item
item
1 1
,
,
,
,
item
item
n n
};
};
Arrays may be initialized with a list when declared:
The items must all match the type of the array
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 255 1317 CPL
Example
Syntax
Arrays
How to Use an Array
int int
i i, ,
a a[ [10 10]; ]; //An array that can hold 10 integers //An array that can hold 10 integers
for for( (i i
= =
0 0; ;
i i
< <
10 10; ;
i i++) { ++) {
a a[ [i i] = ] =
0 0; ;
//Initialize all array elements to 0 //Initialize all array elements to 0
} }
a a[ [4 4] = ] =
42 42; ;
//Set fifth element to 42 //Set fifth element to 42
arrayName
arrayName
[
[
index
index
]
]
Arrays are accessed like variables, but with an index:
index may be a variable or a constant
The first element in the array has an index of 0
C does not provide any bounds checking
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 256 1317 CPL
Example
Syntax
Arrays
Creating Multidimensional Arrays
Arrays may have any number of dimensions
Three dimensions tend to be the largest used in
common practice
int int
a a[ [10 10][ ][10 10]; ]; //10x10 array for 100 integers //10x10 array for 100 integers
float float
b b[ [10 10][ ][10 10][ ][10 10]; ]; //10x10x10 array for 1000 floats //10x10x10 array for 1000 floats
type
type
arrayName
arrayName
[
[
size
size
1 1
]...[
]...[
size
size
n n
];
];
Add additional dimensions to an array declaration:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 257 1317 CPL
Syntax
Example
Arrays
Initializing Multidimensional Arrays at Declaration
char char
a a[ [3 3][ ][3 3] = ] =
{{ {{'X' 'X', ,
'O' 'O', ,
'X' 'X'}, },
{ {'O' 'O', ,
'O' 'O', ,
'X' 'X'}, },
{ {'X' 'X', ,
'X' 'X', ,
'O' 'O'}}; }};
int int
b b[ [2 2][ ][2 2][ ][2 2] = {{{ ] = {{{0 0, , 1 1},{ },{2 2, , 3 3}},{{ }},{{4 4, , 5 5},{ },{6 6, , 7 7}}}; }}};
type
type
arrayName
arrayName
[
[
size
size
0 0
]
]
[
[
size
size
n n
] =
] =
{{
{{
item
item
,
,
,
,
item
item
},
},
{
{
item
item
,
,
,
,
item
item
}};
}};
Arrays may be initialized with lists within a list:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 258 1317 CPL
Arrays
Visualizing 2-Dimensional Arrays
6
a[0][0] = 0;
a[0][1] = 1;
a[0][2] = 2;
a[1][0] = 3;
a[1][1] = 4;
a[1][2] = 5;
a[2][0] = 6;
a[2][1] = 7;
a[2][2] = 8;
y
x 0
0
1
1
0 1
3 4
a[y][x]
Row, Column
Column
R
o
w
R
o
w
0
R
o
w
1
2
5
7 8
2
2
R
o
w
2
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
int
a[3][3] = {{0, 1,
2},
{3, 4,
5},
{6, 7,
8}};
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 259 1317 CPL
a[0][0][0] = 0;
a[0][0][1] = 1;
a[0][1][0] = 2;
a[0][1][1] = 3;
a[1][0][0] = 4;
a[1][0][1] = 5;
a[1][1][0] = 6;
a[1][1][1] = 7;
Arrays
Visualizing 3-Dimensional Arrays
z
y
x
0
1
0
0
1
1
0
1
2
3
4
5
7
a[z][y][x]
Plane, Row, Column
P
l
a
n
e
C
o
l
u
m
n
R
o
w
P
l
a
n
e
0
P
l
a
n
e
1
0
,
0
,
0
0
,
0
,
1
0
,
1
,
0
0
,
1
,
1
1
,
1
,
1
1
,
0
,
1
int
a[2][2][2] = {{{0, 1},{2, 3}},
{{4, 5},{6, 7}}};
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 260 1317 CPL
Arrays
Example of Array Processing
/************************************************** /**************************************************
* Print out 0 to 90 in increments of 10 * Print out 0 to 90 in increments of 10
**************************************************/ **************************************************/
int int
main main( (void void) )
{ {
int int
i i = =
0 0; ;
int int
a a[ [10 10] = { ] = {0 0, ,1 1, ,2 2, ,3 3, ,4 4, ,5 5, ,6 6, ,7 7, ,8 8, ,9 9}; };
while while
( (i i < <
10 10) )
{ {
a a[ [i i] *= ] *=
10 10; ;
printf printf( ("%d "%d\ \n" n", , a a[ [i i]); ]);
i i++; ++;
} }
while while
( (1 1); );
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 261 1317 CPL
Definition
Strings
Character Arrays and Strings
Strings:
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
Strings
Strings
are arrays of
are arrays of
char
char
whose last element is a null
whose last element is a null
character
character
'
'
\
\
0'
0'
with an ASCII value of 0. C has no native
with an ASCII value of 0. C has no native
string data type, so strings must always be treated as
string data type, so strings must always be treated as
character arrays.
character arrays.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 262 1317 CPL
Syntax
Example
Strings
Creating a String Character Array
char char
str1 str1[ [10 10]; ]; //Holds 9 characters plus ' //Holds 9 characters plus '\ \0' 0'
char char
str2 str2[ [6 6]; ]; //Holds 5 characters plus ' //Holds 5 characters plus '\ \0' 0'
char
char
arrayName
arrayName
[
[
length
length
];
];
Strings are created like any other array of char:
length must be one larger than the length of the string
to accommodate the terminating null character '\0'
A char
array with n elements holds strings with n-1 char
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 263 1317 CPL
Example
Syntax
Strings
How to Initialize a String at Declaration
char char
str1 str1[] = [] =
"Microchip" "Microchip"; ; //10 chars "Microchip //10 chars "Microchip\ \0" 0"
char char
str2 str2[ [6 6] = ] =
"Hello" "Hello"; ; //6 chars "Hello //6 chars "Hello\ \0" 0"
//Alternative string declaration //Alternative string declaration
size required size required
char char
str3 str3[ [4 4] = ] =
{ {'P' 'P', ,
'I' 'I', ,
'C' 'C', ,
' '\ \0' 0'}; };
char
char
arrayName
arrayName
[] =
[] =
"Microchip"
"Microchip"
;
;
Character arrays may be initialized with string literals:
Array size is not required
Size automatically determined by length of string
NULL character '\0'
is automatically appended
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 264 1317 CPL
Syntax
Example
Strings
How to Initialize a String in Code
str str[ [0 0] = ] =
'H' 'H'; ;
str str[ [1 1] = ] =
'e' 'e'; ;
str str[ [2 2] = ] =
'l' 'l'; ;
str str[ [3 3] = ] =
'l' 'l'; ;
str str[ [4 4] = ] =
'o' 'o'; ;
str str[ [5 5] = ] =
' '\ \0' 0'; ;
arrayName
arrayName
[
[
0
0
] =
] =
char
char
1 1
;
;
arrayName
arrayName
[
[
1
1
] =
] =
char
char
2 2
;
;
arrayName
arrayName
[
[
n
n
] =
] =
'
'
\
\
0'
0'
;
;
In code, strings must be initialized element by element:
Null character '\0'
must be appended manually
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 265 1317 CPL
Example
Strings
Comparing Strings
Strings cannot be compared using
relational operators (==, !=, etc.)
Must use standard C library string
manipulation functions
strcmp()
returns 0 if strings equal
char char
str str[] = [] =
"Hello" "Hello"; ;
if if ( (! !strcmp strcmp( (
str str, , "Hello" "Hello")) ))
printf printf( ("The "The
string is string is \ \"% "%s s\ \". ".\ \n n" ", , str str); );
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 266 1317 CPL
Functions
Array Parameters
Arrays are passed by reference rather than by
value for greater efficiency
A pointer to the array, rather than the array itself
is passed to the function
void
WriteLCD(char
greetings[]){}
This declaration
void
WriteLCD(char
*greetings){}
is equivalent to this declaration.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 267 1317 CPL
Lab Exercise 10
Lab Exercise 10
Arrays
Arrays
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 268 1317 CPL
Lab 10
Arrays
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab10
Lab10
\
\
Lab10.mcw
Lab10.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 269 1317 CPL
Lab 10
Arrays
/ *############################################################################
# STEP 1: Cr eat e t wo i ni t i al i zed ar r ays wi t h 10 el ement s each named ar r ay1 and
# ar r ay2 ( you may use t he pr e- def i ned const ant ARRAY_SI ZE as par t of
# t he ar r ay decl ar at i on) .
# The ar r ays shoul d be i ni t i al i zed wi t h t he f ol l owi ng val ues:
# + ar r ay1: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# + ar r ay2: 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
# Not e: t he el ement s ar e al l of t ype i nt
############################################################################*/
/ / ar r ay1 decl ar at i on & def i ni t i on
int
array1[ARRAY_SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
/ / ar r ay2 decl ar at i on & def i ni t i on
int
array2[ARRAY_SIZE] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
Solution: Step 1
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 270 1317 CPL
Lab 10
Arrays
/ *############################################################################
# STEP 2: Pass t he t wo ar r ays you decl ar ed above ( ar r ay1 & ar r ay2) t o t he
# f unct i on add_f unct i on( ) ( see i t s def i ni t i on bel ow) . St or e t he
# r esul t of t he f unct i on cal l i n t he ar r ay r esul t [ ] . The i dea her e i s
# t o add each cor r espondi ng el ement of ar r ay1 and ar r ay2 and st or e t he
# r esul t i n r esul t [ ] . I n ot her wor ds, add t he f i r st el ement of
# ar r ay1[ ] t o t he f i r st el ement of ar r ay2[ ] and st or e t he r esul t i n
# t he f i r st el ement of r esul t [ ] . Next add t he second el ement s
############################################################################*/
/ / r esul t = sumof el ement s of ar r ay1 & ar r ay2
result[i] = add_function(array1[i], array2[i]);
i++;
Solution: Step 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 271 1317 CPL
Lab 10
Conclusions
Arrays may be used to store a group of
related variables of the same type under a
common name
Individual elements are accessed by using
the array index in conjunction with the
array name
Arrays may be used in many places that
an ordinary variable would be used
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 272 1317 CPL
Data Pointers
Data Pointers
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 273 1317 CPL
Pointers
A Variable's Address versus A Variable's Value
In some situations, we will want to work with a
variable's address in memory, rather than the
value it contains
005A
Address
16-bit Data Memory
(RAM)
0x0802
0x0804
0x0806
0x0808
0x0800
x
Variable stored
at Address
0123
DEAD
BEEF
F00D
0456
0x080A
Variable name
from C code
int x;
Value of
variable x
= 0x0123
Address of
variable x
= 0x0802
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 274 1317 CPL
Pointers
What are Pointers?
A pointer is a variable or constant that holds the
address of another variable or function
FFFF
Address
16-bit Data Memory
(RAM)
0x0802
0x0804
0x0806
0x0808
0x0800
x
p
Variable at
Address
0123
FFFF
0802
FFFF
FFFF
0x080A
Integer Variable:
Pointer Variable:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 275 1317 CPL
Pointers
What Do They Do?
A pointer allows us to indirectly access a
variable (just like indirect addressing in assembly language)
005A
Address
16-bit Data Memory
(RAM)
0x0802
0x0804
0x0806
0x0808
0x0800
x
0123
DEAD
0802
F00D
0456
0x080A
p
x = 0x0123;
*p = 0x0123;
Direct Access
via x
Direct Access
via x
Indirect Access
via *p
Indirect Access
via *p
p
points to x
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 276 1317 CPL
Pointers
Why Would I Want to Do That?
Pointers make it possible to write a very
short loop that performs the same task on
a range of memory locations/variables.
Example: Data Buffer
//Point to RAM buffer starting address //Point to RAM buffer starting address
char char
* *bufPtr bufPtr
= =
& &buffer buffer; ;
while while
(( ((DataAvailable DataAvailable) )
&& ( && (ReceivedCharacter ReceivedCharacter
!= !=
' '\ \0' 0')) ))
{ {
//Read byte from UART and write it to RAM buffer //Read byte from UART and write it to RAM buffer
ReadUART ReadUART( (bufPtr bufPtr); );
//Point to next available byte in RAM buffer //Point to next available byte in RAM buffer
bufPtr bufPtr++; ++;
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 277 1317 CPL
Pointers
Why Would I Want to Do That?
Example: Data Buffer
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
0x08C8 0x08C8
0123
4567
89AB
CDEF
1357
9BDF
0246
8ACE
Pseudo
Pseudo
-
-
code:
code:
(1) (1)
Point arrow to first Point arrow to first
address of buffer address of buffer
(2) (2)
Write data from UART to Write data from UART to
location pointed to by location pointed to by
arrow arrow
(3) (3)
Move arrow to point to Move arrow to point to
next address in buffer next address in buffer
(4) (4)
Repeat until data from Repeat until data from
UART is 0, or buffer is full UART is 0, or buffer is full
(arrow points to last (arrow points to last
address of buffer) address of buffer)
RAM buffer allocated over RAM buffer allocated over
a range of addresses a range of addresses
(perhaps an array) (perhaps an array)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 278 1317 CPL
Pointers
Where Else Are They Used?
Used in conjunction with dynamic memory
allocation (creating variables at runtime)
Provide method to pass arguments by reference
to functions
Provide method to pass more than one piece of
information into and out of a function
A more efficient means of accessing arrays and
dealing with strings
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 279 1317 CPL
Example
Syntax
Pointers
How to Create a Pointer Variable
int int * *iPtr iPtr; ; // Create a pointer to int // Create a pointer to int
float float * *fPtr fPtr; ; // Create a pointer to float // Create a pointer to float
type
type
*
*
ptrName
ptrName
;
;
In the context of a declaration, the *
merely indicates
that the variable is a pointer
type is the type of data the pointer may point to
Pointer usually described as a pointer to type
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 280 1317 CPL
Example
Syntax
Pointers
How to Create a Pointer Type with typedef
typedef int typedef int * *intPtr intPtr; ; // Create pointer to int type // Create pointer to int type
intPtr intPtr
p p; ; // Create pointer to int // Create pointer to int
// Equivalent to: int *p; // Equivalent to: int *p;
typedef
typedef
type
type
*
*
typeName
typeName
;
;
A pointer variable can now be declared as type
typeName which is a synonym for type
The *
is no longer needed since typeName explicitly
identifies the variable as a pointer to type
No No * *
is used is used
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 281 1317 CPL
To set a pointer to point to another
variable, we use the &
operator (address
of), and the pointer variable is used
without
the dereference operator *:
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;)
Pointers
Initialization
p
p
= &
= &
x
x
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 282 1317 CPL
Pointers
Usage
When accessing the variable pointed to by
a pointer, we use the pointer with
the
dereference operator *:
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)
y
y
= *
= *
p
p
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 283 1317 CPL
Example
Pointers
Another Way To Look At The Syntax
&x
is a constant pointer
It represents the address of x
The address of x
will never change
p
is a variable pointer to int
It can be assigned the address of any int
It may be assigned a new address any time
int
int
x
x
,
,
*
*
p
p
;
;
//int and a pointer to int
//int and a pointer to int
p
p
=
=
&x
&x
;
;
//Assign p the address of x
//Assign p the address of x
*
*
p
p
=
=
5
5
;
;
//Same as x = 5;
//Same as x = 5;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 284 1317 CPL
Example
Pointers
Another Way To Look At The Syntax
*p
represents the data pointed to by p
*p
may be used anywhere you would use x
*
is the dereference operator, also called the
indirection operator
In the pointer declaration, the only significance of *
is
to indicate that the variable is a pointer rather than an
ordinary variable
int
int
x
x
,
,
*
*
p
p
;
;
//1 int, 1 pointer to int
//1 int, 1 pointer to int
p
p
=
=
&
&
x
x
;
;
//Assign p the address of x
//Assign p the address of x
*p
*p
= 5
= 5
;
;
//Same as x = 5;
//Same as x = 5;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 286 1317 CPL
Example
Pointers
How Pointers Work
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
{
{
int
int
x
x
,
,
y
y
;
;
int
int
*
*
p
p
;
;
x
x
=
=
0xDEAD
0xDEAD
;
;
y
y
=
=
0xBEEF
0xBEEF
;
;
p
p
=
=
&
&
x
x
;
;
*
*
p
p
=
=
0x0100
0x0100
;
;
p
p
=
=
&
&
y
y
;
;
*
*
p
p
=
=
0x0200
0x0200
;
;
}
}
x
x
y
y
p
p
Variable at Variable at
Address Address
0x08C8 0x08C8
0000
0000
0000
0000
0000
0000
0000
0000
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 287 1317 CPL
Example
Pointers
How Pointers Work
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
x
x
y
y
p
p
Variable at Variable at
Address Address
0x08C8 0x08C8
0000
DEAD
0000
0000
0000
0000
0000
0000
{
{
int
int
x
x
,
,
y
y
;
;
int
int
*
*
p
p
;
;
x
x
=
=
0xDEAD
0xDEAD
;
;
y
y
=
=
0xBEEF
0xBEEF
;
;
p
p
=
=
&
&
x
x
;
;
*
*
p
p
=
=
0x0100
0x0100
;
;
p
p
=
=
&
&
y
y
;
;
*
*
p
p
=
=
0x0200
0x0200
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 288 1317 CPL
Example
Pointers
How Pointers Work
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
x
x
y
y
p
p
Variable at Variable at
Address Address
0x08C8 0x08C8
0000
DEAD
BEEF
0000
0000
0000
0000
0000
{
{
int
int
x
x
,
,
y
y
;
;
int
int
*
*
p
p
;
;
x
x
=
=
0xDEAD
0xDEAD
;
;
y
y
=
=
0xBEEF
0xBEEF
;
;
p
p
=
=
&
&
x
x
;
;
*
*
p
p
=
=
0x0100
0x0100
;
;
p
p
=
=
&
&
y
y
;
;
*
*
p
p
=
=
0x0200
0x0200
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 289 1317 CPL
Example
Pointers
How Pointers Work
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
x
x
y
y
p
p
Variable at Variable at
Address Address
0x08C8 0x08C8
0000
DEAD
BEEF
08BC
0000
0000
0000
0000
{
{
int
int
x
x
,
,
y
y
;
;
int
int
*
*
p
p
;
;
x
x
=
=
0xDEAD
0xDEAD
;
;
y
y
=
=
0xBEEF
0xBEEF
;
;
p
p
=
=
&x
&x
;
;
*
*
p
p
=
=
0x0100
0x0100
;
;
p
p
=
=
&
&
y
y
;
;
*
*
p
p
=
=
0x0200
0x0200
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 290 1317 CPL
Example
Pointers
How Pointers Work
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
x
x
y
y
p
p
Variable at Variable at
Address Address
0x08C8 0x08C8
0000
0100
BEEF
08BC
0000
0000
0000
0000
{
{
int
int
x
x
,
,
y
y
;
;
int
int
*
*
p
p
;
;
x
x
=
=
0xDEAD
0xDEAD
;
;
y
y
=
=
0xBEEF
0xBEEF
;
;
p
p
=
=
&
&
x
x
;
;
*p
*p
=
=
0x0100
0x0100
;
;
p
p
=
=
&
&
y
y
;
;
*
*
p
p
=
=
0x0200
0x0200
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 291 1317 CPL
Example
Pointers
How Pointers Work
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
x
x
y
y
p
p
Variable at Variable at
Address Address
0x08C8 0x08C8
0000
0100
BEEF
08BE
0000
0000
0000
0000
{
{
int
int
x
x
,
,
y
y
;
;
int
int
*
*
p
p
;
;
x
x
=
=
0xDEAD
0xDEAD
;
;
y
y
=
=
0xBEEF
0xBEEF
;
;
p
p
=
=
&
&
x
x
;
;
*
*
p
p
=
=
0x0100
0x0100
;
;
p
p
=
=
&y
&y
;
;
*
*
p
p
=
=
0x0200
0x0200
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 292 1317 CPL
Example
Pointers
How Pointers Work
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x08BC 0x08BC
0x08BE 0x08BE
0x08C0 0x08C0
0x08C2 0x08C2
0x08C4 0x08C4
0x08C6 0x08C6
0x08BA 0x08BA
x
x
y
y
p
p
Variable at Variable at
Address Address
0x08C8 0x08C8
0000
0100
0200
08BE
0000
0000
0000
0000
{
{
int
int
x
x
,
,
y
y
;
;
int
int
*
*
p
p
;
;
x
x
=
=
0xDEAD
0xDEAD
;
;
y
y
=
=
0xBEEF
0xBEEF
;
;
p
p
=
=
&
&
x
x
;
;
*
*
p
p
=
=
0x0100
0x0100
;
;
p
p
=
=
&
&
y
y
;
;
*p
*p
=
=
0x0200
0x0200
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 293 1317 CPL
Pointers and Arrays
A Quick Reminder
Array elements occupy consecutive memory
locations
Pointers can provide an alternate method for
accessing array elements
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x07FE 0x07FE
x
x
[
[
0
0
]
]
0x0806 0x0806
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
FFFF
FFFF
0001
0001
0002
0002
0003
0003
FFFF
FFFF
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 294 1317 CPL
Pointers and Arrays
Initializing a Pointer to an Array
The array name is the same thing as the
address of its first (0
th
) element
If we declare the following array and pointer variable:
We can initialize the pointer to point to the array using any
one of these three methods:
int
int
x
x
[
[
5
5
] = {
] = {
1
1
,
,
2
2
,
,
3
3
,
,
4
4
,
,
5
5
};
};
int
int
*
*
p
p
;
;
p
p
=
=
x
x
;
;
//Works only for arrays!
//Works only for arrays!
p
p
=
=
&
&
x
x
;
;
//Works for arrays or variables
//Works for arrays or variables
p
p
=
=
&
&
x
x
[
[
0
0
];
];
//This one is the most obvious
//This one is the most obvious
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 295 1317 CPL
Incrementing a pointer will move it to the
next element of the array
More on this in just a bit
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x07FE 0x07FE
x
x
[
[
0
0
]
]
0x0806 0x0806
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
FFFF
FFFF
0001
0001
0002
0002
0003
0003
FFFF
FFFF
Pointers and Arrays
A Preview of Pointer Arithmetic
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
*
*
p
p
;
;
p
p
= &
= &
x
x
;
;
p
p
++;
++;
p
p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 296 1317 CPL
Incrementing a pointer will move it to the
next element of the array
More on this in just a bit
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x07FE 0x07FE
x[0]
x[0]
0x0806 0x0806
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
FFFF
FFFF
0001
0001
0002
0002
0003
0003
0800
0800
Pointers and Arrays
A Preview of Pointer Arithmetic
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
*
*
p
p
;
;
p
p
= &
= &
x
x
;
;
p
p
++;
++;
p
p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 297 1317 CPL
Incrementing a pointer will move it to the
next element of the array
More on this in just a bit
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x07FE 0x07FE
x
x
[
[
0
0
]
]
0x0806 0x0806
x[1]
x[1]
x
x
[
[
2
2
]
]
FFFF
FFFF
0001
0001
0002
0002
0003
0003
0802
0802
Pointers and Arrays
A Preview of Pointer Arithmetic
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
*
*
p
p
;
;
p
p
= &
= &
x
x
;
;
p
p
++;
++;
p
p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 298 1317 CPL
Pointer Arithmetic
Incrementing Pointers
Incrementing or decrementing a pointer
will add or subtract a multiple of the
number of bytes of its type
If we have:
float
float
x
x
;
;
float
float
*
*
p
p
= &
= &
x
x
;
;
p
p
++;
++;
We will get p = &x +
4
since a float
variable occupies 4 bytes of memory
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 299 1317 CPL
Example
float a[4]
float a[5]
float a[6]
float a[7]
float a[8]
Pointer Arithmetic
Incrementing Pointers
float a[0]
float a[1]
float a[2]
float a[3]
ptr
= &a;
0x0050
0x0052
0x0054
0x0056
0x0058
0x005A
0x005C
0x005E
0x0060
0x0062
0x0064
0x0066
0x0068
0x006A
0x006C
0x006E
0x0070
0x0072
0x0074
0x0076
ptr++;
float *ptr;
Incrementing ptr
moves it
to the next sequential
float
array element
16-bit Data Memory Words
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 300 1317 CPL
Pointer Arithmetic
Larger Jumps
Adding or subtracting any other number
with the pointer will change it by a multiple
of the number of bytes of its type
If we have
int
int
x
x
;
;
int
int
*
*
p
p
= &
= &
x
x
;
;
p
p
+=
+=
3
3
;
;
We will get p =
&x +
6
since an int
variable occupies 2 bytes of memory
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 301 1317 CPL
Example
float a[4]
float a[5]
float a[6]
float a[7]
float a[8]
Pointer Arithmetic
Larger Jumps
float a[0]
float a[1]
float a[2]
float a[3]
ptr
= &a;
0x0050
0x0052
0x0054
0x0056
0x0058
0x005A
0x005C
0x005E
0x0060
0x0062
0x0064
0x0066
0x0068
0x006A
0x006C
0x006E
0x0070
0x0072
0x0074
0x0076
ptr
+= 6;
float *ptr;
Adding 6 to ptr
moves it 6
float
array elements
ahead (24 bytes ahead)
16-bit Data Memory Words
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 302 1317 CPL
Example
Pointers
Pointer Arithmetic
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long *p = &x;
long *p = &x;
*
*
p
p
+=
+=
4
4
;
;
p
p
++;
++;
*
*
p
p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*
*
p
p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*
*
p
p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x[0]
x[0]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0000
0002
0000
0003
0000
0800
p
p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 303 1317 CPL
Example
Pointers
Pointer Arithmetic
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x[0]
x[0]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0005
0000
0002
0000
0003
0000
0800
p
p
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long
long
*
*
p
p
= &
= &
x
x
;
;
*p
*p
+=
+=
4
4
;
;
p
p
++;
++;
*
*
p
p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*
*
p
p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*
*
p
p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 304 1317 CPL
Example
Pointers
Pointer Arithmetic
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0005
0000
0002
0000
0003
0000
0804
p
p
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long
long
*
*
p
p
= &
= &
x
x
;
;
*
*
p
p
+=
+=
4
4
;
;
p
p
++;
++;
*
*
p
p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*
*
p
p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*
*
p
p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 305 1317 CPL
Example
Pointers
Pointer Arithmetic
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0005
0000
BEEF
DEAD
0003
0000
0804
p
p
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long
long
*
*
p
p
= &
= &
x
x
;
;
*
*
p
p
+=
+=
4
4
;
;
p
p
++;
++;
*p
*p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*
*
p
p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*
*
p
p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 306 1317 CPL
Example
Pointers
Pointer Arithmetic
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x
x
[
[
1
1
]
]
x[2]
x[2]
0x080C 0x080C
0000
0005
0000
BEEF
DEAD
0003
0000
0808
p
p
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long
long
*
*
p
p
= &
= &
x
x
;
;
*
*
p
p
+=
+=
4
4
;
;
p
p
++;
++;
*
*
p
p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*
*
p
p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*
*
p
p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 307 1317 CPL
Example
Pointers
Pointer Arithmetic
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x
x
[
[
1
1
]
]
x[2]
x[2]
0x080C 0x080C
0000
0005
0000
BEEF
DEAD
F00D
F1D0
0808
p
p
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long
long
*
*
p
p
= &
= &
x
x
;
;
*
*
p
p
+=
+=
4
4
;
;
p
p
++;
++;
*
*
p
p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*p
*p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*
*
p
p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 308 1317 CPL
Example
Pointers
Pointer Arithmetic
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x[0]
x[0]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0005
0000
BEEF
DEAD
F00D
F1D0
0800
p
p
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long
long
*
*
p
p
= &
= &
x
x
;
;
*
*
p
p
+=
+=
4
4
;
;
p
p
++;
++;
*
*
p
p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*
*
p
p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*
*
p
p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 309 1317 CPL
Example
Pointers
Pointer Arithmetic
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x[0]
x[0]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
00D1
BADF
BEEF
DEAD
F00D
F1D0
0800
p
p
{
{
long x
long x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
long
long
*
*
p
p
= &
= &
x
x
;
;
*
*
p
p
+=
+=
4
4
;
;
p
p
++;
++;
*
*
p
p
=
=
0xDEADBEEF
0xDEADBEEF
;
;
p
p
++;
++;
*
*
p
p
=
=
0xF1D0F00D
0xF1D0F00D
;
;
p
p
-
-
=
=
2
2
;
;
*p
*p
=
=
0xBADF00D1
0xBADF00D1
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 310 1317 CPL
Pointers
Post-Increment/Decrement Syntax Rule
Care must be taken with respect to operator
precedence when doing pointer arithmetic:
Syntax Operation Description by Example
Post
Post
-
-
Increment
Increment
data pointed to
data pointed to
by Pointer
by Pointer
(*p)++
(*p)++
Post
Post
-
-
Increment
Increment
Pointer
Pointer
*p++
*p++
*(p++)
*(p++)
z = (
z = (
*p
*p
)++;
)++;
is equivalent to: is equivalent to:
z = *p;
z = *p;
*p = *p + 1;
*p = *p + 1;
z = *(
z = *(
p
p
++);
++);
is equivalent to: is equivalent to:
z = *p;
z = *p;
p = p + 1;
p = p + 1;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 311 1317 CPL
Example
Pointers
Post-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x[0]
x[0]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0002
0003
0800
0000
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int *p = &x;
int *p = &x;
y
y
=
=
5
5
+ *(
+ *(
p
p
++);
++);
y
y
=
=
5
5
+ (*
+ (*
p
p
)++;
)++;
}
}
Remember:
*(p++)
is the same as
*p++
Remember:
*(p++)
is the same as
*p++
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 312 1317 CPL
Example
Pointers
Post-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x[0]
x[0]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0002
0003
0800
0006
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+
+
*
*
(
(
p
p
++);
++);
y
y
=
=
5
5
+ (*
+ (*
p
p
)++;
)++;
}
}
Remember:
*(p++)
is the same as
*p++
Remember:
*(p++)
is the same as
*p++
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 313 1317 CPL
Example
Pointers
Post-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0002
0003
0802
0006
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+ *(
+ *(
p++
p++
);
);
y
y
=
=
5
5
+ (*
+ (*
p
p
)++;
)++;
}
}
Remember:
*(p++)
is the same as
*p++
Remember:
*(p++)
is the same as
*p++
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 314 1317 CPL
Example
Pointers
Post-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0002
0003
0802
0007
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+ *(
+ *(
p
p
++);
++);
y
y
=
=
5
5
+ (
+ (
*p
*p
)++;
)++;
}
}
Remember:
*(p++)
is the same as
*p++
Remember:
*(p++)
is the same as
*p++
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 315 1317 CPL
Example
Pointers
Post-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0003
0003
0802
0007
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+ *(
+ *(
p
p
++);
++);
y
y
=
=
5
5
+ (
+ (
*p
*p
)
)
++
++
;
;
}
}
Remember:
*(p++)
is the same as
*p++
Remember:
*(p++)
is the same as
*p++
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 316 1317 CPL
Pointers
Pre-Increment/Decrement Syntax Rule
Care must be taken with respect to operator
precedence when doing pointer arithmetic:
Syntax Operation Description by Example
Pre
Pre
-
-
Increment
Increment
data pointed to
data pointed to
by Pointer
by Pointer
++(*p)
++(*p)
Pre
Pre
-
-
Increment
Increment
Pointer
Pointer
++*p
++*p
*(++p)
*(++p)
z = ++(
z = ++(
*p
*p
);
);
is equivalent to: is equivalent to:
*p = *p + 1;
*p = *p + 1;
z = *p;
z = *p;
z = *(++
z = *(++
p
p
);
);
is equivalent to: is equivalent to:
p = p + 1;
p = p + 1;
z = *p;
z = *p;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 317 1317 CPL
Example
Pointers
Pre-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x[0]
x[0]
x
x
[
[
1
1
]
]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0002
0003
0800
0000
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int *p = &x;
int *p = &x;
y
y
=
=
5
5
+ *(++
+ *(++
p
p
);
);
y
y
=
=
5
5
+ ++(*
+ ++(*
p
p
);
);
}
}
Remember:
*(++p)
is the same as
*++p
Remember:
*(++p)
is the same as
*++p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 318 1317 CPL
Example
Pointers
Pre-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0002
0003
0802
0000
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+ *(
+ *(
++p
++p
);
);
y
y
=
=
5
5
+ ++(*
+ ++(*
p
p
);
);
}
}
Remember:
*(++p)
is the same as
*++p
Remember:
*(++p)
is the same as
*++p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 319 1317 CPL
Example
Pointers
Pre-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0002
0003
0802
0007
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+
+
*
*
(++
(++
p
p
);
);
y
y
=
=
5
5
+ ++(*
+ ++(*
p
p
);
);
}
}
Remember:
*(++p)
is the same as
*++p
Remember:
*(++p)
is the same as
*++p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 320 1317 CPL
Example
Pointers
Pre-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0003
0003
0802
0007
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+ *(++
+ *(++
p
p
);
);
y
y
=
=
5
5
+
+
++
++
(
(
*p
*p
);
);
}
}
Remember:
*(++p)
is the same as
*++p
Remember:
*(++p)
is the same as
*++p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 321 1317 CPL
Example
Pointers
Pre-Increment/Decrement Syntax
Address Address
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
0x0800 0x0800
0x0802 0x0802
0x0804 0x0804
0x0806 0x0806
0x0808 0x0808
0x080A 0x080A
0x07FE 0x07FE
x
x
[
[
0
0
]
]
x[1]
x[1]
x
x
[
[
2
2
]
]
0x080C 0x080C
0000
0001
0003
0003
0802
0008
0000
0000
p
p
y
y
{
{
int
int
x
x
[
[
3
3
] = {
] = {
1
1
,
,
2
2
,
,
3
3
};
};
int
int
y
y
;
;
int
int
*p
*p
=
=
&x
&x
;
;
y
y
=
=
5
5
+ *(++
+ *(++
p
p
);
);
y
y
=
=
5
5
+ ++(
+ ++(
*p
*p
);
);
}
}
Remember:
*(++p)
is the same as
*++p
Remember:
*(++p)
is the same as
*++p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 322 1317 CPL
The parentheses determine what gets
incremented/decremented:
Pointers
Pre-
and Post-
Increment/Decrement Summary
Modify the pointer itself
*(++p)
or *++p
and *(p++)
or *p++
Modify the value pointed to by the pointer
++(*p)
and (*p)++
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 323 1317 CPL
Example
Pointers
Initialization Tip
If a pointer isn't initialized to a specific
address when it is created, it is a good
idea to initialize it as NUL (pointing to
nowhere)
This will prevent it from unintentionally
corrupting a memory location if it is
accidentally used before it is initialized
int
*p =
NULL;
NUL
is the character '\0'
but NULL
is the value of a
pointer that points to nowhere
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 324 1317 CPL
Lab Exercise 11
Lab Exercise 11
Pointers and Pointer Arithmetic
Pointers and Pointer Arithmetic
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 325 1317 CPL
Lab 11
Pointers and Pointer Arithmetic
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab11
Lab11
\
\
Lab11.mcw
Lab11.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 326 1317 CPL
Lab 11
Pointers and Pointer Arithmetic
/ *############################################################################
# STEP 1: I ni t i al i ze t he poi nt er p wi t h t he addr ess of t he var i abl e x
############################################################################*/
/ / Poi nt t o addr ess of x
p = &x;
/ *############################################################################
# STEP 2: Compl et e t he f ol l owi ng pr i nt f ( ) f unct i ons by addi ng i n t he
# appr opr i at e ar gument s as descr i bed i n t he cont r ol st r i ng.
############################################################################*/
printf("The
variable x is located at address 0x%X\n", &x);
printf("The
value of x is %d\n", x);
printf("The
pointer p is located at address 0x%X\n", &p);
printf("The
value of p is 0x%X\n", p);
printf("The
value pointed to by *p = %d\n", *p);
/ *############################################################################
# STEP 3: Wr i t e t he i nt val ue 10 t o t he l ocat i on p i s cur r ent l y poi nt i ng t o.
############################################################################*/
*p = 10;
Solution: Steps 1, 2 and 3
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 327 1317 CPL
Lab 11
Pointers and Pointer Arithmetic
/ *############################################################################
# STEP 4: I ncr ement t he val ue t hat p poi nt s t o.
############################################################################*/
/ / I ncr ement ar r ay el ement ' s val ue
(*p)++;
pr i nt f ( " y[ %d] = %d\ n" , i , *p) ;
/ *############################################################################
# STEP 5: I ncr ement t he poi nt er p so t hat i t poi nt s t o t he next i t em.
############################################################################*/
/ / I ncr ement poi nt er t o next ar r ay el ement
p++;
Solution: Steps 4 and 5
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 328 1317 CPL
Lab 11
Conclusions
Pointers are variables that hold the
address of other variables
Pointers make it possible for the program
to change which variable is acted on by a
particular line of code
Incrementing and decrementing pointers
will modify the value in multiples of the
size of the type they point to
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 329 1317 CPL
int
int
x
x
=
=
2
2
,
,
y
y
=
=
0
0
;
;
int
int
square
square
(
(
int
int
n
n
)
)
{
{
return
return
(
(
n
n
*
*
n
n
);
);
}
}
int
int
main
main
(
(
void
void
)
)
{
{
y
y
=
=
square
square
(
(
x
x
);
);
}
}
Pointers and Functions
Passing Pointers to Functions
Normally, functions operate on copies of
the data passed to them (pass by value)
After Function Call: After Function Call: y y
= 4 = 4
x x
= 2 = 2
x x
was was not not
changed by function changed by function
Value of variable passed to function Value of variable passed to function
is copied into local variable n is copied into local variable n
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 330 1317 CPL
int
int
x
x
=
=
2
2
,
,
y
y
=
=
0
0
;
;
void
void
square
square
(
(
int
int
*n
*n
)
)
{
{
*
*
n
n
*=
*=
*
*
n
n
;
;
}
}
int
int
main
main
(
(
void
void
)
)
{
{
square
square
(
(
&x
&x
);
);
}
}
Pointers and Functions
Passing Pointers to Functions
Pointers allow a function to operate on the
original variable (pass by reference)
After Function Call: After Function Call: x x
= 4 = 4
x x
was changed by function was changed by function
Address of variable passed to Address of variable passed to
function and stored in local function and stored in local
pointer variable n pointer variable n
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 331 1317 CPL
A function with a pointer parameter:
Must be called in one of two ways:
(assume: int x, *p
= &x;)
Example
Pointers and Functions
Passing Pointers to Functions
int
int
foo(int
foo(int
*q
*q
)
)
foo(
foo(
&x
&x
)
)
Pass an address to the function so the address Pass an address to the function so the address
may be assigned to the pointer parameter: may be assigned to the pointer parameter:
q
q
=
=
&x
&x
foo(
foo(
p
p
)
)
Pass a pointer to the function so the address Pass a pointer to the function so the address
may be assigned to the pointer parameter: may be assigned to the pointer parameter:
q
q
=
=
p
p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 332 1317 CPL
Example
Part 1
Pointers and Functions
Passing Parameters By Reference
void
void
swap
swap
(
(
int
int
*
*
n1
n1
,
,
int
int
*
*
n2
n2
)
)
{
{
int
int
temp
temp
;
;
temp
temp
= *
= *
n1
n1
;
;
*
*
n1
n1
= *
= *
n2
n2
;
;
*
*
n2
n2
=
=
temp
temp
;
;
}
}
Swap function definition:
Swap function definition:
Addresses of parameters
Addresses of parameters
copied to local pointer
copied to local pointer
variables: Function can
variables: Function can
now modify the original
now modify the original
variables via pointers.
variables via pointers.
We know where
you live!
We know where
you live!
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 333 1317 CPL
Example
Part 2
Pointers and Functions
Passing Parameters By Reference
int
int
main
main
(
(
void
void
)
)
{
{
int
int
x
x
=
=
5
5
,
,
y
y
=
=
10
10
;
;
int
int
*
*
p
p
= &
= &
y
y
;
;
swap
swap
(
(
&x
&x
,
,
p
p
);
);
while
while
(
(
1
1
);
);
}
}
Main function definition:
Main function definition:
Swap function prototype: Swap function prototype:
void void
swap swap( (int int
*n1 *n1, ,
int int
*n2 *n2) )
After running program: After running program:
x x
= 10 = 10
y y
= 5 = 5
Tell function where
x
and y
live
n1 = &x
n2 = p
Tell function where
x
and y
live
n1 = &x
n2 = p
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 334 1317 CPL
49
49
50
50
00
00
43
43
91C0
91C0
I
I
I
\0
\
\
0
0
Pointers and Strings
So far, we have worked with strings
strictly as arrays of char
Strings may be created and used with
pointers much more elegantly
char
char
*
*
str
str
=
=
"PIC"
"PIC"
;
;
String declaration with a pointer: String declaration with a pointer:
Address Address
16 16- -bit Data Memory (RAM) bit Data Memory (RAM)
0x91C0 0x91C0
0x08C2 0x08C2
0x91C2 0x91C2
str
str
P
P
P
C
C
C
Implementation Implementation
varies depending on varies depending on
compiler and compiler and
architecture used. architecture used.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 335 1317 CPL
When initialized, a pointer to a string
points to the first character:
Increment or add an offset to the pointer to
access subsequent characters
Pointers and Strings
M M
M
i i
i
c c
c
r r
r
o o
o
c c
c
h h
h
i i
i
p p
p
\0 \
\
0
0
char
char
*
*
str
str
=
=
"Microchip"
"Microchip"
;
;
str
str
str
str
+=
+=
4
4
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 336 1317 CPL
Pointers may also be used to access
characters via an offset:
Pointer always points to "base address"
Offsets used to access subsequent chars
Pointers and Strings
M M
M
i i
i
c c
c
r r
r
o o
o
c c
c
h h
h
i i
i
p p
p
\0 \
\
0
0
char
char
*
*
str
str
=
=
"Microchip"
"Microchip"
;
;
*
*
str
str
==
==
'M'
'M'
*(
*(
str
str
+
+
4
4
) ==
) ==
'o'
'o'
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 337 1317 CPL
Example: Pointer Variable Example: Array Variable
char
char
str
str
[] =
[] =
"PIC"
"PIC"
;
;
char
char
str
str
[
[
4
4
] =
] =
"PIC"
"PIC"
;
;
Pointers and Strings
Pointer versus Array: Initialization at Declaration
Initializing a character string when it is
declared is essentially the same for both a
pointer and an array:
or
or
The NULL character '\0' is automatically appended to
strings in both cases (array must be large enough).
char
char
*
*
str
str
=
=
"PIC"
"PIC"
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 338 1317 CPL
Example: Pointer Variable Example: Array Variable
Pointers and Strings
Pointer versus Array: Assignment in Code
An entire string may be assigned to a pointer
A character array must be assigned character by
character
Must explicitly add NULL character '\0' to array.
char
char
*
*
str
str
;
;
str
str
=
=
"PIC"
"PIC"
;
;
char
char
str
str
[
[
4
4
];
];
str
str
[
[
0
0
] =
] =
'P'
'P'
;
;
str
str
[
[
1
1
] =
] =
'I'
'I'
;
;
str
str
[
[
2
2
] =
] =
'C'
'C'
;
;
str
str
[
[
3
3
] =
] =
'
'
\
\
0'
0'
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 339 1317 CPL
Pointers and Strings
Comparing Strings
If you want to test a string for equivalence,
the natural thing to do is:
if (str
== "Microchip")
This is not
correct, though it might appear
to work sometimes
This compares the address in str
to the
address of the string literal "Microchip"
The correct way is to use the strcmp()
function in the standard library which
compares strings character by character
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 340 1317 CPL
strcmp() prototype:
strcmp() return values:
<0 if s1 is less than s2
0 if s1 is equal to s2
>0 if s1 is greater than s2
Pointers and Strings
Comparing Strings
Function Prototype
int
int
strcmp
strcmp
(
(
const
const
char
char
*
*
s1
s1
,
,
const char
const char
*
*
s2
s2
);
);
The The st r cmp st r cmp( ) ( ) prototype is in prototype is in
C: C: \ \ Pr ogr amFi l es Pr ogr amFi l es\ \ Mi cr ochi p Mi cr ochi p\ \ MPLAB C30 MPLAB C30\ \ i ncl ude i ncl ude\ \ st r i ng. h st r i ng. h
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 341 1317 CPL
Example
Pointers and Strings
Comparing Strings
#include
#include
<
<
string.h
string.h
>
>
char
char
*
*
str
str
=
=
"Microchip"
"Microchip"
;
;
int
int
main
main
(
(
void
void
)
)
{
{
if
if
(
(
0
0
==
==
strcmp(str
strcmp(str
, "Microchip")
, "Microchip")
)
)
printf
printf
(
(
"They
"They
match!
match!
\
\
n"
n"
);
);
while
while
(
(
1
1
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 342 1317 CPL
An array of pointers is an ordinary array
variable whose elements happen to all be
pointers.
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
Arrays of Pointers
Declaration
char
char
*
*
p
p
[
[
4
4
];
];
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 343 1317 CPL
0000
0000
91C0
91C0
91C3
91C3
91C7
91C7
91CC
91CC
0000
0000
0000
0000
0000
0000
Arrays of Pointers
Array Elements are Pointers Themselves
16 16- -bit Data Memory bit Data Memory
(RAM) (RAM)
p
p
[
[
0
0
]
]
p
p
[
[
1
1
]
]
p
p
[
[
2
2
]
]
p
p
[
[
3
3
]
]
O
O
O
n
n
n
O
O
O
f
f
f
f
f
f
\0
\
\
0
0
M
M
M
a
a
a
i
i
i
n
n
n
\0
\
\
0
0
A
A
A
u
u
u
x
x
x
\0
\
\
0
0
91C0 91C0
91C3 91C3
91C7 91C7
91CC 91CC
\0
\
\
0
0
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 344 1317 CPL
A pointer array element may be initialized
just like its ordinary variable counterpart:
Or, when working with strings:
Arrays of Pointers
Initialization
p
p
[
[
0
0
] = &
] = &
x
x
;
;
p
p
[
[
0
0
] =
] =
"My string"
"My string"
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 345 1317 CPL
Arrays of Pointers
Dereferencing
To use the value pointed to by a pointer
array element, just dereference it like you
would an ordinary variable:
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
y
y
=
=
*p[0]
*p[0]
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 346 1317 CPL
Example
Arrays of Pointers
Accessing Strings
int
int
i
i
=
=
0
0
;
;
char
char
*
*
str
str
[] = {
[] = {
"Zero"
"Zero"
,
,
"One"
"One"
,
,
"Two"
"Two"
,
,
"Three"
"Three"
,
,
"Four"
"Four"
,
,
"
"
\
\
0"
0"
};
};
int
int
main
main
(
(
void
void
)
)
{
{
while
while
(*
(*
str
str
[
[
i
i
] !=
] !=
'
'
\
\
0'
0'
)
)
printf
printf
(
(
"%s
"%s
\
\
n
n
"
"
,
,
str
str
[
[
i
i
++]);
++]);
while
while
(
(
1
1
);
);
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 347 1317 CPL
Lab Exercise 12
Lab Exercise 12
Pointers, Arrays, and Functions
Pointers, Arrays, and Functions
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 348 1317 CPL
Lab 12
Pointers, Arrays, and Functions
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab12
Lab12
\
\
Lab12.mcw
Lab12.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 349 1317 CPL
Lab 12
Pointers, Arrays, and Functions
/ *############################################################################
# STEP1: Pass t he var i abl e x t o t he f unct i on t wosCompl ement such t hat t he
# val ue of x i t sel f may be changed by t he f unct i on. Not e: The f unct i on
# expect s a poi nt er ( addr ess) as i t s par amet er .
############################################################################*/
/ / Per f or mt wos compl ement on x
twosComplement(&x);
/ *############################################################################
# STEP 2: Pass t he ar r ay ' a' t o t he f unct i on r ever se1( ) . Use t he const ant
# ARRAY_SI ZE f or t he second par amet er .
# See def i ni t i on of f unct i on r ever se1( ) bel ow.
############################################################################*/
/ / Rever se or der of el ement s by passi ng ar r ay
reverse1(a, ARRAY_SIZE);
Solution: Steps 1 and 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 350 1317 CPL
Lab 12
Pointers, Arrays, and Functions
/ *############################################################################
# STEP 3: Pass a poi nt er t o ar r ay ' a' t o t he f unct i on r ever se2( ) . Use t he
# const ant ARRAY_SI ZE f or t he second par amet er .
# See def i ni t i on of f unct i on r ever se2( ) bel ow.
# Hi nt : You do not need t o def i ne a new poi nt er var i abl e t o do t hi s.
############################################################################*/
/ / Rever se or der of el ement s by passi ng poi nt er
reverse2(a, ARRAY_SIZE);
/ *############################################################################
# STEP 4: Compl et e t he f unct i on header by def i ni ng a par amet er cal l ed ' number '
# t hat poi nt s t o an i nt eger ( i . e. accept s t he addr ess of an i nt eger
# var i abl e) .
############################################################################*/
/ / voi d t wosCompl ement ( / *### Your Code Her e ###*/ )
void twosComplement(int
*number)
{
*number = ~( *number ) ; / / Bi t wi se compl ement val ue
*number += 1; / / Add 1 t o r esul t
}
Solution: Steps 3 and 4
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 351 1317 CPL
Lab 12
Conclusions
Pointers make it possible to pass a
variable by reference to a function (allows
function to modify original variable
not a
copy of its contents)
Arrays are frequently treated like pointers
An array name alone represents the
address of the first element of the array
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 352 1317 CPL
Function Pointers
Function Pointers
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 353 1317 CPL
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 to call
Makes it possible to pass functions to
other functions
Not extremely common, but very useful in
the right situations
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 354 1317 CPL
A function pointer is declared much like a
function prototype:
Here, we have declared a function pointer
with the name fp
The function it points to must take one int
parameter
The function it points to must return an int
Function Pointers
Declaration
int
int
(
(
*
*
fp
fp
)
)
(
(
int
int
x
x
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 355 1317 CPL
A function pointer is initialized by setting
the pointer name equal to the function
name
Function Pointers
Initialization
If we declare the following:
We can initialize the function pointer like this:
fp
fp
=
=
foo
foo
;
;
//
//
fp
fp
now points to
now points to
foo
foo
int
int
(*
(*
fp
fp
)(
)(
int
int
x
x
);
);
//Function pointer
//Function pointer
int
int
foo
foo
(
(
int
int
x
x
);
);
//Function prototype
//Function prototype
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 356 1317 CPL
Function Pointers
Calling a Function via a Function Pointer
The function pointed to by fp
from the
previous slide may be called like this:
This is the same as calling the function
directly:
y
y
=
=
foo
foo
(
(
x
x
);
);
y
y
=
=
fp
fp
(
(
x
x
);
);
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 357 1317 CPL
Function Pointers
Passing a Function to a Function
Example 1: Understanding the Mechanism
int int
x x; ;
int int
foo( foo(int int
a a, ,
int int
b b); );
//Function prototype //Function prototype
int int
bar( bar(int int
a a, ,
int int
b b); );
//Function prototype //Function prototype
//Function definition with function pointer parameter //Function definition with function pointer parameter
int int
foobar foobar( (int int
a a, ,
int int
b b, ,
int int
(* (*fp fp)( )(int int, ,
int int)) ))
{ {
return return fp fp( (a a, ,
b b); ); //Call function passed by pointer //Call function passed by pointer
} }
void void
main main( (void void) )
{ {
x x = =
foobar foobar( (5 5, , 12 12, & , &foo foo); ); //Pass address of //Pass address of foo foo
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 358 1317 CPL
Function Pointers
Passing a Function to a Function
Example 2: Evaluate a Definite Integral (approximation)
float float
integral integral( (float float
a a, ,
float float
b b, ,
float float
(* (*f f)( )(float float)) ))
{ {
float float
sum sum = =
0.0 0.0; ;
float float
x x; ;
int int
n n; ;
//Evaluate //Evaluate integral{a,b integral{a,b} } f(x f(x) ) dx dx
for for
( (n n = =
0 0; ;
n n <= <=
100 100; n++ ; n++) )
{ {
x x = (( = ((n n / /
100.0 100.0) * ( ) * (b b
a a)) + )) +
a a; ;
sum sum += ( += (f f( (x x) * ( ) * (b b
a a)) / )) /
101.0 101.0; ;
} }
return return
sum sum; ;
} }
a a
b b
y =
y =
f(x
f(x
)
)
dx
dx
Adapted from example at: http:// Adapted from example at: http://en.wikipedia.org/wiki/Function_pointer en.wikipedia.org/wiki/Function_pointer
bounds of integral function to be evaluated
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 359 1317 CPL
Lab Exercise 13
Lab Exercise 13
Function Pointers
Function Pointers
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 360 1317 CPL
Lab 13
Function Pointers
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab13
Lab13
\
\
Lab13.mcw
Lab13.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 361 1317 CPL
Lab 13
Function Pointers
Compile and run the code:
2
2
Click on the
Click on the
Build All
Build All
button.
button.
Compile (Build All) Compile (Build All) Run Run 2
2
3
3
3
3 If no errors are reported,
If no errors are reported,
click on the
click on the
Run
Run
button.
button.
Halt Halt 4
4
4
4
Click on the
Click on the
Halt
Halt
button.
button.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 362 1317 CPL
Lab 13
Function Pointers
Results
Three separate functions are integrated over the interval 0 to 1 Three separate functions are integrated over the interval 0 to 1: :
y y
1 1
= =
x x dx dx
= =
x x
2 2
+ C [0,1] + C [0,1] = 0.500000 = 0.500000
y y
2 2
= =
x x
2 2
dx dx
= =
x x
3 3
+ C [0,1] + C [0,1]
= 0.335000 = 0.335000
y y
3 3
= =
x x
3 3
dx dx
= =
x x
4 4
+ C [0,1] + C [0,1]
= 0.252500 = 0.252500
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 363 1317 CPL
Lab 13
Function Pointers
/ *============================================================================
FUNCTI ON: xsquar ed( )
DESCRI PTI ON: I mpl ement s f unct i on y = x^2
PARAMETERS: f l oat x
RETURNS: f l oat ( x * x)
REQUI REMENTS: none
============================================================================*/
float xsquared(float
x)
{
return (x * x);
}
/ *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eval uat e y2 = I nt x^2 dx over t he i nt er val 0 t o 1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
y2 = integral(0, 1, xsquared);
Function to Evaluate: xsquared()
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 364 1317 CPL
Lab 13
Function Pointers
/ *============================================================================
FUNCTI ON: i nt egr al ( )
DESCRI PTI ON: Eval uat es t he i nt egr al of t he f unct i on passed t o i t over t he
i nt er val a t o b.
PARAMETERS: i nt er val end poi nt s a & b and f unct i on t o i nt egr at e
RETURNS: i nt egr al of f unct i on f over i nt er val a t o b
REQUI REMENTS: none
SOURCE: Adapt ed f r omexampl e at :
ht t p: / / en. wi ki pedi a. or g/ wi ki / Funct i on_poi nt er
============================================================================*/
float integral(float
a, float b, float (*f)(float))
{
float sum = 0.0;
float x;
int n;
/ / Eval uat e i nt egr al {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;
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 365 1317 CPL
Lab 13
Conclusions
Function pointers, while not frequently
used, can provide a very convenient
mechanism for passing a function to
another function
Many other possible applications exist
Jump tables
Accommodating multiple calling conventions
Callback functions (used in Windows)
Call different versions of a function under
different circumstances
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 366 1317 CPL
Structures
Structures
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 367 1317 CPL
Definition
Structures
Structures:
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
Structures
Structures
are collections of variables grouped together
are collections of variables grouped together
under a common name. The variables within a structure are
under a common name. The variables within a structure are
referred to as the structure
referred to as the structure
s
s
members
members
, and may be
, and may be
accessed individually as needed.
accessed individually as needed.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 368 1317 CPL
Example
Syntax
Structures
How to Create a Structure Definition
// Structure to handle complex numbers // Structure to handle complex numbers
struct struct
complex complex
{ {
float float
re re; ;
// Real part // Real part
float float
im im; ;
// Imaginary part // Imaginary part
} }
struct
struct
structName
structName
{
{
type
type
1 1
memberName
memberName
1 1
;
;
...
...
type
type
n n
memberName
memberName
n n
;
;
}
}
Members are declared just Members are declared just
like ordinary variables like ordinary variables
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 369 1317 CPL
Example
Syntax
struct
struct
structName
structName
{
{
type
type
1 1
memberName
memberName
1 1
;
;
...
...
type
type
n n
memberName
memberName
n n
;
;
}
}
varName
varName
1 1
,
,
...
...
,
,
varName
varName
n n
;
;
Structures
How to Declare a Structure Variable (Method 1)
// Structure to handle complex numbers // Structure to handle complex numbers
struct struct
complex complex
{ {
float float
re re; ;
float float
im im; ;
} } x, y x, y; ; // Declare x and y of type complex // Declare x and y of type complex
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 370 1317 CPL
Example
Syntax
struct
struct
structName
structName
varName
varName
1 1
,
,
,
,
varName
varName
n n
;
;
Structures
How to Declare a Structure Variable (Method 2)
struct struct
complex complex
{ {
float float
re re; ;
float float
im im; ;
} }
... ...
struct struct
complex complex
x x, ,
y y; ; // Declare x and y of type complex // Declare x and y of type complex
If
If
structName
structName
has already been defined:
has already been defined:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 371 1317 CPL
Example
Syntax
Structures
How to Use a Structure Variable
structVariableName.memberName
structVariableName.memberName
struct struct
complex complex
{ {
float float
re re; ;
float float
im im; ;
} } x, y x, y; ; // Declare x and y of type complex // Declare x and y of type complex
int int
main main( (void void) )
{ {
x.re x.re
= =
1.25 1.25; ; // Initialize real part of x // Initialize real part of x
x.im x.im
= =
2.50 2.50; ; // Initialize imaginary part of x // Initialize imaginary part of x
y y = =
x x; ; // Set struct y equal to struct x // Set struct y equal to struct x
... ...
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 372 1317 CPL
Example
Syntax
Structures
How to Create a Structure Type with typedef
// Structure type to handle complex numbers // Structure type to handle complex numbers
typedef struct typedef struct
{ {
float float
re re; ;
// Real part // Real part
float float
im im; ;
// Imaginary part // Imaginary part
} } complex complex; ;
typedef struct
typedef struct
structTag
structTag
optional optional
{
{
type
type
1 1
memberName
memberName
1 1
;
;
...
...
type
type
n n
memberName
memberName
n n
;
;
}
}
typeName
typeName
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 373 1317 CPL
Example
Syntax
typeName
typeName
varName
varName
1 1
,
,
,
,
varName
varName
n n
;
;
Structures
How to Declare a Structure Type Variable
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} } complex complex; ;
... ...
complex complex
x x, ,
y y; ; // Declare x and y of type complex // Declare x and y of type complex
If
If
typeName
typeName
has already been defined:
has already been defined:
The keyword The keyword
struct struct
is no longer required! is no longer required!
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 374 1317 CPL
Example
Syntax
Structures
How to Initialize a Structure Variable at Declaration
typeName
typeName
varName
varName
= {
= {
const
const
1 1
,
,
,
,
const
const
n n
};
};
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} } complex complex; ;
... ...
complex complex
x x = { = {1.25 1.25, , 2.50 2.50}; }; // // x.re x.re
= 1.25, = 1.25, x.im x.im
= 2.50 = 2.50
If
If
typeName
typeName
or
or
structName
structName
has already been defined:
has already been defined:
struct
struct
structName
structName
varName
varName
= {
= {
const
const
1 1
,
,
,
,
const
const
n n
};
};
-
-
or
or
-
-
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 375 1317 CPL
Example
Structures
Nesting Structures
typedef struct typedef struct
{ {
float float
x x; ;
float float
y y; ;
} }
point point; ;
typedef struct typedef struct
{ {
point point
a a; ;
point point
b b; ;
} }
line line; ;
int int main main( (void void) )
{ {
line m line m; ;
m.a.x m.a.x
= =
1.2 1.2; ;
m.a.y m.a.y
= = 7.6 7.6; ;
m.b.x m.b.x
= = 38.5 38.5; ;
m.b.y m.b.y
= = 17.8 17.8; ;
... ...
a
b
(x
a
, y
a
) = (1.2, 7.6)
(x
b
, y
b
) = (38.5, 17.8)
x
y
m
line
point
point
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 376 1317 CPL
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 Example: Initializing Members
Structures
Arrays and Pointers with Strings
struct struct
strings strings
{ {
char char
a[4] a[4]; ;
char char
*b *b; ;
} } str str; ;
int int
main( main(void void) )
{ {
str.a str.a[ [0 0] = ] =
B B ; ;
str.a str.a[ [1 1] = ] =
a a ; ;
str.a str.a[ [2 2] = ] =
d d ; ;
str.a str.a[ [3 3] = ] =
\ \0 0 ; ;
str.b str.b
= =
Good Good ; ;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 377 1317 CPL
Syntax
Example 1 Example 2
Structures
How to Declare a Pointer to a Structure
typeName
typeName
*
*
ptrName
ptrName
;
;
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} } complex complex; ;
... ...
complex complex
*p *p; ;
If typeName or structName has already been defined:
struct
struct
structName
structName
*
*
ptrName
ptrName
;
;
-
-
or
or
-
-
struct struct
complex complex
{ {
float float
re re; ;
float float
im im; ;
} }
... ...
struct struct complex complex
*p *p; ;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 378 1317 CPL
Example: Definitions Example: Usage
Syntax
Structures
How to Use a Pointer to Access Structure Members
ptrName
ptrName
-
-
>
>
memberName
memberName
If ptrName has already been defined:
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} } complex complex; ; //complex type //complex type
... ...
complex x complex x; ; //complex //complex var var
complex complex
*p *p; ; //ptr to complex //ptr to complex
int int main main( (void void) )
{ {
p = &x p = &x; ;
//Set //Set x.re x.re
= 1.25 via p = 1.25 via p
p p- ->re >re
= = 1.25 1.25; ;
//Set //Set x.im x.im
= 2.50 via p = 2.50 via p
p p- -> >im im
= = 2.50 2.50; ;
} }
Pointer must first be initialized to point to the address of the Pointer must first be initialized to point to the address of the
structure itself: structure itself: ptrName ptrName = =
& &structVariable structVariable; ;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 379 1317 CPL
Example
Syntax
Structures
Creating Arrays of Structures
typeName
typeName
arrName
arrName
[
[
n
n
];
];
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} } complex complex; ;
... ...
complex complex
a a[ [3 3]; ];
If typeName or structName has already been defined:
struct
struct
structName
structName
arrName
arrName
[
[
n
n
];
];
-
-
or
or
-
-
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 380 1317 CPL
Example
Syntax
Structures
Initializing Arrays of Structures at Declaration
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} } complex complex; ;
... ...
complex complex
a a[ [3 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}}; }};
typeName
typeName
arrName
arrName
[
[
n
n
]
]
= {{
= {{
list
list
1 1
},
},
,{
,{
list
list
n n
}};
}};
If typeName or structName has already been defined:
struct
struct
structName
structName
arrName
arrName
[
[
n
n
]
]
= {{
= {{
list
list
1 1
},
},
,{
,{
list
list
n n
}};
}};
-
-
or
or
-
-
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 381 1317 CPL
Example: Definitions Example: Usage
Syntax
Structures
Using Arrays of Structures
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} } complex complex; ;
... ...
complex a complex a[ [3 3]; ];
int int main main( (void void) )
{ {
a a[ [0 0] ].re .re
= = 1.25 1.25; ;
a a[ [0 0] ].im .im
= = 2.50 2.50; ;
... ...
} }
arrName
arrName
[
[
n
n
]
]
.
.
memberName
memberName
If arrName has already been defined:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 382 1317 CPL
Example
Structures
How to Pass Structures to Functions
typedef struct typedef struct
{ {
float float
re re; ;
float float
im im; ;
} }
complex complex; ;
void void
display display( (complex complex
x x) )
{ {
printf printf( ( (%f (%f
+ + j%f) j%f)\ \n n , ,
x.re x.re, ,
x.im x.im); );
} }
int int
main main( (void void) )
{ {
complex a complex a = =
{ {1.2 1.2, ,
2.5 2.5}; };
complex b complex b = =
{ {3.7 3.7, ,
4.0 4.0}; };
display display( (a a); );
display display( (b b); );
} }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 383 1317 CPL
Lab Exercise 14
Lab Exercise 14
Structures
Structures
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 384 1317 CPL
Lab 14
Structures
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab14
Lab14
\
\
Lab14.mcw
Lab14.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 385 1317 CPL
Lab 14
Structures
/ *############################################################################
# STEP 1: Cal cul at e t he di f f er ence bet ween maxi mumand mi ni mumpower i n
# ci r cui t 1 usi ng t he i ndi vi dual power st r uct ur es ( i . e. var i abl es
# PMax1 & PMi n1) . Al gebr ai c Not at i on:
# Pdi f f = ( Vmax * I max) - ( Vmi n * I mi n)
############################################################################*/
powerDiff1 = (PMax1.v * PMax1.i) -
(PMin1.v * PMin1.i);
power Di f f 2 = ( PMax2. v * PMax2. i ) - ( PMi n2. v * PMi n2. i ) ;
power Di f f 3 = ( PMax3. v * PMax3. i ) - ( PMi n3. v * PMi n3. i ) ;
/ *############################################################################
# STEP 2: Cal cul at e t he di f f er ence bet ween maxi mumand mi ni mumpower i n
# ci r cui t 1 usi ng t he st r uct ur e of st r uct ur es ( i . e. var i abl e PRange1) .
# Al gebr ai c Not at i on: Pdi f f = ( Vmax * I max) - ( Vmi n * I mi n)
############################################################################*/
powerDiff1 = (PRange1.max.v * PRange1.max.i) -
(PRange1.min.v * PRange1.min.i);
power Di f f 2 = ( PRange2. max. v * PRange2. max. i ) - ( PRange2. mi n. v * PRange2. mi n. i ) ;
power Di f f 3 = ( PRange3. max. v * PRange3. max. i ) - ( PRange3. mi n. v * PRange3. mi n. i ) ;
Solution: Steps 1 and 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 386 1317 CPL
Lab 14
Conclusions
Structures make it possible to associate
related variables of possibly differing
types under the same name
Structure members (using the dot
notation) may be used anywhere an
ordinary variable would be used
Pointers to structures make it possible to
copy one entire structure to another very
easily
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 387 1317 CPL
Lab Exercise 15
Lab Exercise 15
Arrays of Structures
Arrays of Structures
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 388 1317 CPL
Lab 15
Arrays of Structures
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Labs
Labs
\
\
Lab15
Lab15
\
\
Lab15.mcw
Lab15.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 389 1317 CPL
Lab 15
Arrays of Structures
/ *############################################################################
# STEP 1: Mul t i pl y t he r eal ( r e) par t of each ar r ay el ement by 10
# HI NT: Use *=
############################################################################*/
/ / Mul t i pl y r e par t of cur r ent ar r ay el ement by 10
x[i].re
*= 10;
/ *############################################################################
# STEP 2: Mul t i pl y t he i magi nar y ( i m) par t of each ar r ay el ement by 5
# HI NT: Use *=
############################################################################*/
/ / Mul t i pl y i mpar t of cur r ent ar r ay el ement by 5
x[i].im
*= 5;
Solution: Steps 1 and 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 390 1317 CPL
Lab 15
Conclusions
Arrays of structures allow groups of
related structures to be referenced by a
common name
Individual structures may be referenced by
the array index
Individual structure members may be
referenced by the dot notation, in
conjunction with the array name and index
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 391 1317 CPL
Unions
Unions
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 392 1317 CPL
Definition
Unions
Unions:
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
Unions
Unions
are similar to structures but a union
are similar to structures but a union
s members all
s members all
share the same memory location. In essence a union is a
share the same memory location. In essence a union is a
variable that is capable of holding different types of data at
variable that is capable of holding different types of data at
different times.
different times.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 393 1317 CPL
Syntax
Example
Unions
How to Create a Union
// Union of char, int and float // Union of char, int and float
union union
mixedBag mixedBag
{ {
char char
a a; ;
int int
b b; ;
float float
c c; ;
} }
union
union
unionName
unionName
{
{
type
type
1 1
memberName
memberName
1 1
;
;
...
...
type
type
n n
memberName
memberName
n n
;
;
}
}
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 394 1317 CPL
Syntax
Example
Unions
How to Create a Union Type with typedef
// Union of char, int and float // Union of char, int and float
typedef union typedef union
{ {
char char
a a; ;
int int
b b; ;
float float
c c; ;
} } mixedBag mixedBag; ;
typedef union
typedef union
unionTag
unionTag
optional optional
{
{
type
type
1 1
memberName
memberName
1 1
;
;
...
...
type
type
n n
memberName
memberName
n n
;
;
}
}
typeName
typeName
;
;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 395 1317 CPL
Example
typedef union typedef union
{ {
char char
a a; ;
int int
b b; ;
float float
c c; ;
} } mixedBag mixedBag; ;
mixedBag mixedBag
x x; ;
Unions
How Unions Are Stored In Memory
Union variables may be declared exactly
like structure variables
Memory is only allocated to accommodate
the unions largest member
x
16-bit Data Memory (RAM)
Space allocated
for x
is size of
float
0x800
0x802
0x7FF
0x804
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 396 1317 CPL
Example
typedef union typedef union
{ {
char char
a a; ;
int int
b b; ;
float float
c c; ;
} } mixedBag mixedBag; ;
mixedBag mixedBag
x x; ;
Unions
How Unions Are Stored In Memory
Union variables may be declared exactly
like structure variables
Memory is only allocated to accommodate
the unions largest member
x
16-bit Data Memory (RAM)
x.a
only
occupies the
lowest byte of
the union
0x800
0x802
0x7FF
0x804
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 397 1317 CPL
Example
typedef union typedef union
{ {
char char
a a; ;
int int
b b; ;
float float
c c; ;
} } mixedBag mixedBag; ;
mixedBag mixedBag
x x; ;
Unions
How Unions Are Stored In Memory
Union variables may be declared exactly
like structure variables
Memory is only allocated to accommodate
the unions largest member
x
16-bit Data Memory (RAM)
x.b
only
occupies the
lowest two
bytes of the
union
0x800
0x802
0x7FF
0x804
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 398 1317 CPL
Example
typedef union typedef union
{ {
char char
a a; ;
int int
b b; ;
float float
c c; ;
} } mixedBag mixedBag; ;
mixedBag mixedBag
x x; ;
Unions
How Unions Are Stored In Memory
Union variables may be declared exactly
like structure variables
Memory is only allocated to accommodate
the unions largest member
x
16-bit Data Memory (RAM)
x.c
occupies
all four bytes of
the union
0x800
0x802
0x7FF
0x804
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 399 1317 CPL
Lab Exercise 16
Lab Exercise 16
Unions
Unions
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 400 1317 CPL
Lab 16
Unions
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab16
Lab16
\
\
Lab16.mcw
Lab16.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 401 1317 CPL
Lab 16
Unions
/ *############################################################################
# STEP 1: Set t he i nt member of uni onVar equal t o 16877.
############################################################################*/
/ / Set i nt Var = 16877
unionVar.intVar
= 16877;
/ *############################################################################
# STEP 2: Set t he f l oat member of uni onVar equal t o 6. 02e23.
############################################################################*/
/ / Set f l oat Var = 6. 02e23
unionVar.floatVar
= 6.02e23;
Solution: Steps 1 and 2
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 402 1317 CPL
Lab 16
Conclusions
Unions make it possible to store multiple
variables at the same location
They make it possible to access those
variables in different ways
They make it possible to store different
variable types in the same memory
location(s)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 403 1317 CPL
Bit Fields
Bit Fields
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 404 1317 CPL
Definition
Bit Fields
Bit Fields:
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
Bit Fields
Bit Fields
are
are
unsigned int
unsigned int
members of structures that
members of structures that
occupy a specified number of adjacent bits from one to
occupy a specified number of adjacent bits from one to
sizeof(int)
sizeof(int)
.
.
They may be used as an ordinary
They may be used as an ordinary
int
int
variable in arithmetic and logical operations.
variable in arithmetic and logical operations.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 405 1317 CPL
Syntax
Example
Bit Fields
How to Create a Bit Field
typedef struct typedef struct
{ {
unsigned int unsigned int
bit0: 1 bit0: 1; ;
unsigned int unsigned int
bit1to3: 3 bit1to3: 3; ;
unsigned int unsigned int
bit4: 1 bit4: 1; ;
unsigned int unsigned int
bit5: 1 bit5: 1; ;
unsigned int unsigned int
bit6to7: 2 bit6to7: 2; ;
} } byteBits byteBits; ;
struct
struct
structName
structName
{
{
unsigned int
unsigned int
memberName
memberName
1 1
:
:
bitWidth
bitWidth
;
;
...
...
unsigned int
unsigned int
memberName
memberName
n n
:
:
bitWidth
bitWidth
;
;
}
}
bitfield bitfield
struct struct
may be declared may be declared
normally or as a normally or as a
typedef typedef
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 406 1317 CPL
Example
Bit Fields
How to Use a Bit Field
struct struct byteBits byteBits
{ {
unsigned unsigned
a: 1 a: 1; ;
unsigned unsigned
b: 1 b: 1; ;
unsigned unsigned
c: 2 c: 2; ;
unsigned unsigned
d: 1 d: 1; ;
unsigned unsigned
e: 3 e: 3; ;
} } x x; ;
int int
main main( (void void) )
{ {
x.a x.a
= = 1 1; ; // //x.a x.a
may contain values from 0 to 1 may contain values from 0 to 1
x.b x.b
= = 0 0; ; // //x.b x.b
may contain values from 0 to 1 may contain values from 0 to 1
x.c x.c
= = 0b10 0b10; ; // //x.c x.c
may contain values from 0 to 3 may contain values from 0 to 3
x.d x.d
= = 0x0 0x0; ; // //x.d x.d
may contain values from 0 to 1 may contain values from 0 to 1
x.e x.e
= = 7 7; ; // //x.e x.e
may contain values from 0 to 7 may contain values from 0 to 7
} }
1
1
1
1
1
1
0
0
1
1
0
0
0
0
1
1
x
x
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7
Byte in Data Memory (RAM) Byte in Data Memory (RAM)
a
a
b
b
c
c
d
d
e
e
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 407 1317 CPL
Lab Exercise 17
Lab Exercise 17
Bit Fields
Bit Fields
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 408 1317 CPL
Lab 17
Bit Fields
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab17
Lab17
\
\
Lab17.mcw
Lab17.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 409 1317 CPL
Lab 17
Bit Fields
Compile and run the code:
2
2
Click on the
Click on the
Build All
Build All
button.
button.
Compile (Build All) Compile (Build All) Run Run 2
2
3
3
3
3 If no errors are reported,
If no errors are reported,
click on the
click on the
Run
Run
button.
button.
Halt Halt 4
4
4
4
Click on the
Click on the
Halt
Halt
button.
button.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 410 1317 CPL
Lab 17
Bit Fields
/ *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
VARI ABLE DECLARATI ONS
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
union {
char fullByte;
struct {
int bit0: 1;
int bit1: 1;
int bit2: 1;
int bit3: 1;
int bit4: 1;
int bit5: 1;
int bit6: 1;
int bit7: 1;
} bitField;
} bitByte;
Bit Field Definition
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 411 1317 CPL
Lab 17
Bit Fields
Demo Results 1
bitByte.fullByte
= 0x55;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 412 1317 CPL
Lab 17
Bit Fields
Demo Results 2
bitByte.bitField.bit0 = 0;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 413 1317 CPL
Lab 17
Bit Fields
Demo Results 3
bitByte.bitField.bit2 = 0;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 414 1317 CPL
Lab 17
Bit Fields
Demo Results 4
bitByte.bitField.bit7 = 1;
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 415 1317 CPL
Lab 17
Conclusions
Bit fields provide an efficient mechanism
to store Boolean values, flags and
semaphores in data memory
Care must be used if code size or speed is
a concern
Compiler will usually make use of bit set/bit
clear instructions
In some circumstances this isn't possible
(comparing bit values)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 416 1317 CPL
Enumerations
Enumerations
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 417 1317 CPL
Definition
Enumerations
Enumerations:
Are unique integer data types
May only contain a specified list of values
Values are specified as symbolic constants
Enumerations
Enumerations
are integer data types that you can create
are integer data types that you can create
with a limited range of values. Each value is represented by
with a limited range of values. Each value is represented by
a symbolic constant that may be used in conjunction with
a symbolic constant that may be used in conjunction with
variables of the same enumerated type.
variables of the same enumerated type.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 418 1317 CPL
Example
Syntax
Enumerations
How to Create an Enumeration Type
enum enum weekday weekday { {SUN SUN, ,
MON MON, ,
TUE TUE, ,
WED WED, ,
THR THR, ,
FRI FRI, ,
SAT SAT}; };
enum
enum
typeName
typeName
{
{
label
label
0 0
,
,
label
label
1 1
,
,
,
,
label
label
n n
}
}
Where compiler sets Where compiler sets label label
0 0
= = 0 0, , label label
1 1
= = 1 1, , label label
n n
= = n n
Creates an ordered list of constants
Each labels value is one greater than the
previous label
SUN SUN
= = 0 0, , MON MON
= = 1 1, , TUE TUE
= = 2 2, , WED WED
= = 3 3, , THR THR
= = 4 4 , , FRI FRI
= = 5 5, , SAT SAT
= = 6 6
Label Values: Label Values:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 419 1317 CPL
Example
Enumerations
How to Create an Enumeration Type
Any label may be assigned a specific value
The following labels will increment from
that value
Syntax
enum
enum
typeName
typeName
{
{
label
label
0 0
=
=
const
const
0 0
,
,
,
,
label
label
n n
}
}
Where compiler sets Where compiler sets label label
0 0
= = const const
0 0
, , label label
1 1
= ( = (const const
0 0
+ 1), ... + 1), ...
enum enum people people { {Rob Rob, ,
Steve Steve, ,
Paul Paul = =
7 7, ,
Bill Bill, ,
Gary Gary}; };
Rob Rob
= = 0 0, , Steve Steve
= = 1 1, , Paul Paul
= = 7 7, , Bill Bill
= = 8 8, , Gary Gary
= = 9 9
Label Values: Label Values:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 420 1317 CPL
Example
Syntax
Syntax
enum
enum
typeName
typeName
{
{
const
const
-
-
list
list
}
}
varname
varname
1 1
,
,
;
;
Enumerations
How to Declare an Enumeration Type Variable
enum enum weekday weekday { {SUN SUN, ,
MON MON, ,
TUE TUE, ,
WED WED, ,
THR THR, ,
FRI FRI, ,
SAT SAT} } today today; ;
enum enum
weekday weekday day day; ; //day is a variable of type weekday //day is a variable of type weekday
Declared along with type:
enum
enum
typeName
typeName
varName
varName
1 1
,
,
,
,
varName
varName
n n
;
;
Declared independently:
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 421 1317 CPL
Example
Syntax
enum
enum
{
{
const
const
-
-
list
list
}
}
varName
varName
1 1
,
,
,
,
varName
varName
n n
;
;
Enumerations
How to Declare a Tagless
Enumeration Variable
enum enum { {SUN SUN, ,
MON MON, ,
TUE TUE, ,
WED WED, ,
THR THR, ,
FRI FRI, ,
SAT SAT} } today today; ;
No type name specified:
Only variables specified as part of the enum
declaration may be of that type
No type name is available to declare additional
variables of the enum
type later in code
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 422 1317 CPL
Example
Syntax
typedef enum
typedef enum
{
{
const
const
-
-
list
list
}
}
typeName
typeName
;
;
Enumerations
How to Declare an Enumeration Type with typedef
typedef enum typedef enum { {SUN SUN, ,
MON MON, ,
TUE TUE, ,
WED WED, ,
THR THR, ,
FRI FRI, ,
SAT SAT} } weekday weekday; ;
weekday weekday
day day; ; //Variable of type weekday //Variable of type weekday
Variables may be declared as type typeName
without needing the enum
keyword
The enumeration may now be used as an
ordinary data type (compatible with int)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 423 1317 CPL
Example
Syntax
varName
varName
=
=
label
label
n n
;
;
Enumerations
How to Use an Enumeration Type Variable
enum enum weekday weekday { {SUN SUN, ,
MON MON, ,
TUE TUE, ,
WED WED, ,
THR THR, ,
FRI FRI, ,
SAT SAT}; };
enum enum
weekday day weekday day; ;
day day
= = WED WED; ;
day day
= = 6 6; ; //May only use values from 0 to 6 //May only use values from 0 to 6
if if ( (day day
== == WED WED) )
{ {
If enumeration and variable have already been defined:
The labels may be used as any other symbolic constant
Variables defined as enumeration types must be used in
conjunction with the types labels or equivalent integer
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 424 1317 CPL
Lab Exercise 18
Lab Exercise 18
Enumerations
Enumerations
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 425 1317 CPL
Lab 18
Enumerations
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab18
Lab18
\
\
Lab18.mcw
Lab18.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 426 1317 CPL
Lab 18
Enumerations
Compile and run the code:
2
2
Click on the
Click on the
Build All
Build All
button.
button.
Compile (Build All) Compile (Build All) Run Run 2
2
3
3
3
3 If no errors are reported,
If no errors are reported,
click on the
click on the
Run
Run
button.
button.
Halt Halt 4
4
4
4
Click on the
Click on the
Halt
Halt
button.
button.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 427 1317 CPL
Lab 18
Enumerations
typedef enum
{BANDSTOP, LOWPASS, HIGHPASS, BANDPASS} filterTypes;
filterTypes
filter;
/ *============================================================================
FUNCTI ON: mai n( )
============================================================================*/
int
main(void)
{
filter = BANDPASS;
switch
(filter)
{
case
BANDSTOP: BandStopFilter(); break;
case
LOWPASS: LowPassFilter(); break;
case
HIGHPASS: HighPassFilter(); break;
case
BANDPASS: BandPassFilter(); break;
}
while(1);
}
Enum Definition and Use
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 428 1317 CPL
Lab 18
Conclusions
Enumerations provide a means of
associating a list of constants with one or
more variables
Make code easier to read and maintain
Variables declared as enum
are essentially
still int
types
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 429 1317 CPL
Macros with #define
Macros with #define
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 430 1317 CPL
Macros with #define
Macros
Are evaluated by the preprocessor
Are not executable code themselves
Can control the generation of code before the
compilation process
Provide shortcuts
Definition
Macros
Macros
are text replacements created with #define that
are text replacements created with #define that
insert code into your program. Macros may take parameters
insert code into your program. Macros may take parameters
like a function, but the macro code and parameters are
like a function, but the macro code and parameters are
always inserted into code by text substitution.
always inserted into code by text substitution.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 431 1317 CPL
Macros with #define
Simple Macros
Text substitution as seen earlier
Syntax
#define
#define
label text
label text
Every instance of label in the current file will be
replaced by text
text can be anything you can type into your editor
Arithmetic expressions evaluated at compile time
Example
#define #define
Fosc Fosc
4000000 4000000
#define #define
Tcy Tcy
(0.25 * (1/Fosc)) (0.25 * (1/Fosc))
#define #define
Setup Setup InitSystem(Fosc InitSystem(Fosc, 250, 0x5A) , 250, 0x5A)
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 432 1317 CPL
Macros with #define
Argument Macros
Create a function-like macro
Syntax
#define
#define
label
label
(
(
arg
arg
1 1
,
,
,
,
arg
arg
n n
)
)
code
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
#define #define
min(x min(x, y) ((x)<( , y) ((x)<(y)?(x):(y y)?(x):(y)) ))
#define #define
square(x square(x) ((x)*(x)) ) ((x)*(x))
#define #define
swap(x swap(x, y) { x ^= y; y ^= x; x ^= y; } , y) { x ^= y; y ^= x; x ^= y; }
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 433 1317 CPL
Macros with #define
Argument Macros
Side Effects
Example
#define
#define
square(a
square(a
) ((a)*(a))
) ((a)*(a))
Extreme care must be exercised when using macros.
Extreme care must be exercised when using macros.
Consider the following use of the above macro:
Consider the following use of the above macro:
i = 5;
i = 5;
x =
x =
square(i
square(i
++);
++);
x = 30 x = 30
i = 7 i = 7
Results: Results:
x = x = square(i square(i++); ++);
expands to: expands to:
x = ((i++)*(i++)); x = ((i++)*(i++));
So i gets incremented twice, not So i gets incremented twice, not
once at the end as expected. once at the end as expected.
Wrong Answers!
Wrong Answers!
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 434 1317 CPL
Lab Exercise 19
Lab Exercise 19
Macros with #define
Macros with #define
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 435 1317 CPL
Lab 19
#define Macros
Open the projects workspace:
On the lab PC
On the lab PC
C:
C:
\
\
Masters
Masters
\
\
1317
1317
\
\
Lab19
Lab19
\
\
Lab19.mcw
Lab19.mcw
1
1
Open MPLAB
Open MPLAB
IDE and select
IDE and select
Open
Open
Workspace
Workspace
from the
from the
File
File
menu.
menu.
Open the file listed above.
Open the file listed above.
If you already have a project open
If you already have a project open
in MPLAB, close it by selecting
in MPLAB, close it by selecting
Close Workspace
Close Workspace
from the
from the
File
File
menu before opening a new one.
menu before opening a new one.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 436 1317 CPL
Lab 19
#define
Macros
Compile and run the code:
2
2
Click on the
Click on the
Build All
Build All
button.
button.
Compile (Build All) Compile (Build All) Run Run 2
2
3
3
3
3 If no errors are reported,
If no errors are reported,
click on the
click on the
Run
Run
button.
button.
Halt Halt 4
4
4
4
Click on the
Click on the
Halt
Halt
button.
button.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 437 1317 CPL
Lab 19
#define
Macros
/ *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MACROS
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#define square(m)
((m) * (m))
#define BaudRate(DesiredBR, FoscMHz)
((((FoscMHz
* 1000000)/DesiredBR)/64)-1)
/ *============================================================================
FUNCTI ON: mai n( )
============================================================================*/
int main(void)
{
x = square(3);
printf("x = %d\n", x);
SPBRG = BaudRate(9600, 16);
printf("SPBRG
= %d\n", SPBRG);
}
#define Macro Definition and Use
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 438 1317 CPL
Lab 19
Conclusions
#define macros can dramatically simplify
your code and make it easier to maintain
Extreme care must be taking when crafting
a macro due to the way they are
substituted within the text of your code
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 439 1317 CPL
Resources
A Selection of C Compilers
Microchip Technology MPLAB
C30 and MPLAB
C18
(Free 'student' versions available)
http://www.microchip.com
Hi-Tech PICC
Compiler, PICC-18, C for dsPIC
DSC/PIC24
http://www.htsoft.com
Custom Computer Services Inc. (CCS) C Compilers
http://www.ccsinfo.com
ByteCraft Ltd. MPC
http://www.bytecraft.com
IAR Systems Embedded Workbench
http://www.iar.com
Small Device C Compiler (Free)
http://sourceforge.net/projects/sdcc/
SourceBoost
BoostC
http://www.sourceboost.com/
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 440 1317 CPL
Resources
Books
General C Language
The C Programming Language
2
nd
Edition (March 22, 1988)
Brian W. Kernighan & Dennis Ritchie
ISBN-10: 0131103628
ISBN-13: 978-0131103627
SAMS Teach Yourself C in 21 Days
6
th
Edition (September 25, 2002)
Bradley L. Jones & Peter Aitken
ISBN-10: 0672324482
ISBN-13: 978-0672324482
Beginning C From Novice to Professional
4
th
Edition (October 19, 2006)
Ivor
Horton
ISBN-10: 1590597354
ISBN-13: 978-1590597354
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 441 1317 CPL
Resources
Books
General C Language
Programming Embedded Systems
with C and GNU Development Tools
2
nd
Edition (October 1, 2006)
Michael Barr & Anthony Massa
ISBN-10: 0596009836
ISBN-13: 978-0596009830
Practical C Programming
3
rd
Edition (August 1, 1997)
Steve Oualline
ISBN-10: 1565923065
ISBN-13: 978-1565923065
Code Complete
2
nd
Edition (June 2004)
Steve McConnell
ISBN-10: 0735619670
ISBN-13: 978-0735619678
Not about C
specifically, but a
must read for all
software engineers
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 442 1317 CPL
Resources
Books
PIC
MCU Specific
Programming 16-bit Microcontrollers in C
Learning to Fly the PIC24
1
st
Edition (March 16, 2007)
Lucio Di Jasio
ISBN-10: 0750682922
ISBN-13: 978-0750682923
Embedded C Programming and the Microchip PIC
1
st
Edition (November 3, 2003)
Richard H. Barnett, Sarah Cox, Larry O'Cull
ISBN-10: 1401837484
ISBN-13: 978-1401837488
PICmicro MCU C:
An Introduction to Programming the Microchip PIC in CCS C
2
nd
Edition (August 19, 2002)
Nigel Gardner
ISBN-10: 0972418105
ISBN-13: 978-0972418102
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 443 1317 CPL
Resources
Books
Compiler Specific
MPLAB
C30 C Compiler User's Guide
Current Edition (PDF)
Microchip Technology
DS51284
http://www.microchip.com
MPLAB
ASM30, LINK30 and Utilities User's
Guide
Current Edition (PDF)
Microchip Technology
DS51317
http://www.microchip.com
The Definitive Guide to GCC
2
nd
Edition (August 11, 2006)
William von Hagen
ISBN-10: 1590595858
ISBN-13: 978-1590595855
MPLAB
C30
Compiler
Users Guide
MPLAB
ASM30,
LINK30 and
Utilities
Users Guide
MPLAB
C30
is based on the
GCC tool chain
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 444 1317 CPL
MPASM
MPLINK
MPLIB
Users Guide
MPLAB
C18
Compiler
Users Guide
Resources
Books
Compiler Specific
MPLAB
C18 C Compiler User's Guide
Current Edition (PDF)
Microchip Technology
DS51288
http://www.microchip.com
MPASM
MPLINK
and MPLIB
User's Guide
Current Edition (PDF)
Microchip Technology
DS33014
http://www.microchip.com
The older books on C are much more relevant to embedded C The older books on C are much more relevant to embedded C
programming since they were written back when PCs and other comp programming since they were written back when PCs and other computers uters
had limited resources and programmers had to manage them careful had limited resources and programmers had to manage them carefully. ly.
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 445 1317 CPL
Thank You!
2009 Microchip Technology Incorporated. All Rights Reserved. Slide 446 1317 CPL
Trademarks
The Microchip name and logo, the Microchip logo, dsPIC, KeeLoq, KeeLoq logo,
MPLAB, PIC, PICmicro, PICSTART, 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, ICSP, ICEPIC, Mindi, MiWi, MPASM,
MPLAB Certified logo, MPLIB, MPLINK, mTouch, nanoWatt XLP, Omniscient
Code Generation, PICC, PICC-18, PICkit, PICDEM, PICDEM.net, PICtail, PIC32
logo, REAL ICE, rfLAB, Select Mode, Total Endurance, TSHARC, 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.
2009, Microchip Technology Incorporated, Printed in the U.S.A., All Rights
Reserved.