100% found this document useful (2 votes)
86 views189 pages

EMBEDDED C

The document outlines a training agenda for Embedded C, covering topics such as the definition of embedded systems, the advantages of using C, and the features of ANSI C. It discusses the differences between embedded and desktop systems, the importance of real-time systems, and the characteristics that make C suitable for embedded programming. Additionally, it delves into the syntax, identifiers, and storage classes in ANSI C, emphasizing the language's efficiency and accessibility for developers.

Uploaded by

J.A.S SANTHOSH
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
100% found this document useful (2 votes)
86 views189 pages

EMBEDDED C

The document outlines a training agenda for Embedded C, covering topics such as the definition of embedded systems, the advantages of using C, and the features of ANSI C. It discusses the differences between embedded and desktop systems, the importance of real-time systems, and the characteristics that make C suitable for embedded programming. Additionally, it delves into the syntax, identifiers, and storage classes in ANSI C, emphasizing the language's efficiency and accessibility for developers.

Uploaded by

J.A.S SANTHOSH
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
You are on page 1/ 189

Embedded C Training

Supplying value
Agenda

Embedded systems  Embedded Systems


Why C?
ANSI C
 Why C?
Embedded SW
 ANSI C – Basic & Extended Syntax Elements
Design  Embedded Software Architecture & Design
 Coding Guidelines

SV I IP HVAC ©
Embedded Systems

Embedded systems
Why C?
ANSI C
Embedded SW
Design

Embedded Systems
Introduction

SV I IP HVAC ©
Embedded Systems

Embedded systems
Why C?
ANSI C
Embedded SW "An embedded system is an application that contains at
Design least one programmable computer (typically in the
form of a microcontroller, a microprocessor or digital
signal processor chip) and which is used by
individuals who are, in the main, unaware that the
system is computer-based." (Michael J. Pont)

SV I IP HVAC ©
Embedded Systems

Embedded systems Typical applications:


Why C?
 Automotive applications
ANSI C
Embedded SW  Aerospace applications
Design
 Defense systems
 Mobile phone systems
 Medical equipment
 Household equipment

 etc.

SV I IP HVAC ©
Embedded Systems

Embedded systems Differences between desktop systems and


Why C?
embedded systems:
ANSI C
 Embedded systems are dedicated to specific tasks,
Embedded SW
Design whereas PCs are generic computing platforms
 Embedded systems are supported by a wide array
of processors and processor architectures.
 Embedded systems are usually cost sensitive.
 Embedded systems have real-time constraints.
 The implications of software failure is much more
severe in embedded systems than in desktop
systems.

SV I IP HVAC ©
Embedded Systems

Embedded systems Differences between desktop systems and


Why C?
embedded systems:
ANSI C
 Embedded systems often have power constraints.
Embedded SW
Design  Embedded systems often must operate under
extreme environmental conditions.
 Embedded systems have far fewer system
resources than desktop systems.
 Embedded systems often store all their object code
in ROM.
 Embedded systems require specialized tools and
methods to be efficiently designed.
 Embedded microprocessors often have dedicated

SV I IP HVAC ©
debugging circuitry.
Embedded Systems

Embedded systems Differences between desktop systems and


Why C?
embedded systems:
ANSI C
 no direct man-machine-interface (MMI) and
Embedded SW
Design  usually no operating system (OS).
 in case there is an OS, most probably it is a RTOS
(Real Time Operating System)

SV I IP HVAC ©
Embedded Systems

Embedded systems What is a Real-Time System?


Why C?
 the overall correctness of the system depends on
ANSI C
Embedded SW
both the functional correctness and the timing
Design correctness. The timing correctness is at least as
important as the functional correctness
 The system responds in a timely, predictable way to
unpredictable external stimuli arrivals
A RTOS (Real-Time Operating System)
 an Operating Systems with the necessary features
to support a Real-Time System
 A Good RTOS is one that has a bounded (predictable)
behavior under all system load scenarios
SV I IP HVAC ©
Embedded Systems

Embedded systems
Why C?
Hard Real-Time:
 Missing a deadline has catastrophic results
ANSI C
Embedded SW for the system
Design
Firm Real-Time
 Missing a deadline causes an
unacceptable quality reduction
Soft Real-Time
 Reduction in system quality is acceptable
 Deadlines may be missed and can be
recovered from
Non Real-Time
 No deadlines have to be met

SV I IP HVAC ©
Embedded Systems

Embedded systems  Real-time systems must quickly react to external


Why C?
events and process a certain part of code that is
ANSI C
associated with the event. This is usually performed
Embedded SW
Design using interrupts.

 As soon as an event generates an interrupt, the


CPU temporarily suspends the current program
execution and branches to the appropriate interrupt
service routine. The current program status is saved
on the system stack.

SV I IP HVAC ©
Why C?

Embedded systems
Why C?
ANSI C
Embedded SW
Design

Why C?

SV I IP HVAC ©
Why C?

Embedded systems Which language is suitable for embedded systems?


Why C?
 microcontrollers only accept instructions in ‘machine
ANSI C
Embedded SW
code
Design  Interpretation of machine code by the programmer is
difficult and error prone.
 All software, whether in assembly, C, C++ or Java
must ultimately be translated into machine code in
order to be executed by the CPU
 Embedded processors have limited processor power
and very limited memory available: the language
used must be efficient.

SV I IP HVAC ©
Why C?

Embedded systems Which language is suitable for embedded systems?


Why C?
 To program embedded systems, we need low-level
ANSI C
Embedded SW
access to the hardware
Design  the language must be able at least, to read from and
write to particular memory locations (using ‘pointers’
or an equivalent mechanism).
 reusability of the code is very important. The
language must support the creation of flexible
libraries, making it easy to re-use (well-tested) code
components in a range of projects

SV I IP HVAC ©
Why C?

Embedded systems Which language is suitable for embedded systems?


Why C?
 many embedded systems have a long lifetime.
ANSI C
Embedded SW
During this time, their code will often have to be
Design maintained. Good code must therefore be easy to
understand now, and in five years’ time (and not just
by those who first wrote it)
 the language should be in common use, in order to
be able to find experienced developers, and many
sources of information for trainings and self-trainings

SV I IP HVAC ©
Why C?

Embedded systems Which language is suitable for embedded systems?


Why C?
 there is no perfect solution
ANSI C
Embedded SW
 we need a compromise between safety,
Design
maintainability, portability
 we need a language that is efficient, high-level, gives
low-level access to hardware, and is well defined.
 C is the most commonly considered option

SV I IP HVAC ©
Why C?

Embedded systems Features of the C programming language:


Why C?
 it is ‘mid-level’, with ‘high-level’ features (such as
ANSI C
Embedded SW
support for functions and modules), and ‘low-level’
Design features (such as good access to hardware via
pointers).
 it is very efficient.
 it is popular and well understood.
 even desktop developers who have used only Java
or C++ can soon understand C syntax.
 Good, well-proven compilers are available for every
embedded processor (8-bit to 32-bit or more).

SV I IP HVAC ©
Why C?

Embedded systems Features of the C programming language:


Why C?
 experienced staff are available.
ANSI C
Embedded SW
 books, training courses, code samples and WWW
Design
sites discussing the use of the language are all
widely available.

SV I IP HVAC ©
ANSI C

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions ANSI C
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Introduction

Embedded systems Common C


Why C?
 There was one dominant form of the C
ANSI C
Introduction
language.
Identifiers  This was the native UNIX form, which for
Numbers, Variables historical reasons is known as either Bell Labs
Expressions
C, after the most popular compiler, or K.&R. C,
Program flow
after the authors of the most popular textbook
Arrays & Pointers
Functions
on the language.
Preprocessor  It is now often called "Classic C”
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Introduction

Embedded systems
Why C? ANSI C
ANSI C  The American National Standards Institute
Introduction defined a standard for C, eliminating much
Identifiers uncertainty about the exact syntax of the
Numbers, Variables
language.
Expressions
Program flow
Arrays & Pointers
 ANSI C does incorporate a few
Functions improvements over the old common C. The
Preprocessor main difference is in the grammar of the
Embedded SW language.
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables Lexical convention
Expressions
Program flow
Meaning of Identifiers
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Tokens: there are six types of tokens:


Why C? identifiers
ANSI C
keywords
Introduction
constants
Identifiers
string literals
Numbers, Variables
Expressions
operators
Program flow other separators
Arrays & Pointers blanks, horizontal and vertical tabs, new lines
Functions and comments (collectively named, “white
Preprocessor
spaces”) are ignored, their role is to separate
Embedded SW
Design tokens

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Identifiers:


Why C?
 a sequence of letters and digits
ANSI C
Introduction
 functions, structures, unions and enumeration
Identifiers members of structures or unions, enumeration
Numbers, Variables constants, typedef names and objects
Expressions
Rules:
Program flow
Arrays & Pointers
 The first character must be a letter
Functions  The underscore _ counts as a letter
Preprocessor
 Upper and lower case letter are different
Embedded SW
Design  Identifiers may have any length , and for internal
identifiers, at least the first 31 characters are
significant
SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Keywords: the following identifiers are reserved for


Why C?
used as keywords, and may not be use otherwise:
ANSI C
Introduction
auto double int struct
Identifiers break else long switch
Numbers, Variables
case enum register typedef
Expressions
Program flow
char extern return union
Arrays & Pointers const float short unsigned
Functions
continue for signed void
Preprocessor
Embedded SW default goto sizeof volatile
Design
do if static while
Some implementation also reserved the word asm

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems
Why C? Constants:
ANSI C  integer-constant
Introduction
 character-constant
Identifiers
Numbers, Variables  floating-constant
Expressions  enumeration-constant
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Identifiers:


Why C?
ANSI C functions, structures, unions and enumeration
Introduction members of structures or unions, enumeration
constants, typedef names and objects.
Identifiers
Numbers, Variables
Expressions
Object (variable):
Program flow
Arrays & Pointers a location in storage and its interpretation depends on
Functions two main attributes
Preprocessor
 storage class
Embedded SW
Design  type

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Objects declarations have the following syntax:


Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Storage classes


Why C?
 determines the lifetime of the storage associated
ANSI C
Introduction
with the identified object ("global" or "local" lifetime)
Identifiers
Numbers, Variables
Type:
Expressions
 determines the meaning of the value found in the
Program flow
Arrays & Pointers identified object
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Storage Class


Why C?
 automatic: objects are local to a block and are
ANSI C
Introduction
discarded on exit from the block. Declaration within
Identifiers a block create automatic objects if no storage class
Numbers, Variables specification is mentioned, or if the auto specifier is
Expressions used
Program flow  static: objects may be local to a block or external to
Arrays & Pointers
all blocks, but in either case retain their values
Functions
Preprocessor
across exit from and reentry to functions and blocks
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Storage class specifiers


Why C?
 auto
ANSI C
Introduction  static
Identifiers  register
Numbers, Variables
 extern
Expressions
Program flow  typedef
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems auto:


Why C?
 default storage class
ANSI C
Introduction  local lifetime
Identifiers  visible only in the block in which it is declared
Numbers, Variables
 is not initialized automatically
Expressions
Program flow  must be initialized explicitly
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems static:


Why C?
 global lifetime
ANSI C
Introduction  visible only within the block in which it is declared
Identifiers  all module – global variables must be declared as
Numbers, Variables
static
Expressions
 initialized to 0 by default (however, DO NOT
Program flow
Arrays & Pointers COUNT ON THIS!!!)
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems register:


Why C?
 used for optimizations for heavily used variables
ANSI C
Introduction
 the variable is assigned to a high-speed CPU
Identifiers register (rather than an ordinary memory location), if
Numbers, Variables possible
Expressions
 limitation: you cannot generate pointers to them
Program flow
Arrays & Pointers
using the & operator
Functions  mostly obsolete, modern compilers do an excellent
Preprocessor job without such “hints”
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems extern:


Why C?
 reference to a variable with the same name defined
ANSI C
Introduction
at the external level in any of the source files of the
Identifiers program
Numbers, Variables  the identifier declared has its defining instance
Expressions somewhere else
Program flow
 used to make the external-level variable definition
Arrays & Pointers
Functions
visible within the block
Preprocessor  is visible only in the block in which it is declared
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems extern:


Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Type specifiers:


Why C?
ANSI C
Introduction
void float struct-or-union
Identifiers specifier
Numbers, Variables char double enum specifier
Expressions short signed typedef-name
Program flow int unsigned long
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems Type qualifiers


Why C?
ANSI C
Introduction Syntax:
Identifiers
type-qualifier :
Numbers, Variables
Expressions
const
Program flow volatile
Arrays & Pointers
Functions
Preprocessor
 may be used alone (as the sole declaration-
Embedded SW specifier), or in conjunction with type specifiers
Design
 relevant only when accessing identifiers as l-values
in expressions

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems const:


Why C?
 the object may be initialized, but not thereafter
ANSI C
Introduction
assigned to
Identifiers  announces objects that may be placed in read-only
Numbers, Variables memory, and perhaps to increase opportunities for
Expressions optimization
Program flow
Arrays & Pointers
volatile:
Functions  directs the compiler not to perform certain
Preprocessor optimizations on an object because that object can
Embedded SW have its value altered in ways beyond the control of
Design
the compiler

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems volatile:


Why C?
 useful for controlling access to memory-mapped
ANSI C
Introduction
device registers, as well as for providing reliable
Identifiers access to memory locations used by asynchronous
Numbers, Variables processes
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Identifiers

Embedded systems program:


Why C?  consists of a sequence of functions which mostly
ANSI C
are placed in different modules
Introduction
Identifiers
module:
Numbers, Variables  a group of functions and data . Large program can
Expressions be divided into a collection of separately compiled
Program flow modules. They can be placed in a library for use by
Arrays & Pointers different programs
Functions function:
Preprocessor  consists of a function header and a function block
Embedded SW
Design  The function header contains the function name and
the function parameters.
 The function block can contain a definition part and

©
a statement part
SV I IP HVAC
ANSI C – Identifiers

Embedded systems block structure:


Why C?
 The curly brackets { and } are used for combining
ANSI C
Introduction
definitions and statements to one block.
Identifiers  Definitions and statements are terminated by a “;”.
Numbers, Variables  A single “;” represents a statement
Expressions
 In a function block further blocks can be nested
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions Numbers, Variables, Data Types
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems  Numbers  Data Types


Why C?
 Variables  Data encapsulation with
ANSI C
Introduction
 Memory class modifier struct
Identifiers  External variables  Data encapsulation with
Numbers, Variables
 Scope rules union
Expressions
 Static variables
 Bitfields
Program flow
Arrays & Pointers  Register variables
 Enumerated data types
Functions
 Initialization
 Definition of private types
Preprocessor
Embedded SW
 Type Conversion
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Two’s complement


Why C?
ANSI C
Nonnegative integers from 0 to (2k-1-1) are represented
Introduction
in binary the same way as with sign-magnitude, 0
Identifiers followed by a (k-1) - bit absolute value.
Numbers, Variables Negative integers -(2k-1) to -1 are represented by
Expressions
adding 2k and expressing the result in binary.
Program flow
Arrays & Pointers
Functions 25 = 0 0 0 1 1 0 0 1
Preprocessor
Embedded SW
Design
-25 = 1 1 1 0 0 1 1 1

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Two’s complement


Why C?
Algorithm for Negating a Number:
ANSI C
Introduction
 Complement (flip) each bit.
Identifiers  Add 1
Numbers, Variables
Expressions
Complementing a k-bit number is same as subtracting
Program flow
it from 2k-1.
Arrays & Pointers
Functions 25 : 0 0 0 1 1 0 0 1
Preprocessor
Embedded SW 1’s compl. 1 1 1 0 0 1 1 0
Design

2’s compl. 1 1 1 0 0 1 1 1

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Constants


Why C?
 Text constants
ANSI C
Introduction
 Numerical constants
Identifiers
Numbers, Variables
Expressions
Text constants
Program flow  char Ex: ‘A’, ‘E’, ‘9’, ‘#’
Arrays & Pointers  string Ex: “Siemens”
Functions
Preprocessor
Embedded SW For string constants an array of appropriate length is
Design
reserved and the character ‘\0’ is automatically
added to the end. Thus the string end can be
recognized by the program.
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Text constants


Why C?
Ex:
ANSI C
Introduction ‘S’ ‘i’ ‘e’ ‘m’ ‘e’ ‘n’ ‘s’ ‘\0’
Identifiers
53 69 65 6D 65 6E 73 00
Numbers, Variables
Expressions
Program flow A char doesn’t end with ‘\0’
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Numerical constants


Why C?
Numbers always start with a digit.
ANSI C
Introduction The base is characterized with
Identifiers  0xnnnn hexadecimal number (digits: 0-9, a-f or A-F),
Numbers, Variables
 0nnn octal number (digits: 0-7),
Expressions
Program flow  0bnnnn binary number (digits: 0,1). - this is not ANSI
Arrays & Pointers standard but many compilers accept this.
Functions
Any other number is supposed to be decimal.
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Numerical constants


Why C?
Long integer constants are specified with an ending L,
ANSI C
Introduction e.g. long a = 10L;
Identifiers Unsigned integer constants are specified with an ending
Numbers, Variables
u, e.g. unsigned int c = 3u;
Expressions
Program flow
Floating point values should contain a decimal point,
Arrays & Pointers e.g. float b = 1.;
Functions
and may be written with mantissa and exponent,
Preprocessor
Embedded SW e.g. float c = 0.5e-3;
Design
The suffixes may be omitted. However, this might
sometimes result in an error.

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Symbolic definition of Constants


Why C?
 Symbolic constants are defined with the pre-
ANSI C
Introduction
processor directive #define
Identifiers
Numbers, Variables
Ex: #define MAX 100
Expressions
Program flow #define TEXT “Programming in C”
Arrays & Pointers
Functions
 It is recommended to defined a symbolic constant
Preprocessor
Embedded SW
for each constant value for improved readability
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Symbolic definition vs. const


Why C?
 constants declared with const are stored in ROM -
ANSI C
Introduction
disadvantage
Identifiers  constants declared with const are visible in
Numbers, Variables debuggers - advantage!
Expressions
 symbolic constants do not take up space in ROM,
Program flow
Arrays & Pointers
but are not visible in debuggers. They are
Functions
recommended for embedded systems where ROM
Preprocessor memory is critical.
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Variables


Why C?
Variables are characterized by their:
ANSI C
Introduction
 value
Identifiers  address
Numbers, Variables
 attribute (modifier)
Expressions
Program flow  type
Arrays & Pointers  lifetime
Functions
Preprocessor
Embedded SW Declaration syntax:
Design
[class] [modifier] [type] <name> [, <name1>][,…]

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Variables


Why C?
The modifier can be one of:
ANSI C
Introduction
 volatile
Identifiers  const
Numbers, Variables
Expressions
Program flow Volatile
Arrays & Pointers
volatile <type> <name>
Functions
 must always be read from its original location and is
Preprocessor
Embedded SW not kept in a register at any time
Design
 compiler optimizations are not available, therefore it
must be used only if necessary

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Const


Why C?
const <type> <name>
ANSI C
Introduction
 allows only read access to the variable
Identifiers  may only be initialized once in a program. The
Numbers, Variables
initialization is performed in the startup code
Expressions
 allows the compiler to perform type checking
Program flow
Arrays & Pointers
Functions
Constants may be defined:
Preprocessor
 only once in a program
Embedded SW
Design
 as a macro by the preprocessor
 with the const-keyword as data in memory

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Memory class modifiers


Why C?
 have a different meaning for local and for global
ANSI C
Introduction
objects
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems External variables


Why C?
 recommended use:
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Variable scope


Why C?
 the part of the program within which the variable can
ANSI C
Introduction
be used
Identifiers  For automatic variables declared at the beginning of
Numbers, Variables a function, the scope is the function in which the
Expressions name are declared
Program flow
 Local variables of the same name in different
Arrays & Pointers
Functions
functions are unrelated
Preprocessor  The same is true of the parameters of the function,
Embedded SW which are in effect local variables
Design
 The scope of an external variable or function lasts
from the point at which it is declared to the end of
the file being compiled
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Declaration vs. definition
Why C?
ANSI C
 A declaration announces the properties of a
Introduction variable (primarily its type)
Identifiers  a definition also causes storage to be set aside
Numbers, Variables
Expressions
 There must be only one definition of an external
Program flow
variable among all the files that make up the source
Arrays & Pointers program; other files may contain “extern”
Functions declarations to access it.
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Static variables
Why C?
ANSI C
 the scope of the object is limited to the rest of the
Introduction source file being compiled
Identifiers  function names are global, visible to any part of the
Numbers, Variables
entire program
Expressions
Program flow
 a static function is invisible outside of the file in
Arrays & Pointers which it is declared
Functions  function local variables can also be declared as
Preprocessor static. These are local to the function, but they
Embedded SW
Design
remain in existence after the function terminates its
execution.
 static variables are allocated in the “global” memory
©
space (heap)
SV I IP HVAC
ANSI C – Numbers, Variables, Data Types

Embedded systems
Register variables
Why C?
ANSI C
 makes sense for heavily used variables
Introduction  register variables are to be placed in machine
Identifiers registers, which may result in smaller an faster
Numbers, Variables
programs
Expressions
Program flow
 compiler are free to ignore the advice
Arrays & Pointers  obsolete, compilers are able to optimize the code
Functions without such hints
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Variable initialization
Why C?
ANSI C
 global variables are guaranteed to be initialized to
Introduction zero
Identifiers  automatic and register variables have undefined
Numbers, Variables
initial values
Expressions
Program flow
 for explicitly initialized global variables the initializer
Arrays & Pointers must be a constant expression
Functions  for automatic and register variables, the initializer is
Preprocessor not restricted to being a constant. It may be any
Embedded SW
Design
expression involving previously defined values, even
function calls

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Example 1
Why C?
ANSI C
Before simulation:
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
During simulation time:
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Why C?
Example 2
ANSI C Before simulation:
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
During simulation time:
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data Types
Why C?
ANSI C
Basic types : char, int, float, double
Introduction Type definition is used for:
Identifiers  the definition of the range of values
Numbers, Variables
 the size of memory
Expressions
Program flow  the operations allowed
Arrays & Pointers
 the scaling of pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems Data types:


Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation - struct
Why C?
ANSI C
 encapsulates several data of different types that
Introduction belong to the same object
Identifiers
Numbers, Variables
Expressions
Syntax:
Program flow struct [struct_name]
Arrays & Pointers
{
Functions
Preprocessor
data_type1 ivar_list1;
Embedded SW data_type2 ivar_list2;
Design
...
} [svar_list];
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation - struct
Why C?
ANSI C
 struct_name is the name the structure is given. If
Introduction the structure declaration won’t be referenced in the
Identifiers program again, struct_name may be omitted. This is
Numbers, Variables only true in connection with an immediate data
Expressions definition with svar_list or in connection with the
Program flow
typedef keyword. The structure is then called
Arrays & Pointers
Functions
anonymous
Preprocessor  data_type must be a standard type or a before
Embedded SW declared user type. If the current structure is given a
Design
struct_name, this name is already known. Pointers
to this type of structure might be an element of the
structure itself. This is a basis for linked lists.
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation - struct
Why C?
ANSI C
 ivar_list is a list of the structure elements of the
Introduction same type. This list might consist of one element
Identifiers only
Numbers, Variables  svar_list is the possibility to define variables,
Expressions
arrays, or pointers of type struct struct_name within
Program flow
Arrays & Pointers
the declaration. It is, however, advised to separate
Functions data declaration and data definition. In this manner,
Preprocessor the declaration might be shared
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – struct
Why C?
ANSI C
Introduction  The access to a member of the structure is
Identifiers
performed with the dot operator ”.”
Numbers, Variables
Expressions
 The order of the structure elements bears compiler
Program flow specific consequences.
Arrays & Pointers  Usually, data are aligned to even address
Functions
boundaries.
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – struct
Why C?
ANSI C If there is a structure declaration:
Introduction struct s1
Identifiers
Numbers, Variables {
Expressions unsigned char sid;
Program flow
Arrays & Pointers
unsigned int size;
Functions unsigned char msg;
Preprocessor
Embedded SW
};
Design
the compiler may reserve four, six, or even more
bytes of memory, depending on the alignment

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – struct
Why C?
ANSI C
Introduction  alignment of structure members depends on the
Identifiers
memory alignment of the system
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – struct
Why C?
ANSI C
Introduction  If a structure variable is assigned to another variable
Identifiers
of the same type, member by member will be
Numbers, Variables
copied.
Expressions
Program flow
 Take caution if structure members are pointers
Arrays & Pointers because after the assignment there are two pointers
Functions that point to the identical location!
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Before simulation: During simulation time:
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – union
Why C?
ANSI C
 A union means an overlay of elements of different
Introduction data types to the same memory location.
Identifiers  Syntax:
Numbers, Variables
Expressions
Program flow union [union_name]
Arrays & Pointers {
Functions
Preprocessor
data_type1 ivar_1;
Embedded SW data_type2 ivar_2;
Design
...
} [uvar_list];
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – union
Why C?
ANSI C
 union_name is the name the union is given. If the
Introduction union won’t be referenced in the program again,
Identifiers union_name may be omitted. This is only true in
Numbers, Variables connection with an immediate data definition with
Expressions uvar_list or in connection with the typedef keyword.
Program flow
The union is then called anonymous
Arrays & Pointers
Functions
Preprocessor  data_type must be a standard type or a user type
Embedded SW which was declared before. If the current union is
Design
given a union_name, this name is already known

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – union
Why C?
ANSI C
 ivar is a member element of the union. All member
Introduction elements start at the same base address of the
Identifiers union. The size of the union is determined by the
Numbers, Variables size of its biggest member element
Expressions
Program flow
Arrays & Pointers
 uvar_list is the possibility to define variables, arrays
Functions or pointers of type union union_name within the
Preprocessor declaration. It is, however, advised to separate data
Embedded SW declaration and data definition
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – union
Why C?
ANSI C
Example 1:
Introduction union
Identifiers
{
Numbers, Variables
Expressions unsigned char c[2];
Program flow long l;
Arrays & Pointers
} u1;
Functions
Preprocessor
 The size of u1 is equivalent to the size of long (4
Embedded SW bytes). The lowest byte of u1 may now be accessed
Design
by u1.c[0] as well as by u1.l, as can be seen in the
memory layout

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – union
Why C?
ANSI C
union
Introduction {
Identifiers
unsigned char c[2];
Numbers, Variables
Expressions long l;
Program flow } u1;
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – union
Why C?
ANSI C
struct s2
Introduction {
Identifiers unsigned char sid;
Numbers, Variables
unsigned char size_l;
Expressions
Program flow
unsigned char size_h;
Arrays & Pointers unsigned char msg;
Functions };
Preprocessor
union REQUEST
Embedded SW
Design {
struct s1 message;
struct s2 detailed_message;
SV I IP HVAC © };
ANSI C – Numbers, Variables, Data Types

Embedded systems
Data encapsulation – union
Why C?
ANSI C union REQUEST request;
Introduction unsigned char message_char1, detailed_char1;
Identifiers
Numbers, Variables
Expressions Assigning message_char1 and detailed_char1 to
Program flow
message_char1 = request.message.msg;
Arrays & Pointers
Functions
detailed_char1 = request.detailed_message.msg;
Preprocessor
Embedded SW
Design
leads to different results! Likewise, a direct initialization
as
union REQUEST request =
©
{‘A’,0x1000,“1“}
SV I IP HVAC
ANSI C – Numbers, Variables, Data Types

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Bitfields
Why C?
ANSI C
 offer the possibility to access single bits or groups of
Introduction bits in the not bit addressable memory.
Identifiers  The order of the bits can be defined with the help of
Numbers, Variables
the struct keyword:
Expressions
Program flow
struct [bitfield_name]
Arrays & Pointers {
Functions
data_type1 ivar_1: n_bit_1;
Preprocessor
Embedded SW
data_type2 ivar_2: n_bit_2;
Design
...
} [bitfield_list];

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Bitfields
Why C?
ANSI C
 bitfield_name is the name of the bitfield. It may be
Introduction omitted if the bitfield declaration won’t be referenced
Identifiers in the program again. This is only true in connection
Numbers, Variables with an immediate data definition with bitfield_list or
Expressions in connection with the typedef keyword. The bitfield
Program flow
is then called anonymous
Arrays & Pointers
Functions
 data_type must be a standard type or a before
Preprocessor declared user type. It is recommended to use
Embedded SW
Design
unsigned types only
 ivar is the name of a bit or bitgroup which is
element of the bitfield
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Bitfields
Why C?
ANSI C
 n_bit is the size of the bitfield element ivar in bits.
Introduction Negative values are forbidden, values with more bits
Identifiers than that of the standard word width of the controller
Numbers, Variables might lead to errors. A value of zero means that the
Expressions current bitgroup fills up the remaining bits to the next
Program flow
word (=int) boundary.
Arrays & Pointers
Functions
 bitfield_list is the possibility to define variables
Preprocessor of type struct bitfield_name within the
Embedded SW
Design
declaration. Again, it is advised to separate data
declaration and data definition

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Bitfields
Why C?
ANSI C
 Bitfields are used especially in connection with
Introduction control and status registers of the periphery of
Identifiers microcontrollers
Numbers, Variables  ANSI C does not define anything that has to do with
Expressions
bits. Therefore, using bitfields usually leads to non-
Program flow
Arrays & Pointers
portable code because different compilers might use
Functions
different conventions!
Preprocessor  The ordering of the bits is compiler specific. This
Embedded SW means that some compilers assign the LSBs to the
Design
first bits of the bitfield definition, while others use the
MSBs

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Bitfields - example
Why C?
struct TxIC
ANSI C
{
Introduction
unsigned int glvl: 2;
Identifiers
unsigned int ilvl: 4;
Numbers, Variables
unsigned int ie: 1;
Expressions
unsigned int ir: 1;
Program flow
unsigned int : 0;
Arrays & Pointers
} t7ic;
Functions
t7ic.ilvl = 12;
Preprocessor
Embedded SW The compiler will assign the bits as given below:
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Bitfields - example
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Enumerated data types
Why C?
ANSI C
 Syntax:
Introduction enum [enum_name]
Identifiers
{
Numbers, Variables
Expressions value_1 [= ival]
Program flow [,value_2 [= ival]]
Arrays & Pointers
...
Functions
Preprocessor } [enum_list];
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Enumerated data types
Why C?
ANSI C
 enum_name is the name of the enumerated type. It
Introduction may be omitted if the declaration won’t be
Identifiers referenced in the program again. This is only true in
Numbers, Variables connection with an immediate data definition with
Expressions the enum_list or in connection with the typedef
Program flow
keyword. The enumeration is then called
Arrays & Pointers
Functions
anonymous
Preprocessor
Embedded SW
Design
 value_x is any free choosable name but not a
number

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Enumerated data types
Why C?
ANSI C
 ival is the value that value_x shall be represented
Introduction with. If not specified value_1 will be assigned 0,
Identifiers value_2 = 1, etc.
Numbers, Variables
Expressions
Program flow
 enum_list is the possibility to define variables of
Arrays & Pointers type enum enum_name within the declaration.
Functions Again, it is advised to separate data declaration and
Preprocessor data definition
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Enumerated data types - Remarks
Why C?
ANSI C
 Internally, an enum variable is treated as a signed
Introduction integer
Identifiers  The compiler does not check the variable against
Numbers, Variables
the defined values of the enumeration value list
Expressions
Program flow
 enum variables should only be used in assignment
Arrays & Pointers and comparison operations
Functions  Enumerated values can be used as if they were
Preprocessor defined as a macro, what means that they are
Embedded SW
Design
known at compile time and can thus be used in
switch-case statements

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Enumerated data types - Remarks
Why C?
ANSI C
 Enumeration variables are best suited to represent
Introduction states and transitions of automatons
Identifiers  the size of an enum variable depends on the
Numbers, Variables
platform. However, some compilers offer the
Expressions
possibility to control the size of them
Program flow
Arrays & Pointers Example:
Functions typedef enum
Preprocessor
{
Embedded SW
Design EEP_Read,
EEP_Write
} EEP_tEEPOperation;
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Definition of private types
Why C?
ANSI C
 struct, union, and enum keywords allow both type
Introduction declaration and data definition in one statement
Identifiers  in order to separate declaration and definition, the
Numbers, Variables
typedef keyword can be used
Expressions
Program flow
 syntax:
Arrays & Pointers typedef basic_type type_name;
Functions
where:
Preprocessor
Embedded SW
 typedef “C“-keyword for data structure declaration
Design  basic_type may be any type such as char, int, float,
struct, union, enum, etc
 type_name is any name allowed
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Definition of private types
Why C?
ANSI C
 Useful type definitions:
Introduction typedef unsigned char uint8;
Identifiers
typedef signed char int8;
Numbers, Variables
Expressions typedef unsigned int uint16;
Program flow typedef signed int int16;
Arrays & Pointers
typedef unsigned long uint32;
Functions
Preprocessor typedef signed long int32;
Embedded SW  the above type definitions allow writing platform-
Design
independent code

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Type Conversion
Why C?
ANSI C
 Implicit type conversion
Introduction  Explicit type conversion
Identifiers
Numbers, Variables
Expressions Implicit type conversion
Program flow  when operands of different types are combined in
Arrays & Pointers expressions
Functions
 the conversions are implicitly performed according to
Preprocessor
Embedded SW
standard rules
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Type Conversion
Why C?
ANSI C
Implicit cast
Introduction  all char and short operands are converted to int
Identifiers  if one operand is unsigned, the other operand is
Numbers, Variables
Expressions
converted to unsigned as well
Program flow  all float operand are converted to double
Arrays & Pointers  if the operand of an expression are of different types,
Functions
calculations always occur with the widest type.
Preprocessor
(Width of a data type simply means the number of
Embedded SW
Design bytes a value occupies.
 the result of an expression is always adjusted to the
type of variable the result has.
SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Type Conversion
Why C?
ANSI C
Implicit cast – example
Introduction char v1;
Identifiers
Numbers, Variables
int v2;
Expressions double v3;
Program flow
Arrays & Pointers
Functions
v2 = v1+v3 /*expression is double, result is int*/
Preprocessor v1 = v2 - 2*v1 /* expression is int. The result
Embedded SW variable is of type char. The most significant
Design
part of result is lost */

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Type Conversion
Why C?
ANSI C
Explicit cast
Introduction  to avoid hidden code which might lead to wrong
Identifiers results, every type conversion must be casted
Numbers, Variables
explicitly.
Expressions
Program flow
Arrays & Pointers  explicit cast is expressed by writing the desired data
Functions type in parenthesis as an operator in front of them
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Numbers, Variables, Data Types

Embedded systems
Type Conversion
Why C?
ANSI C
Explicit type conversion
Introduction Example:
Identifiers unsigned int i1;
Numbers, Variables
char c1, c2;
Expressions
c1 = (char)(i1 - (int)c2);
Program flow
Arrays & Pointers
Functions
 it is obvious to the reader that there is a value range
Preprocessor
reduction by casting the expression as char. If it was
missing the compiler would produce a warning only
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions Assignment, Expression, Operators
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Variable assignment
Why C?
ANSI C
 Simple variable assignment
Introduction variable = expression;
Identifiers
variable - defined or declared memory location
Numbers, Variables
Expressions = assignment operator
Program flow expression - constituted from one more operands
Arrays & Pointers and operator
Functions
Preprocessor
; end of statement
Embedded SW  Multiple variable assignment
Design
var_1 = var_2 = [=…] = expression;
Assigns the same value to multiple variables
SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Expressions
Why C?
ANSI C
[unary operator] operand [binary operator][operand][…];
Introduction unary operator: concern a single operand only
Identifiers + positive sign
Numbers, Variables - negative sign
Expressions ++ increment
Program flow -- decrement
Arrays & Pointers & address of
Functions * indirection
Preprocessor
sizeof(name) size of name in byte
Embedded SW
Design (type cast) explicit type casting
! logical negation
~ bit by bit inversion

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Binary operators
Why C?
ANSI C
performs a two operand operation
Introduction
Identifiers
arithmetic operators
Numbers, Variables
+ sum
Expressions
- difference
Program flow
* multiplication
Arrays & Pointers
/ division
Functions
% modulo operation
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Binary operators
Why C?
ANSI C
comparison operators
Introduction
< less than
Identifiers <= less or equal
Numbers, Variables > greater than
Expressions >= greater or equal
Program flow == equivalence
Arrays & Pointers != not equal
Functions &&logical AND
Preprocessor || logical OR
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems Binary operators & 0 1


Why C?
bit-by-bit operations
0 0 0
ANSI C & AND
Introduction | OR 1 0 1
Identifiers ^ XOR (exclusive OR)
Numbers, Variables << shift left
>> shift right | 0 1
Expressions
0 0 1
Program flow compound assignment operators 1 1 1
Arrays & Pointers += -= *= /= %=
Functions <<= >>= &= |= ^=
Preprocessor ^ 0 1
Embedded SW 0 0 1
Design
1 1 0

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Expressions
Why C?
ANSI C
ternary operator: performs a three operand operation
Introduction
Identifiers
?: conditional
Numbers, Variables
Expressions
Program flow operand:
Arrays & Pointers
 constant
Functions
 variable
Preprocessor
 pointer
Embedded SW
Design  return value of a function

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Shift operations
Why C?
ANSI C
Introduction
result = operand << shiftwidth ;
Identifiers
Numbers, Variables
result = operand >> shiftwidth;
Expressions
Program flow  Zeros are shifted in from right when shifting left.
Arrays & Pointers
Functions
 Usually a right shift distinguishes between unsigned
Preprocessor and signed variables. For unsigned values zeros are
Embedded SW shifted in, for signed values the sign (highest bit) is
Design
duplicated (Arithmetic shift). This is, however, not
true for all compilers because ANSI-C does not
define anything that deals with bits.
SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Shift operations
Why C?
ANSI C
 multiplication and divisions can be avoided for
Introduction operands of value 2x, what results in a faster code.
Identifiers
Numbers, Variables
Expressions
Examples:
Program flow 1. z = x * 2; ==> z = x << 1;
Arrays & Pointers 2. z = x / 2; ==> z = x >> 1;
Functions
Preprocessor
Embedded SW  there is no overflow checking mechanism available!
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Shift operations
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Operator’s Hierarchy
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Operator’s Hierarchy
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Operators
Why C?
ANSI C Examples:
Introduction Incrementing before the calculated value is used:
Identifiers x=++n;
Numbers, Variables
Expressions
Incrementing after the calculated value is used:
Program flow x=n++;
Arrays & Pointers
Functions
++n && ++i
Preprocessor
Embedded SW Caution! : if n evaluates to 0, ++I is not executed
Design
any more.

x = ++ (x+y); x = 10++ not allowed


SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Operators
Why C?
ANSI C Examples:
Introduction x = x | MASK; all bits of x which are set in MASK
Identifiers are set
Numbers, Variables
Expressions
Program flow n = ~ n; negation of bits
Arrays & Pointers
Functions
Preprocessor
res = status & (~1); clear the bit 0
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Operators
Why C?
ANSI C
 Increment and decrement operators can be used in
Introduction prefix or postfix notation. They must not be used for
Identifiers expressions.
Numbers, Variables
Expressions
Program flow
 An increment/decrement of pointers is type specific
Arrays & Pointers E.g.:
Functions

Preprocessor
Embedded SW 
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Operators
Why C?
ANSI C
 The order of unary operations is important as this
Introduction may affect the result.
Identifiers E. g.:
Numbers, Variables
Expressions
unsigned char a = 0x7f;
Program flow unsigned int b1, b2;
Arrays & Pointers
b1 = (unsigned int)~a; // b1 = 0x0080;
Functions
Preprocessor
b2 = ~(unsigned int)a; // b2 = 0xff80;
Embedded SW
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Operators
Why C?
ANSI C
 The modulo operation works for integer-by-integer
Introduction divisions only. It returns the integer remainder.
Identifiers  Instead of the conditional operator, an if-...construct
Numbers, Variables
should be used,
Expressions
Program flow e.g
Arrays & Pointers  should be replaced by
Functions

Preprocessor
Embedded SW 
Design

SV I IP HVAC ©
ANSI C – Assignment, Expression, Operators

Embedded systems
Logical expressions
Why C?
ANSI C
 It is rare for logical values to be stored in
Introduction variables
Identifiers
Numbers, Variables
 They are usually generated as required by
Expressions comparing two numeric values
Program flow  they are evaluated from the left to the right
Arrays & Pointers
Functions
 in order to reduce calculation time, put to the
Preprocessor first place the most unlike condition in an AND
Embedded SW
Design
connection (&&) and the most probable
condition in an OR connection (||).

SV I IP HVAC ©
Program Flow Statements

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions Program Flow Statements
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Program Flow Statements

Embedded systems
Sequences
Why C?
ANSI C
 Single Branching: The “if“-Statement
Introduction  Double Branching: The “if-else“-Statement
Identifiers  Multiple Branching: The “switch - case“-Statement
Numbers, Variables
Expressions
 Loop with Testing in the Beginning: The “while“-
Program flow Statement
Arrays & Pointers  Indexed Loop with Testing in the Beginning: The
Functions
“for“-Statement
Preprocessor
Embedded SW
 Loop with Testing in the End: The “do - while“-
Design Statement
 Other Program Flow Statements: continue, break,
goto
SV I IP HVAC ©
Program Flow Statements

Embedded systems Single Branching: The “if“-Statement


Why C?
if ( expression )
ANSI C
Introduction sequence
Identifiers  Only if the boolean expression in parenthesis
Numbers, Variables
evaluates to logical TRUE, the sequence will be
Expressions
executed
Program flow
Arrays & Pointers
 To compare an unsigned int variable with unlike 0
Functions the following syntax should be preferred :
Preprocessor
if (var!=0) or if (var) instead of if (var>0)
Embedded SW
Design

SV I IP HVAC ©
Program Flow Statements

Embedded systems Double Branching: The “if-else“-Statement


Why C?
if ( expression )
ANSI C
Introduction sequence_1
Identifiers else
Numbers, Variables
Expressions
sequence_2
Program flow
Arrays & Pointers  the expression should be formulated so that the most
Functions
probable result is TRUE. Then, most often the branch to
Preprocessor
sequence_2 may not be taken, which results in a
Embedded SW
Design shorter program execution time.

SV I IP HVAC ©
Program Flow Statements

Embedded systems Double Branching: The “if-else“-Statement


Why C?
 encapsulation of several “if - else“ statements can be
ANSI C
Introduction
avoided by using boolean algebra:
Identifiers
Numbers, Variables
if ( expression_1 || ( expression_2 && expression_3) )
Expressions
Program flow
sequence_1
Arrays & Pointers
Functions  Be careful with the ordering of the expressions in
Preprocessor
parenthesis if they contain assignments. In the example
Embedded SW
Design above the expressions 2 and 3 will not be evaluated if
expression 1 is TRUE!

SV I IP HVAC ©
Program Flow Statements

Embedded systems Multiple Branching: The “switch - case“-Statement


Why C?
switch ( expression )
ANSI C
{
Introduction
Identifiers
case const_expression_1: statement_1; break;
Numbers, Variables ...
Expressions case const_expression_n: statement_n; break;
Program flow default: statement_n+1; break;
Arrays & Pointers }
Functions
 expression will be evaluated. The result is of type
Preprocessor
Embedded SW
int or unsigned int
Design

SV I IP HVAC ©
Program Flow Statements

Embedded systems Multiple Branching: The “switch - case“-Statement


Why C?
 const_expression must be a constant value which
ANSI C
Introduction
is known at compile time. If the expression in
Identifiers parenthesis matches the const_expression, the
Numbers, Variables subsequent statements are evaluated up to the next
Expressions break statement rsp. the end of the block.
Program flow
Arrays & Pointers
Functions
 The order of the constant expressions should be
Preprocessor chosen according to the plausibility of their
Embedded SW occurrence for runtime reasons.
Design

SV I IP HVAC ©
Program Flow Statements

Embedded systems Multiple Branching: The “switch - case“-Statement


Why C?
 break “C“-keyword that causes leaving the actual
ANSI C
Introduction
block. Every case should have a break statement.
Identifiers  default is a predefined label for all cases that do not
Numbers, Variables match any of the other constant expressions in the
Expressions
block. In ANSI-“C“ it may be missing, which however
Program flow
means a bad programming style.
Arrays & Pointers
Functions  put the cases in the order according to their
Preprocessor probability because the compiler sometimes
Embedded SW
Design
generates an assembly code which rather
reflects an if … elseif ... else structure,
especially if only few cases are given
SV I IP HVAC ©
Program Flow Statements

Embedded systems The “while“-Statement


Why C?
while ( expression )
ANSI C
Introduction sequence
Identifiers
Numbers, Variables
Expressions
 The condition given by expression is evaluated first.
Program flow
Only if the result is TRUE the sequence is executed.
Arrays & Pointers It will be repeated as long as the expression is
Functions TRUE.
Preprocessor  Potentially endless loops must be equipped with
Embedded SW
Design a software watchdog:
while (*int_ptr <= TopValue && special_exit == 0);

SV I IP HVAC ©
Program Flow Statements

Embedded systems
The “for“-Statement
Why C?
ANSI C
for ( [init_list] ; [expression]; [continue_list] )
Introduction sequence
Identifiers  init_list is a list of statements separated by commas
Numbers, Variables
Expressions
which will be executed unconditionally in advance of
Program flow
the loop.
Arrays & Pointers  expression results in a boolean value TRUE or
Functions FALSE. As long as it is TRUE, the sequence is
Preprocessor executed, followed by the statements of the
Embedded SW
Design
continue_list.
 continue_list is a list of statements separated by
commas which are evaluated as long as the
©
expression is TRUE.
SV I IP HVAC
Program Flow Statements

Embedded systems
The “for“-Statement
Why C?
ANSI C
 The loop control variable must only be changed in
Introduction the continue_list but nowhere else.
Identifiers  Likewise, the loop exit condition must only be
Numbers, Variables
checked in the expression.
Expressions
Program flow
 To compare a decreasing local counter with unlike 0
Arrays & Pointers the following syntax should be used:
Functions for (i=10; i>0; i--) instead of for (i=10; i!=0; i--)
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Program Flow Statements

Embedded systems
The “do - while“-Statement
Why C?
ANSI C
do
Introduction sequence
Identifiers
while ( expression );
Numbers, Variables
Expressions
Program flow  The sequence is executed at least once. After that
Arrays & Pointers the expression is evaluated, and the sequence is
Functions
repeated as long as it’s result is TRUE.
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Program Flow Statements

Embedded systems
Other Program Flow Statements
Why C?
ANSI C
 goto
Introduction  continue
Identifiers  break
Numbers, Variables
Expressions
Program flow  goto must and the other two instructions should be
Arrays & Pointers avoided as they lead to an ill structured program
Functions
flow
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Program Flow Statements

Embedded systems
Other Program Flow Statements
Why C?
ANSI C
 goto causes the program to continue at the label
Introduction which is defined at any other place in the program
Identifiers by a subsequent colon.
Numbers, Variables  continue is used in loop constructs and means a
Expressions
Program flow
shortcut to continue with testing the next loop
Arrays & Pointers condition. Therefore, the statements following
Functions the continue statement won’t be executed.
Preprocessor
Embedded SW
 break statement causes the program to continue
Design at the next label outside the current block. It
should be used in connection with switch - case
constructs but not otherwise.
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions Arrays, Pointers, Functions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems Arrays


Why C?
Pointers
ANSI C
 Pointers scaling
Introduction
 Pointers and Function Arguments
Identifiers
Numbers, Variables  Pointers and Arrays
Expressions  Pointers vs.. Multi-dimensional Arrays
Program flow
Functions
Arrays & Pointers
 Function Header
Functions
 Function Body
Preprocessor
 Calling a function
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Arrays
Why C?
ANSI C
 Encapsulate multiple elements of a single data type
Introduction with one variable name.
Identifiers  May be one or two dimensional
Numbers, Variables
Expressions
 No checking mechanism for the boundaries
Program flow  Index must be of an unsigned type
Arrays & Pointers  Data are contiguously allocated
Functions
Preprocessor
Embedded SW Array Declaration:
Design
<type> <name> [<size>];

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Arrays
Why C?
ANSI C
 type could be any type;
Introduction  size is mandatory: it's the maximal number of
Identifiers elements in the array
Numbers, Variables
Expressions
 The declaration is going to allocate enough bytes for
Program flow the whole array
Arrays & Pointers  Array could be initialized when declaring :
Functions <type> <name> [<optional size>] = { <value list> }
Preprocessor  in this case, the size is optional (if the size is not
Embedded SW
Design given, the size of the array is set to the number of
element in the declaration list)

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Arrays
Why C?
ANSI C Examples :
Introduction int t [4] ;
Identifiers int j [] = {1, 2, 3 } ; /* size 3 */
Numbers, Variables int k [5] = {1,2}; /* other elements are
Expressions initialized to 0 */
Program flow
float t[2][3] = {{2.3, 4.6, 7.2}, {4.9, 5.1, 9.3}};
Arrays & Pointers
Functions
int l [2] = {1, 2, 3 } ; /* Incorrect */
Preprocessor
char vocals[5] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’ };
Embedded SW char string[] = “This is a string”;
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Arrays
Why C?
ANSI C
 The access to an element of the array is done with
Introduction the index between brackets
Identifiers
Example: r = a [i] + b [j];
Numbers, Variables
Expressions
 The first element of the array is 0 (zero-based index)
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers
Why C?
ANSI C
 Are variables that contain the address of an object
Introduction (variable or function).
Identifiers  Enable indirect access to an object.
Numbers, Variables
 Are defined with an asterix (*)
Expressions
Program flow Definition:
Arrays & Pointers type * pointer_name;
Functions
Preprocessor
type is the type of the object the pointer points to.
Embedded SW  * is the patch for a pointer.
Design
 pointer_name is a free choosable name of the
pointer.

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers
Why C?
ANSI C
Introduction
unsigned u16Val;
Identifiers
Numbers, Variables
unsigned *p = &u16Val;
Expressions ….
Program flow
p is 0x0186 (address of
Arrays & Pointers
u16Val)
Functions
Preprocessor *p is 0x55AA; (value
Embedded SW located at address
Design
0x0186, the value of
u16Val)

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers
Why C?
ANSI C
 A pointer can take the value of another pointer, an
Introduction address of an object with & operator, or a pointer
Identifiers expression
Numbers, Variables
char *p ; int *q;
Expressions
Program flow
char a; int b;
Arrays & Pointers p = &a; /*correct*/
Functions
p = &b; /* incorrect */
Preprocessor
Embedded SW
q = &a; /* incorrect */
Design
q= &b ; /* correct */
p = &q; /* address of the pointer */

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers
Why C?
ANSI C
 Const keyword can be used in pointer declarations.
Introduction For example:
Identifiers
int a; int *p;
Numbers, Variables
Expressions int *const ptr = &a; // Constant pointer
Program flow *ptr = 1; // Legal
Arrays & Pointers
Functions
ptr =p; // Error
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers
Why C?
ANSI C
 A pointer to a variable declared as const can only be
Introduction assigned to a pointer that is also declared as const.
Identifiers
Numbers, Variables
Expressions
int a; int *p; const int *q;
Program flow const int *ptr = &a; // Pointer to constant data
Arrays & Pointers *ptr = 1; // Error
Functions
Preprocessor
ptr =p; // Error
Embedded SW ptr =q; // Legal
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers scaling
Why C?
ANSI C
Introduction  The type of the object a pointer points to serves
Identifiers
the compiler as a basis for relative address
Numbers, Variables
calculations using pointer addition, subtraction,
Expressions
Program flow
increment, and decrement.
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers scaling.
Why C?
Example:
ANSI C
Introduction
long *sl_ptr = 0x4000;
Identifiers char *sc_ptr;
Numbers, Variables sc_ptr++ = (char *)(sl_ptr + 2);
Expressions will result in
Program flow tmp = sl_ptr + 2*sizeof(long)
Arrays & Pointers = 0x4000 + 2*4
Functions
= 0x4008 ==> sc_ptr
Preprocessor
sc_ptr++ = 0x4008 + 1*sizeof(char)
Embedded SW
Design = 0x4008 + 1*1
= 0x4009 ==> sc_ptr

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers and Function Arguments
Why C?
ANSI C
 Pointer arguments enable a function to access
Introduction and change objects in the function that called
Identifiers it. For instance, a sorting routine might
Numbers, Variables exchange two out-of-order elements with a
Expressions function called swap:
Program flow
Arrays & Pointers
swap(&a, &b);
Functions  Since the operator & produces the address of a
Preprocessor variable, &a is a pointer to a.
Embedded SW
Design
 the parameters are declared to be pointers, and
the operands are accessed indirectly through
them.
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers and Function Arguments
Why C?
ANSI C
Introduction
void swap(int *px, int *py) /* interchange *px and
Identifiers
*py */
Numbers, Variables
Expressions {
Program flow int temp;
Arrays & Pointers
Functions
temp = *px;
Preprocessor *px = *py;
Embedded SW
Design
*py = temp;
}

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers and Arrays
Why C?
ANSI C
 Any operation which can be achieved by
Introduction array subscripting can also be done with
Identifiers pointers.
Numbers, Variables
 The pointer version will in general be
Expressions
Program flow faster
Arrays & Pointers
The declaration
Functions
Preprocessor int a[10]
Embedded SW
Design
defines an array a of size 10, that is a block of
10 consecutive objects named a[0], a[1], ...,
a[9].
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers and Arrays
Why C?
ANSI C
 The notation a[i] refers to the i-th element
Introduction of the array If pa is a pointer to an integer,
Identifiers declared as
Numbers, Variables
Expressions
int *pa
Program flow then the assignment
Arrays & Pointers
Functions
pa = &a[0];
Preprocessor sets pa to point to element zero of a:
Embedded SW
Design pa contains the address of a[0].
Now the assignment x = *pa will copy the
contents of a[0] into x.
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers and Arrays
Why C?
ANSI C
 If pa points to a particular element of an
Introduction array, then by definition:
Identifiers  pa+1 points to the next element, pa-i
Numbers, Variables
points i elements before pa, and
Expressions
Program flow
 pa+i points i elements after.
Arrays & Pointers Thus, if pa points to a[0],
Functions
Preprocessor
*(pa+1)
Embedded SW refers to the contents of a[1], pa+1 is the
Design
address of a[i], and *(pa+i) is the contents
of a[i].
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers and Arrays
Why C?
ANSI C
 By definition, the value of a variable or
Introduction expression of type array is the address of
Identifiers element zero of the array. Thus after the
Numbers, Variables
assignment
Expressions
Program flow pa = &a[0]
Arrays & Pointers
pa and a have identical values
Functions
Preprocessor
 The assignment pa=&a[0] can also be
Embedded SW written as
Design
pa = a:

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers and Arrays
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers vs. Multi-dimensional Arrays
Why C?
ANSI C
 Given the declarations
Introduction int a[10] [20];
Identifiers
int *b[10];
Numbers, Variables
Expressions then a[3][4] and b[3][4] are both syntactically
Program flow legal references to a single int
Arrays & Pointers
Functions
Preprocessor
 Array a is a true two-dimensional: 200 int-sized
Embedded SW
locations have been set aside, and the
Design calculation 20xrow+col is used to find the
element a[row,col]

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers vs. Multi-dimensional Arrays
Why C?
ANSI C
 For b, however, the definition only allocates 10
Introduction pointers and does not initialize them;
Identifiers initialization must be done explicitly, either
Numbers, Variables syntactically or with code.
Expressions
 advantage of the pointer array is that the rows
Program flow
Arrays & Pointers
of the array may be of different lengths. That is,
Functions each element of b need not point to a twenty-
Preprocessor element vector; some may point to two
Embedded SW elements, some to fifty, and some to none at all.
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers vs. Multi-dimensional Arrays
Why C?
ANSI C
 char array [3][12] = {“The Course\n”,
Introduction “is\n”,
Identifiers
“boring\n”};
Numbers, Variables
Expressions
Program flow array[2] b o r i n g \n \0
Arrays & Pointers array[1] i s \n \0
Functions
array[0] T h e C o u r s e \n \0
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers vs. Multi-dimensional Arrays
Why C?
ANSI C
 char *array[] = {“The Course\n”,
Introduction “is\n”,
Identifiers
“boring\n”};
Numbers, Variables
Expressions
b o r i n g \n \0
Program flow array[2]
Arrays & Pointers
array[1] i s \n \0
Functions
Preprocessor array[0] T h e C o u r s e \n \0
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointer to Strings
Why C?
ANSI C
 C does not know string, only arrays of
Introduction characters.
Identifiers  for the processing of strings, (searching,
Numbers, Variables
comparing, copying), standard routines exist.
Expressions
Program flow
 to be able to use subprograms, pointers to
Arrays & Pointers strings are used when passing parameters. The
Functions whole processing of strings relies on the use of
Preprocessor pointers
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointer to Strings
Why C?
ANSI C
 the incrementing of a pointer on characters
Introduction shifts the pointer to the next valid element of the
Identifiers string.
Numbers, Variables
Expressions
Program flow
char *text, character;
Arrays & Pointers text = “C - training”;
Functions
character = *(text+4);
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointers
Why C?
ANSI C
 only a small selection of operations are defined
Introduction for pointers:
Identifiers
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions
Why C?
ANSI C A function is defined by
Introduction  a header (name, type, formal parameters)
Identifiers
 a body
Numbers, Variables
Expressions A function has
Program flow  a scalar type (char, int, long or pointer) : actual
Arrays & Pointers
function
Functions
Preprocessor
 void type : procedure
Embedded SW
Design
 non void functions have a result
 void functions do not return any result
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions
Why C?
ANSI C
Function Header
Introduction Syntax:
Identifiers
<visibility<type><name>(<parameters list>)
Numbers, Variables
Expressions
Program flow Type
Arrays & Pointers  void for procedure
Functions
 scalar type (default int)
Preprocessor
Embedded SW Visibility
Design
 static modifier used to hide the function

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions - Function Header
Why C?
ANSI C
Parameter list:
Introduction
 could be null, when no parameter is required (or

Identifiers void)
Numbers, Variables  parenthesis are mandatory, even when no
Expressions parameter is required
Program flow  the parameter’s list is a list of data declaration
Arrays & Pointers
 those parameters (the formal parameters) are
Functions
Preprocessor
considered as local variables, only available inside
Embedded SW
the body of the function
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions - Function Header
Why C?
ANSI C
Parameter types:
Introduction
 input parameters (or value parameters) : when

Identifiers calling the function, the caller copy a value in each


Numbers, Variables input parameter. The const keyword could be used
Expressions to declare those parameters as constant (optional)
Program flow
Arrays & Pointers  input-output parameters (or address parameters) :
Functions
when calling the function, the caller give the address
Preprocessor
of a variable to the formal parameter. Those
Embedded SW
Design parameters are marked with the * operator

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions - Function Header
Why C?
ANSI C
Examples of headers :
Introduction  a function f which has an input parameter x and
Identifiers return an integer value
Numbers, Variables int f (const int x);
Expressions
int f (int x);
Program flow
Arrays & Pointers
Functions  a procedure g which has an input parameter x and
Preprocessor an input-output parameter y and return an integer
Embedded SW value.
Design
int f (int x, int *y);

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions - Function Body
Why C?
ANSI C
 Delimited by { and }
Introduction  Allows local declarations
Identifiers  Automatic data – located on the stack
Numbers, Variables  Static data – located in global memory
Expressions
Program flow
 If type is not void, the function includes a return
Arrays & Pointers statement which affects the result
Functions  the return exits the function
Preprocessor
 Input parameters are used as they have been
Embedded SW
Design declared
 Output parameters are used using the *
operator
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions - Calling a function
Why C?
ANSI C
 The call of a function is done using the name of
Introduction the function, and with a list of actual parameters
Identifiers  parenthesis are mandatory, even if no
Numbers, Variables
parameter is required
Expressions
Program flow
 input parameters accept expression of same
Arrays & Pointers type
Functions  input-output parameters require the address of
Preprocessor a variable. The address of a variable is given by
Embedded SW
Design
the operator &

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions - Example
Why C?
ANSI C
Function with input parameter (example):
Introduction int f (int x)
Identifiers {
Numbers, Variables return x+1 ;
Expressions }
Program flow Calling:
Arrays & Pointers int a;
Functions
const b = 14 ;
Preprocessor
int r;
Embedded SW
Design
a=3;
r = f (a) ; /* r is set to 4 */
©
r = f(b+r-1) /* r is set to 18 */
SV I IP HVAC
Arrays, Pointers, Functions

Embedded systems
Functions - Example
Why C?
ANSI C
Function with input-output parameter (example):
Introduction void g (int *y, int x)
Identifiers {
Numbers, Variables
*y = x+1 ;
Expressions
}
Program flow
Arrays & Pointers Calling:
Functions int a; const b = 14 ; int r;
Preprocessor
Embedded SW a=3;
Design
g(&r,a) ; /* r is set to 4 */
g(&r,b+r-1) /* r is set to 18*/
g(r,a) ; /* incorrect, protection fault */
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Functions - Example
Why C?
ANSI C
Function bad example:
Introduction Function with input parameter as an output parameter
Identifiers void g (int y, const int x)
Numbers, Variables {
Expressions y = x+1 ;
Program flow
}
Arrays & Pointers Calling:
Functions int a; const b = 14 ; int r;
Preprocessor r=0;
Embedded SW
Design
a=3;
g(r,a) ; /* r is not affected */
g(&r,a) ; /* compilation error */
SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointer to Functions
Why C?
ANSI C
 The address of a function can be assigned to a
Introduction pointer variable.
Identifiers  a function can also be passed as a parameter.
Numbers, Variables
Expressions
 the call happens with the aid of the dereferencing
Program flow operator “*”.
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Arrays, Pointers, Functions

Embedded systems
Pointer to Functions
Why C?
ANSI C
Introduction type (*name)(); int main()
Identifiers {
Numbers, Variables
void sort(char *v[], int n, int
Expressions
(*comp)()) extern int strcmp(), numcmp();
{
Program flow …

Arrays & Pointers
int comp_res; if(numerical)
Functions
comp_res = (*comp)();
Preprocessor
... sort(lineptr, nlines, numcmp);
Embedded SW
Design
} else
sort(lineptr, nlines, strcmp);
}
SV I IP HVAC ©
Preprocessor directives

Embedded systems
Why C?
ANSI C
Introduction
Identifiers
Numbers, Variables
Expressions Preprocessor directives
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Preprocessor directives

Embedded systems  Macro definition


Why C?
ANSI C
 File inclusion
Introduction  Conditional compilation
Identifiers  Memory model
Numbers, Variables
Expressions
Program flow
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Preprocessor directives

Embedded systems  preprocessing is scheduled before compilation


Why C?
process
ANSI C
Introduction
 It mainly consist in a text analyzing and
Identifiers processing tool. The produced file is used as
Numbers, Variables input for compilation process
Expressions  the goal: flexible software for different
Program flow
application parameters and different software
Arrays & Pointers
development tools
Functions
Preprocessor
 preprocessor directives always start with #
Embedded SW character in the first column line
Design

SV I IP HVAC ©
Preprocessor directives

Embedded systems #define


Why C? introduces the definition of a preprocessor
ANSI C macro
Introduction
#undef
Identifiers
clears a preprocessor macro definition
Numbers, Variables
Expressions #include
Program flow includes the source text of another file
Arrays & Pointers #if
Functions evaluates an expression for conditional
Preprocessor compilation.
Embedded SW
Design
#ifdef
checks for conditional compilation whether a
macro is defined

SV I IP HVAC ©
Preprocessor directives

Embedded systems #ifndef


Why C? checks for conditional compilation whether a
ANSI C macro is not defined
Introduction
#elif
Identifiers
introduces an alternative #if branch following
Numbers, Variables
a not compiled #if, #ifdef, #ifndef or #elif
Expressions
branch.
Program flow
Arrays & Pointers
#else
Functions
introduces an alternative branch following a
Preprocessor
not compiled #if, #ifdef, #ifndef or #elif
Embedded SW branch.
Design
#endif
completes a conditional compilation branch

SV I IP HVAC ©
Preprocessor directives

Embedded systems #line


Why C?
indicates the line number and, optionally, a
ANSI C
file name which is used in error logging files
Introduction
Identifiers
to identify the error position.
Numbers, Variables #error
Expressions reports an error which is determined by the
Program flow user.
Arrays & Pointers
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Preprocessor directives

Embedded systems #pragma


Why C?
ANSI C
Introduction Inserts a compiler control command.
Identifiers
Options for the compilation can be given just as in
Numbers, Variables
the command line.
Expressions
Program flow A #pragma directive not known to the compiler is
Arrays & Pointers ignored and leads to a portable code.
Functions
Preprocessor
Embedded SW
Design

SV I IP HVAC ©
Preprocessor directives

Embedded systems Macro definitions


Why C?
ANSI C
#define Macro_Name [ [(parameters)] replace_text]
Introduction
Identifiers
#define: preprocessor directive
Numbers, Variables
Expressions
Macro_Name: is the name of the macro. Will be
Program flow substituted by replace_text.
Arrays & Pointers parameters: used literally in the replace_text and
Functions
replaced when the macro is expanded
Preprocessor
Embedded SW
replace_text: the given text will replace the macro call
Design literally

SV I IP HVAC ©
Preprocessor directives

Embedded systems It is forbidden to define macro with side effect (eg.


Why C?
increment) - disturbs the error checks consistency.
ANSI C
Introduction
String operator: #
Identifiers  is used in the replace_text to induce that the
Numbers, Variables subsequent string is interpreted as the name of
Expressions
parameter. This name is replaced at the time the
Program flow
macro is expanded.
Arrays & Pointers
Functions Token-pasting operator: ##
Preprocessor  precedes or follows a formal parameter. When it is
Embedded SW
Design
expanded, the parameter is concatenated with the
other text of the token.

SV I IP HVAC ©
Preprocessor directives

Embedded systems
Files inclusion
Why C?
ANSI C
#include <file_name>
Introduction #include ”file_name”
Identifiers
Numbers, Variables
Expressions
Additional information can be used in a source file
Program flow
(data types, function prototypes, ...) => header
Arrays & Pointers files.
Functions “…” - source file path is the first path were the
Preprocessor include file is searched. If it can not be found
Embedded SW there, the project specific include path will be
Design
inspected.
<...> - omits the current source path and start the
search of the include search path of the project.
SV I IP HVAC ©
Preprocessor directives

Embedded systems
Files inclusion
Why C?
ANSI C
 Some problem might arise if a header file defines
Introduction some symbols and is included in multiple modules.
Identifiers The content of a header file must be delimited by a
Numbers, Variables preprocessor switch
Expressions  Solution:
Program flow
Arrays & Pointers #ifndef __HEADER_FILE_H__
Functions #defIne __HEADER_FILE_H__
Preprocessor
……..
Embedded SW
Design header-file content
……..
#endif
SV I IP HVAC ©
Embedded SW Design

 Disciplined SW Development
 Partitioning
 Real Time SW Systems
 Closer Look to a Real Example

SV I IP HVAC ©
Embedded SW Design

Disciplined SW Development

 Biggest mistake: “temptation of the keyboard”


 Use of development processes is important!
 Difference between a “SW Engineer” and a “Coder”:
the SW Engineer is actively responsible for the SW
design phase, according to well defined processes.
 Coding is easy, if it is based on a good design

SV I IP HVAC ©
Embedded SW Design

Disciplined SW Development
 Main target: produce quality SW
 Quality is exactly what the customer says it is
 SW quality is the reason we need processes
 SW maturity can be measured according to CMM
(Capability Maturity Model)

SV I IP HVAC ©
Embedded SW Design

SV I IP HVAC ©

You might also like