0% found this document useful (0 votes)
20 views68 pages

Lecture 5

This lecture introduces the C programming language, focusing on its structure, syntax rules, and essential components such as data types, variables, and control statements. Key topics include the organization of a C program, the use of flowcharts for software design, and the importance of structured programming. Additionally, it covers standard input/output functions and the significance of proper punctuation and readability in code.

Uploaded by

pangunpark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views68 pages

Lecture 5

This lecture introduces the C programming language, focusing on its structure, syntax rules, and essential components such as data types, variables, and control statements. Key topics include the organization of a C program, the use of flowcharts for software design, and the importance of structured programming. Additionally, it covers standard input/output functions and the significance of proper punctuation and readability in code.

Uploaded by

pangunpark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lecture 5 :

Introduction to C

Pangun Park
Chungnam National University
Information Communications Engineering

Some materials from


“Embedded Systems – Shape the world” by Jonathan Valvano and Ramesh Yerraballi

1
Learning Objectives
§ Know the elements of a C program: What goes where, what are the
syntax rules
§ Know declarations: simple data types, char, short, long (unsigned and
signed)
§ Know the form of the mandatory main subroutine for a program to be
executable
§ Know the basic assignment statement: variable = expression;
§ Know how to use printf and scanf for I/O.
§ Know the basic form of the if-statement and the while(1) statement
and how they use the conditional Boolean expression.

Pangun Park (CNU) 2


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 3


Popular Programming Languages
§ Over the last ten years, it has ranked one or two out of all high-level
languages.
Ø C is by far the most common language for writing software for embedded
systems.

Pangun Park (CNU) 4


Introduction to Programming in C
§ Before we write software, we need to develop a plan.
Ø Software development is an iterative process.

§ Structured programming
Ø One of the fundamentals when developing software, regardless whether it is a
microcontroller with 1000 lines of assembly code or a large computer system
with billions of lines of code, is to maintain a consistent structure.

§ Structured programming has four templates


Ø Sequential: first one operation then the next operation in order
Ø Decision: test some condition and execute one operation or the other
Ø Iterative: repeat an operation over and over until a condition becomes true
Ø Interrupt : software executes a task when a certain hardware condition
becomes true.

Pangun Park (CNU) 5


Flowcharts
§ Flowcharts to illustrate what the software does

Flowchart symbols.

Ø Entry point is the starting point of the software.


• Each function, or subroutine, also has an entry point.
Ø Exit point returns the flow of control back to the place from which the
function was called.
• When the software runs continuously, as is typically the case in an embedded
system, there will be no main exit point.
Ø Process block might involve many operations, but in a low-level flowchart, the
exact operation is defined in the rectangle.
Ø Input/Output operations are an important part of embedded systems.

Pangun Park (CNU) 6


Flowcharts
Ø Inside the conditional block, we can define what is being tested.
• Each arrow out of a condition block must be labeled with the condition causing
flow to go in that direction. The condition for each arrow must be mutually
exclusive. Furthermore, the complete set of conditions must define all possibilities.
Ø The rectangle with double lines on the side specifies a call to a predefined
function.
• Functions, subroutines, and procedures are terms that all refer to a well-defined
section of code that performs a specific operation. When a function (or subroutine
or procedure) is called, the software execution path jumps to the function, the
specific operation is performed, and the execution path returns to the point
immediately after the function call.
• We will use the terms subroutine, procedure, function, and program
interchangeably.
Ø Circles are used as connectors.
• Connectors with an arrow pointing into the circle are jumps or goto commands.
When the flow reaches a goto connector, the execution path jumps to the position
specified by the corresponding label connector. It is bad style to use a lot of
connectors.

Pangun Park (CNU) 7


Structured programs in C
§ Structured programs in C are built from three basic templates:
the sequence, the conditional, and the while-loop.

Flowchart showing the basic building blocks of structured programming.

Pangun Park (CNU) 8


Example : Toaster
§ Requirement:
Ø There will be a start button the user pushes to activate the machine.
Ø There is other input that measures toast temperature. The desired temperature
is preprogrammed into the machine.
Ø The output is a heater, which can be on or off. The toast is automatically
lowered into the oven when heat is applied and is ejected when the heat is
turned off.

Flowchart illustrating the process of making toast.


Pangun Park (CNU) 9
Using Flowcharts to Design
§ Software development is an iterative process.
§ General development process into 4 steps
Ø 1) We begin with a list of the inputs and outputs. This usually defines what
the overall system will do. We specify the range of values and their
significance.
Ø 2) Next, we make a list of the required data. We must decide how the data is
structured, what does it mean, how it is collected, and how it can be
changed.
Ø 3) Next we develop the software algorithm, which is a sequence of operations
we wish to execute. There are many approaches to describing the plan.
Experienced programmers can develop the algorithm directly in C language.
On the other hand, most of us need an abstractive method to document the
desired sequence of actions. Flowcharts and pseudo code are two common
descriptive formats.
Ø 4) The last stage is debugging. Learning debugging skills will greatly improve
the quality of your software and the efficiency at which you can develop code.

Pangun Park (CNU) 10


Example: Switch + LED
§ Requirement:
Ø The system has one input and one output. An event should be recognized when the
input goes from 0 to 1 and back to 0 again. In this example, we assume the input is
initially 0. The output is initially 0, but should go 1 after four events are detected. After
this point, the output should remain 1.

Pangun Park (CNU) 11


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 12


Terminology
§ Compiler is system software that converts a high-level language
program (human readable format) into object code (machine readable
format).
Ø To change the software we need to edit the source code and recompile.
C code (z = x+y;) → Assembly code (ADD R2,R1,R0) → Machine code (0xEB010200)

§ Assembler is system software that converts an assembly language


program (human readable format) into object code (machine readable
format).
Assembly code (ADD R2,R1,R0) → Machine code (0xEB010200)

§ Interpreter executes directly the high level language. It is interactive


but runs slower than compiled code.

Pangun Park (CNU) 13


Terminology
§ Linker builds software system by connecting (linking) software
components.
Ø In Keil uVision, the build command (Project->BuildTarget) performs both
a compilation and a linking.
startup.s
uart.c
main.c

§ Loader will place the object code in memory. In an embedded system,


the loader will program object code into flash ROM.
Ø In Keil uVision, the download command (Flash->Download) performs a load
operation.
§ Debugger is a set of hardware and software tools we use to verify
system is operating correctly.

Pangun Park (CNU) 14


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 15


Punctuation
§ Punctuation marks (semicolons, colons, commas, apostrophes,
quotation marks, braces, brackets, and parentheses) are very important
in C.
Punctuation Meaning
; End of statement
: Defines a label
, Separates elements of a list
( ) Start and end of a parameter list
{ } Start and stop of a compound statement
[ ] Start and stop of a array index
" " Start and stop of a string
' ' Start and stop of a character constant
Special characters can be punctuation marks.

Pangun Park (CNU) 16


Software Readability
§ Although spaces, tabs, and line breaks are syntactically equivalent, their
proper usage will have a profound impact on the readability of your
software.
§ The following three functions produce the same results when executed,
the differences therefore are style.
unsigned long M=1;unsigned long Random1(void){M=1664525*M+1013904223;return(M);}
unsigned long M=1;
unsigned long
Random2(void){
M = 1664525
*M
+1013904223;
return(M);
}
unsigned long M=1;
unsigned long Random3(void){
M = 1664525*M+1013904223;
return(M);
}

Pangun Park (CNU) 17


Sections of a Program
§ General four sections of C program

//**** 0. Documentation Section


// This program calculates the area of square shaped rooms
// Author: Ramesh Yerraballi & Jon Valvano
// Date: 11/20/2015
//
// 1. Pre-processor Directives Section
#include <stdio.h> // Diamond braces for sys lib: Standard I/O
#include "uart.h" // Quotes for user lib: UART lib
// 2. Global Declarations section
// 3. Subroutines Section
// MAIN: Mandatory routine for a C program to be executable
int main(void) {
UART_Init(); // call subroutine to initialize the uart
printf("This program calculates areas of square-shaped
rooms\n");
}

Software to calculate the area of a square room.

Pangun Park (CNU) 18


Sections of a Program
§ 1. Documentation section
Ø Includes the purpose of the software, the authors, the date, and any copyright
information. When the software involves external hardware we will add
information about how the external hardware is connected.
§ 2. Preprocessor directives.
Ø We will use the preprocessor directive #include to connect this software with
other modules. We use diamond braces to include system libraries, like the
standard I/O, and we use quotes to link up with other user code within the
project.
Ø In this case the uart module is software we wrote to perform I/O with the
universal asynchronous receiver/transmitter (uart).
§ 3. Global declarations.
Ø This section will include global variables and function prototypes for functions
defined in this module.
§ 4. Functions.
Ø Every software system in C has exactly one main program, which defines
where it begins execution.
Pangun Park (CNU) 19
§
Sections of a Program
§ Two types of comments
Ø The first type explains how to use the software. These comments are usually
placed at the top of the file, within the header file, or at the start of a function.
Ø The second type of comments assists a future programmer (ourselves
included) in changing, debugging or extending these routines.
§ Preprocessor directives begin with # in the first column.
Ø As the name implies preprocessor commands are processed first. I.e., the
compiler passes through the program handling the preprocessor directives.

#define SIZE 10 wherever SIZE is found as a token, it is


replaced with the 10.

#include "tm4c123gh6pm.h" This file will define all the I/O port names for
the TM4C123.

Pangun Park (CNU) 20


Standard I/O and Printf
§ Configure the TM4C123 to use printf using the UART.
Ø The first one configures the I/O through the UART Printf_UART_4C123.
Ø The second one configures output to the Nokia 5110 Printf_Nokia_4C123.
• At the low level, we implement how the output actually happens by writing
a fputc function. The fputc function is a private and implemented inside
the UART.c, or Nokia5110.c file.
• This abstraction clearly separates what it does (printf outputs information) from
how it works (fputc sends data to the display over UART or SSI).

Ø To make the standard input and output library available to your program, you
must include one of these UART.c (Nokia5110.c) files in your project, and add
these lines, replacing UART.h (Nokia5110.h) as appropriate:

#include <stdio.h>
#include "UART.h"

Pangun Park (CNU) 21


Standard I/O and Printf
Example code Output
printf("Hello world\n"); Hello world
printf("cc = %c %d %#x\n",cc,cc,cc); cc = V 86 0x56
printf("xx = %c %d %#x\n",xx,xx,xx); xx = d 100 0x64
printf("yy = %d %#x\n",yy,yy); yy = -100 0xffffff9c
printf("zz = %f %3.2f\n",zz,zz); zz = 3.141593 3.14

Ø cc is an 8-bit variable containing 0x56 (‘V’)


Ø xx is a 32-bit variable containing 100
Ø yy is a 16-bit variable containing -100
Ø zz is a 32-bit floating containing 3.14159265.
Specifier Output Example
c Character a
d or i Signed decimal integer 392
ld Signed 32-bit long decimal integer 1234567890
e Scientific notation 6.022141e23
E Scientific notation, capital letter 6.022141E23
f Floating point 3.14159
o Unsigned octal 610
s String of characters sample
u Unsigned decimal integer 7235
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (capital letters) 7FA
% %% will write % to stdout %
Pangun Park (CNU) 22
Standard I/O and Printf
Flags Description
- Left-justify within the given field width
+ Forces the result to have a plus or minus sign
(space) If no sign is going to be written, a blank space is inserted before the value.
# Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values
different than zero.
0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width
sub-specifier).

printf("%x", 13); // prints just 'd'


printf("%#x", 13); // prints '0xd'
printf("%X", 13); // prints just 'D'
printf("%#X", 13); // prints '0XD'
printf("%o", 13); // prints just '15'
printf("%#o", 13); // prints '015'

printf("%.4d", 7); // prints '0007'


printf("%.4d", 123456); // prints '123456'
printf("%3s", "Jonathan"); // prints 'Jonathan'
printf("%.3s", "Jonathan"); // prints 'Jon'
printf("%3s", "JV"); // prints 'JV '
printf("%.3s", "JV"); // prints 'JV'

Pangun Park (CNU) 23


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 24


Data Types and Variables

Data type Precision Range


unsigned char 8-bit unsigned 0 to +255
signed char 8-bit signed -128 to +127
unsigned int compiler-dependent
int compiler-dependent
unsigned short 16-bit unsigned 0 to +65535
short 16-bit signed -32768 to +32767
unsigned long unsigned 32-bit 0 to 4294967295L
long signed 32-bit -2147483648L to
2147483647L
float 32-bit float ±10-38 to ±10+38
double 64-bit float ±10-308 to ±10+308
Data types in C.

Pangun Park (CNU) 25


Expressions
Operation Meaning Operation Meaning
= Assignment statement == Equal to comparison
? Selection <= Less than or equal to
< Less than >= Greater than or equal to
> Greater than != Not equal to
! Logical not (true to false, false to true) << Shift left
~ 1’s complement >> Shift right
+ Addition ++ Increment
- Subtraction -- Decrement
* Multiply or pointer reference && Boolean and
/ Divide || Boolean or
% Modulo, division remainder += Add value to
| Logical or -= Subtract value to
& Logical and, or address of *= Multiply value to
^ Logical exclusive or /= Divide value to
. Used to access parts of a structure |= Or value to
&= And value to
Special characters can be operators; ^= Exclusive or value to

operators can be made from 1, 2, or 3 <<= Shift value left


characters. >>= Shift value right
%= Modulo divide value to

Pangun Park (CNU) -> Pointer to a structure


26
Expressions
Precedence Precedence and associativity determine the
Operators order of operation.
Associativity
Highest () []. -> ++(postfix) --(postfix) Left to right
++(prefix) --(prefix) ! ~ sizeof(type) +(unary) Right to left
-(unary) &(address) *(dereference)
* / % Left to right
+ - Left to right
<< >> Left to right
< <= > >= Left to right
== != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= %= <<= >>= |= &= ^= Right to left
Lowest , Left to right

Precedence and associativity determine the order of operation.

Pangun Park (CNU) 27


Expressions
§ Example
void main(void){
long x,y,z; // Three local variables
x=1; y=2; // set the values of x and y
z = x+4*y; // arithmetic operation
x++; // same as x=x+1;
y--; // same as y=y-1;
x = y<<2; // left shift same as x=4*y;
z = y>>2; // right shift same as x=y/4;
y += 2; // same as y=y+2;
}

Simple program illustrating C arithmetic operators.

Pangun Park (CNU) 28


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 29


Function Syntax
§ Function is a sequence of operations that can be invoked from other
places within the software.
§ Declaration and Definition
Ø function declaration specifies its name, its input parameters and its output
parameter. Another name for a function declaration is prototype.
• declaration shows us how to use the function, not how the function works.
Ø function definition specifies the exact sequence of operations to execute when
it is called. A function definition will generate object code, which are machine
instructions to be loaded into memory that perform the intended operations.

§ C compilation is a one-pass process, an object must be declared or


defined before it can be used in a statement.

Pangun Park (CNU) 30


Function Syntax
Top-down approach Bottom-down approach
unsigned long Calc_Area(unsigned long s); // Calculates area
int main(void) { // Input: side of a room (unsigned long) in
unsigned long side; // room wall meters meters
unsigned long area; // size squared meters // Output: area of the room (unsigned long) in
UART_Init(); // call subroutine to initialize square meters
the uart unsigned long Calc_Area(unsigned long s) {
printf("This program calculates areas of square- unsigned long result;
shaped rooms\n"); result = s*s;
side = 3; return(result);
area = Calc_Area(side); }
printf("\nArea of the room with side of %ld m is int main(void) {
%ld sqr m\n",side,area); unsigned long side; // room wall meters
side = side+2; unsigned long area; // size squared meters
area = Calc_Area(side); UART_Init(); // call subroutine to initialize
printf("\nArea of the room with side of %ld m is the uart
%ld sqr m\n",side,area); printf("This program calculates areas of
} square-shaped rooms\n");
// Calculates area side = 3;
// Input: side of a room (unsigned long) in area = Calc_Area(side);
meters printf("\nArea of the room with side of %ld m
// Output: area of the room (unsigned long) in is %ld sqr m\n",side,area);
square meters side = side+2;
unsigned long Calc_Area(unsigned long s) { area = Calc_Area(side);
unsigned long result; printf("\nArea of the room with side of %ld m
result = s*s; is %ld sqr m\n",side,area);
return(result); }
}

A main program that calls a function. In A main program that calls a function. In this
this case the declaration occurs first. case the definition occurs before its use.
Pangun Park (CNU) 31
Function Parameters

• The Address shows the ROM location into which the instruction is stored.
• The Machine code is the actual instruction in hexadecimal format.
• The Label is a symbol marking that spot in the program. We use labels to call
functions and the jump to other locations in the same program.
• Each Instruction has an op code and one or more operands.
• The Comments were added to explain what the program is doing.

Pangun Park (CNU) 32


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 33


Keyword Meaning
__asm C Keywords and Punctuation
Specify a function is written in assembly code (specific to ARM Keil™uVision®)
auto Specifies a variable as automatic (created on the stack)
break Causes the program control structure to finish
case One possibility within a switch statement
char Defines a number with a precision of 8 bits
const Defines parameter as constant in ROM, and defines a local parameter as fixed value
continue Causes the program to go to beginning of loop
default Used in switch statement for all other cases
do Used for creating program loops
Keywords have predefined meanings.
double Specifies variable as double precision floating point
else Alternative part of a conditional
extern Defined in another module
float Specifies variable as single precision floating point
for Used for creating program loops
goto Causes program to jump to specified location
if Conditional control structure
int Defines a number with a precision that will vary from compiler to compiler
long Defines a number with a precision of 32 bits
register Specifies how to implement a local
return Leave function
short Defines a number with a precision of 16 bits
signed Specifies variable as signed (default)
sizeof Built-in function returns the size of an object
static Stored permanently in memory, accessed locally
struct Used for creating data structures
switch Complex conditional control structure
typedef Used to create new data types
unsigned Always greater than or equal to zero
void Used in parameter list to mean no parameter
volatile Can change implicitly outside the direct action of the software.
while Used for creating program loops
Pangun Park (CNU) 34
If-Then Conditional

unsigned long error;


// Calculates area
// Input: side of a room (unsigned long)
// Output: area of the room (unsigned long)
// Notes: ...
unsigned long Calc_Area(unsigned long s) {
unsigned long result;
if(s <= 25){
result = s*s;
}else{
result = 0; // mistake
error = error +1;
}
return(result);
}

Simple program illustrating the C if else control structure.

Pangun Park (CNU) 35


While Loop

int main(void) {
unsigned long side; // room wall meters
unsigned long area; // size squared meters
UART_Init(); // call subroutine to initialize the uart
printf("This program calculates areas of square-shaped rooms\n");
side = 1;
while(side < 50){
area = Calc_Area(side);
printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area);
side = side+1;
}
}
Simple program illustrating the C while control structure.

Pangun Park (CNU) 36


For Loop
for(part1;part2;part3){body;}
Ø The first part is executed once at the beginning.
Ø Before the body is executed, the end-condition part 2 is executed.
Ø If the condition is true, then the body is executed. The second part is always a
conditional that results in a true or a false.
Ø After the body is executed, the third part is executed. The body and third part are
repeated until the conditional is false.

int main(void) {
unsigned long side; // room wall meters
unsigned long area; // size squared meters
UART_Init(); // call subroutine to initialize the uart
printf("This program calculates areas of square-shaped rooms\n");
for(side = 1; side < 50; side = side+1){
area = Calc_Area(side);
printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area);
}
}

Simple program illustrating the C for-loop control structure.

Pangun Park (CNU) 37


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 38


Punctuation
§ Punctuation marks (semicolons, colons, commas, apostrophes,
quotation marks, braces, brackets, and parentheses) are very important
in C.
Punctuation Meaning
; End of statement
: Defines a label
, Separates elements of a list
( ) Start and end of a parameter list
{} Start and stop of a compound statement
[ ] Start and stop of a array index
" " Start and stop of a string
' ' Start and stop of a character constant
Special characters can be punctuation marks.

Pangun Park (CNU) 39


Keyword Meaning
__asm C Keywords and Punctuation
Specify a function is written in assembly code (specific to ARM Keil™uVision®)
auto Specifies a variable as automatic (created on the stack)
break Causes the program control structure to finish
case One possibility within a switch statement
char Defines a number with a precision of 8 bits
const Defines parameter as constant in ROM, and defines a local parameter as fixed value
continue Causes the program to go to beginning of loop
default Used in switch statement for all other cases
do Used for creating program loops
Keywords have predefined meanings.
double Specifies variable as double precision floating point
else Alternative part of a conditional
extern Defined in another module
float Specifies variable as single precision floating point
for Used for creating program loops
goto Causes program to jump to specified location
if Conditional control structure
int Defines a number with a precision that will vary from compiler to compiler
long Defines a number with a precision of 32 bits
register Specifies how to implement a local
return Leave function
short Defines a number with a precision of 16 bits
signed Specifies variable as signed (default)
sizeof Built-in function returns the size of an object
static Stored permanently in memory, accessed locally
struct Used for creating data structures
switch Complex conditional control structure
typedef Used to create new data types
unsigned Always greater than or equal to zero
void Used in parameter list to mean no parameter
volatile Can change implicitly outside the direct action of the software.
while Used for creating program loops
Pangun Park (CNU) 40
C Keywords and Punctuation
§ Volatile keyword disables compiler optimization, forcing the compiler
to fetch a new value each time.
Ø Use volatile when defining I/O ports because the value of ports can change
outside of software action.
Ø Use volatile when sharing a global variable between the main program and an
interrupt service routine.
§ Punctuation marks are very important in C.
Ø It is one of the most frequent sources of errors for both beginning and
experienced programmers.

Pangun Park (CNU) 41


C Keywords and Punctuation
§ Semicolons are used as statement terminators.
Ø Strange and confusing syntax errors may be generated when you forget a
semicolon, so this is one of the first things to check when trying to remove
syntax errors.

The #define statement creates a substitution rule, such that every instance
of STEPPER in the program is replaces with (*((volatile unsigned
long *)0x4000703C)). (Preprocessor directives do not end with a
semicolon since they are not actually part of the C language proper.)
#define STEPPER (*((volatile unsigned long *)0x4000703C))
void Step(void){
STEPPER = 10;
STEPPER = 9;
STEPPER = 5; When executed, the function Step will output the
STEPPER = 6; pattern 10, 9, 5, 6 to Port D.
}
Semicolons are used to separate one statement from the next.

Pangun Park (CNU) 42


C Keywords and Punctuation
§ Example: Fill the array DataBuffer with data read from the input Port
A.
Ø Square brackets enclose array dimensions (in declarations) and subscripts (in
expressions).

unsigned char DataBuffer[100];


#define GPIO_PORTA_DATA_R (*((volatile unsigned long *)0x400043FC))
void Fill(void){ long j;
for(j=0; j<100; j++){
DataBuffer[j] = GPIO_PORTA_DATA_R;
}
}

Semicolons are used to separate three fields of the for statement.

Pangun Park (CNU) 43


C Keywords and Punctuation
§ Example: One output to the stepper motor produced each time the
function OneStep is called.
Ø The proper stepper motor sequence is 10–9–5–6. The default case is used to
restart the pattern.
unsigned char Last=10; Colons terminate case,
void OneStep(void){ and default prefixes that appear
unsigned char theNext; in switch statements.
switch(Last){
case 10: theNext = 9; break; // 10 to 9
case 9: theNext = 5; break; // 9 to 5
case 5: theNext = 6; break; // 5 to 6
case 6: theNext = 10; break; // 6 to 10
default: theNext = 10;
}
GPIO_PORTD_DATA_R = theNext;
Last = theNext; // set up for next call
}

Colons are also used with the switch


statement.
Pangun Park (CNU) 44
C Keywords and Punctuation
§ Commas separate items that appear in lists.
unsigned short beginTime,endTime,elapsedTime;

§ Lists are also used with functions having multiple parameters, both
when the function is defined and called.
short add(short x, short y){ short z;
z = x+y;
if((x>0)&&(y>0)&&(z<0))z = 32767;
if((x<0)&&(y<0)&&(z>0))z = -32768;
return(z);
}
void main(void){ short a,b;
a = add(2000,2000)
b = 0
while(1){
b = add(b,1);
}
Commas separate the parameters of a
function.

Pangun Park (CNU) 45


C Keywords and Punctuation
§ Apostrophes are used to specify character literals. Assuming the
function OutChar will display a single ASCII character.
Ø Example : display the lower case alphabet.
void Alphabet(void){ unsigned char mych;
for(mych='a'; mych<='z'; mych++){
OutChar(mych); // Print next letter
}
}

Pangun Park (CNU) 46


C Keywords and Punctuation
§ Quotation marks are used to specify string literals.
Ø Strings are stored as a sequence of ASCII characters followed by a termination
code, 0.
Ø Example: display “Hello World” twice.

const unsigned char Msg[]= "Hello World"; // string constant


void OutString(const unsigned char str[]){ int i;
i = 0;
while(str[i]){ // output until the 0 termination
OutChar(str[i]); // Print next letter
i = i+1;
}
}
void PrintHelloWorld(void){
OutString("Hello World");
OutString(Msg);
}

Pangun Park (CNU) 47


Contents
§ Introduction
§ Terminology
§ Structure and Organization
§ Variables and Expression
§ Functions
§ Conditional Branching and Loops
§ C Keywords and Punctuation
§ Pointer Basics

Pangun Park (CNU) 48


Pointers
§ The most useful and tricky concept in C language
Ø Other high level languages abstract-out this concept
§ The most powerful construct too
Ø Makes C very fast
Ø Direct interaction with hardware
Ø Solves very complicated programming problems

Pangun Park (CNU) 49


Operators used in Pointers

Dereferencing Address

*
(Value of)
&
(Address of)

Pangun Park (CNU) 50


Pointer Basics
§ Variables are allocated at addresses in computer memory (address depends on
computer/operating system)
§ Name of the variable is a reference to that memory address (direct reference)
§ A pointer variable contains a representation of an address of another
variable (indirect reference):

Name V P
Address v (some value) p (some value)
int V = 101;
Abstract
101
Representation
int *P = &V;
Concrete 4 bytes for 4 bytes for
Representation int value 101 mem address v

Pangun Park (CNU) 51


Pointer Variable Definition
§ Basic syntax: Type *Name
§ Examples:
int *P; /* P is var that can point to an int var */
float *Q; /* Q is a float pointer */
char *R; /* R is a char pointer */

§ Complex example:
int *AP[5]; /* AP is an array of 5 pointers to ints */

Pangun Park (CNU) 52


Address (&) Operator
§ The address (&) operator can be used in front of any variable object in
C
Ø The result of the operation is the location in memory of the variable
§ Syntax: &VariableReference
§ Examples:
int V;
int *P;
int A[5];
&V - memory location of integer variable V
&(A[2]) - memory location of array element 2 in array A
&P - memory location of pointer variable P

Pangun Park (CNU) 53


Pointer Variable Initialization/Assignment
§ NULL - pointer lit constant to non-existent address
Ø Used to indicate pointer points to nothing
§ Can initialize/assign pointer vars to NULL or use the address (&) op to
get address of a variable
Ø Variable in the address operator must be of the right type for the pointer (an
integer pointer points only at integer variables)
§ Examples:
int V;
int *P = &V;
int A[5];
P = &(A[2]);

Pangun Park (CNU) 54


Indirection (*) Operator
§ A pointer variable contains a memory address
§ To refer to the contents of the variable that the pointer points to, we use
indirection operator
§ Syntax: *PointerVariable
§ Example:
int V = 101;
int *P = &V;
/* Then *P would refer to the contents of the variable V
(in this case, the integer 101) */
printf(“%d”,*P); /* Prints 101 */

Pangun Park (CNU) 55


Pointer Types
§ Pointers are generally of the same size (enough bytes to represent all
possible memory addresses), but it is inappropriate to assign an address
of one type of variable to a different type of pointer
§ Example:
int V = 101;
float *P = &V; /* Generally results in a Warning */

§ Warning rather than error because C will allow you to do this (it is
appropriate in certain situations)

Pangun Park (CNU) 56


Example
§ Declare variables a, b
Ø int a, b;
§ Declare a pointer
Ø int* pa;
§ Set value of a
Øa= 10;
§ Point pa to address of a
Ø pa= &a;
§ Set value of a using pa
Ø *pa = 12;
Ø pa = &b;

Pangun Park (CNU) 57


1 /* Fig. 7.4: fig07_04.c
2 Using the & and * operators */
3 #include <stdio.h>
4
5 int main()
6 { The address of a is the value 1. Declare variables
7 int a; /* a is an integer */ of aPtr.
8 int *aPtr; /* aPtr is a pointer to an integer */
9 2 Initialize variables
10 a = 7; The * operator returns an
11 aPtr = &a; /* aPtr set to address of a */ alias to what its operand
12 3. Print
points to. aPtr points to a,
13 printf( "The address of a is %p"
so *aPtr returns a.
14 "\nThe value of aPtr is %p", &a, aPtr );
15
16 printf( "\n\nThe value of a is %d"
17 "\nThe value of *aPtr is %d", a, *aPtr );
18
19 printf( "\n\nShowing that * and & are inverses of " Notice how * and
20 "each other.\n&*aPtr = %p" & are inverses
21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr );
22
23 return 0;
24 }
The address of a is 0012FF88
The value of aPtr is 0012FF88
Program Output
The value of a is 7
The value of *aPtr is 7
Proving that * and & are complements of each other.
&*aPtr = 0012FF88
*&aPtr = 0012FF88
58
1 /* Fig. 7.4: fig07_04.c
2 Using the & and * operators */
3 #include <stdio.h>
4
5 int main()
6 { The address of a is the value 1. Declare variables
7 int a; /* a is an integer */ of aPtr.
8 int *aPtr; /* aPtr is a pointer to an integer */
9 2 Initialize variables
10 a = 7; The * operator returns an
11 aPtr = &a; /* aPtr set to address of a */ alias to what its operand
12 3. Print
points to. aPtr points to a,
13 printf( "The address of a is %p"
so *aPtr returns a.
14 "\nThe value of aPtr is %p", &a, aPtr );
15
16 printf( "\n\nThe value of a is %d"
17 "\nThe value of *aPtr is %d", a, *aPtr );
18
19 printf( "\n\nShowing that * and & are inverses of " Notice how * and
20 "each other.\n&*aPtr = %p" & are inverses
21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr );
22
23 return 0;
24 }
The address of a is 0012FF88
The value of aPtr is 0012FF88
Program Output
The value of a is 7
The value of *aPtr is 7
Proving that * and & are complements of each other.
&*aPtr = 0012FF88
*&aPtr = 0012FF88
59
Calling Functions by Reference
§ To make changes to a variable that exist after a function ends, we pass
the address of (a pointer to) the variable to the function (a reference
parameter)
§ Then we use indirection operator inside the function to change the
value the parameter points to:
void changeVar(float *cvar) {
*cvar = *cvar + 10.0;
}

float X = 5.0;

changeVar(&X);
printf(“%.1f\n”,X);

Pangun Park (CNU) 60


1 /* Fig. 7.7: fig07_07.c
2 Cube a variable using call-by-reference
3 with a pointer argument */
4
5 #include <stdio.h>
Notice how the address of 1. Function prototype
6
7 void cubeByReference( int * ); /*
number is given -
prototype */
- takes a pointer to an
8
cubeByReference expects a int.
9 int main()
pointer (an address of a variable).
10 {
11 int number = 5;
1.1 Initialize variables
12
13 printf( "The original value of number is %d", number );
2. Call function
14 cubeByReference( &number );
15 printf( "\nThe new value of number is %d\n", number );
16 Inside cubeByReference,
17 return 0; *nPtr is used (*nPtr is
18 } number).
19
20 void cubeByReference( int *nPtr )
21 { 3. Define function
22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */
23 }

The original value of number is 5


The new value of number is 125 Program Output

Pangun Park (CNU) 61


1 /* Fig. 7.7: fig07_07.c
2 Cube a variable using call-by-reference
3 with a pointer argument */
4
5 #include <stdio.h>
Notice how the address of 1. Function prototype
6
7 void cubeByReference( int * ); /*
number is given -
prototype */
- takes a pointer to an
8
cubeByReference expects a int.
9 int main()
pointer (an address of a variable).
10 {
11 int number = 5;
1.1 Initialize variables
12
13 printf( "The original value of number is %d", number );
2. Call function
14 cubeByReference( &number );
15 printf( "\nThe new value of number is %d\n", number );
16 Inside cubeByReference,
17 return 0; *nPtr is used (*nPtr is
18 } number).
19
20 void cubeByReference( int *nPtr )
21 { 3. Define function
22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */
23 }

The original value of number is 5


The new value of number is 125 Program Output

Pangun Park (CNU) 62


C-Programming Practice
§ Basic C Program Practice
Ø http://www.zybooks.com

§ (Advanced) Embedded C Program


Ø http://users.ece.utexas.edu/~valvano/embed/toc1.htm

Pangun Park (CNU) 63


Appendix

64
Calling Functions by Reference

§ A function can also return a pointer value:


float *findMax(float A[], int N) {
int I;
float *theMax = &(A[0]);
Pointer Return Values
for (I = 1; I < N; I++)
if (A[I] > *theMax) theMax = &(A[I]);
return theMax;
}
void main() {
float A[5] = {0.0, 3.0, 1.5, 2.0, 4.1};
float *maxA;
maxA = findMax(A,5);
*maxA = *maxA + 1.0;
printf("%.1f %.1f\n",*maxA,A[4]);
}

65
1D Arrays and Pointers
§ int A[5] - A is the address where the array starts (first element), it is
equivalent to &(A[0])
§ A is in some sense a pointer to an integer variable
§ To determine the address of A[x] use formula:
Ø (address of A + x * bytes to represent int)
Ø (address of array + element num * bytes for element size)
§ The + operator when applied to a pointer value uses the formula above:
Ø A + x is equivalent to &(A[x])
Ø *(A + x) is equivalent to A[x]

Pangun Park (CNU) 66


Using the Const Qualifier with Pointers
§ const qualifier - variable cannot be changed
Ø Good idea to have const if function does not need to change a variable
Ø Attempting to change a const is a compiler error
§ const pointers - point to same memory location
Ø Must be initialized when declared
int *const myPtr = &x;
Type int *const - constant pointer to an int
const int *myPtr = &x;
Regular pointer to a const int
const int *const Ptr = &x;
const pointer to a const int
x can be changed, but not *Ptr

Pangun Park (CNU) 67


1 /* Fig. 7.13: fig07_13.c
2 Attempting to modify a constant pointer to
3 non-constant data */
4 1. Declare variables
5 #include <stdio.h>
6
1.1 Declare const
7 int main()
pointer to an int.
8 { Changing *ptr is allowed - x is
9 int x, y; not a constant.
10 2. Change *ptr
11 int * const ptr = &x; /* ptr is a constant pointer to an (which is x).
12 integer. An integer can be modified
13 through ptr, but ptr always points
14 to the same memory location. */
2.1 Attempt to change
ptr.
15 *ptr = 7;
Changing ptr is an error -
16 ptr = &y;
ptr is a constant pointer.
17 3. Output
18 return 0;
19 }

FIG07_13.c:
Error E2024 FIG07_13.c 16: Cannot modify a const object in
function main Program Output
*** 1 errors in Compile ***

Pangun Park (CNU) 68

You might also like