Вы находитесь на странице: 1из 54

Programming in C/C++

Chapter 2: Programming in C

Bachelor Course
Summer Term 2017

Prof. Dr. Gregor Schiele n FG Eingebettete Systeme der Informatik n Uni Duisburg-Essen
C in a Nutshell

§ Imperative programming language from the 70s


§ Designed as a small & simple language to design
portable yet efficient (system) software – e.g. UNIX

§ Thin (HW independent) layer on top of assembler


§ Relatively small number of keywords
§ Many functionalities provided by libraries (e.g. IO)
§ Small runtime environment (read: few checks!)

Embedded Systems Group


University of Duisburg-Essen 2
C in a Nutshell

§ Easy to port to new platform / OS


§ Available on most modern platforms

Hosted vs. freestanding implementations:

§ Hosted: full support for standard libraries


(usually available on top of an OS, e.g. Linux)
§ Freestanding: restricted library support
(usually executed directly on HW, e.g. emb. sys.)

Embedded Systems Group


University of Duisburg-Essen 3
C in a Nutshell

§ Simple yet powerful language concepts


§ Easy to learn, hard to master – take your time

§ If used right: can lead to very efficient, yet easy and


clean source code / software
§ If used wrong: can lead to very bad (i.e. incredibly hard
to maintain and even inefficient) source code / software

Embedded Systems Group


University of Duisburg-Essen 4
C in a Nutshell

C didn‘t stop its development in the 70s


§ Many features added in later versions (C89, C99, C11)
§ E.g. support for multithreading, new types, variable
length arrays, in-place declarations, ...

Compilers & IDEs didn‘t stop their development either


§ Many old assumptions / tips no longer valid
§ Manual optimisations often not useful anymore

Embedded Systems Group


University of Duisburg-Essen 5
Main Concepts

§ Structured programming (loops, breaks, ...)


§ Static (weak) typing with basic and composite types
§ Stand-alone functions and function prototypes
§ Pointers (!) and pointer arithmetic
§ Powerful Preprocessor and macros
§ Standard library with optional parts

Embedded Systems Group


University of Duisburg-Essen 6
C Keyword Overview

§ _Alignas § break § float § signed


§ _Alignof § case § for § sizeof

n C11
§ _Atomic § char § goto § static
§ _Bool § const § if § struct
§ _Complex § continue § inline § switch

n C99
§ _Generic § default § int § typedef
§ _Imaginary § do § long § union
§ _Noreturn § double § register § unsigned

n C89
§ _Static_assert § else § restrict § void
§ _Thread_local § enum § return § volatile
§ auto § extern § short § while
Embedded Systems Group
University of Duisburg-Essen 7
Our First Program: Hello World!

hello.c Preprocessor directives to include


function declarations. Definition will
Main function of be taken from libraries
every executable #include <stdio.h>

String variable int main(void) {


definition with char h[] = "Hello world\n";
assignment printf("%s", h);
return 0;
operator
}

Function call to Exit code


print out string 0 interpreted as „no
error“, i.e. successful
execution

Embedded Systems Group


University of Duisburg-Essen 8
Our First Program: Hello World!

hello.c

#include <stdio.h>

int main(void) {
char h[] = "Hello world\n";
printf("%s", h);
return 0;
}

Note:
Since C99 this can be omitted.
Main function will implicitly return status of 0

Embedded Systems Group


University of Duisburg-Essen 9
What Did We Learn So Far?

§ There is a main function


§ C Sytax looks similar to Java
§ There are variables, operators, control structures, functions
§ I/O seems to be handled by library functions
§ There is something like a preprocessor

Embedded Systems Group


University of Duisburg-Essen 10
Variables and Data Types

§ On first glance, pretty similar in C and Java


§ Java borrows most of its syntax for variables / data types from C
§ Thus: if you know Java, then C should look familiar:

A global int x;
variable with
name ‘x’ and
int main(void) {
type integer
float y; A local variable
... with name ‘y’
} and type float

Embedded Systems Group


University of Duisburg-Essen 11
Variables and Data Types

Variables
§ ... must be declared before first use
§ ... are statically typed (static type binding)
§ ... use static name binding
§ ... can have different scopes (visibility) and lifetimes

Supported data types


§ ... predefined basic types (e.g. for integers)
§ ... user defined composite types (e.g. for structs)

Careful: if you look closer, there are lot‘s of differences (àlater)

Embedded Systems Group


University of Duisburg-Essen 12
Operators

Again if you know Java then these should look very familiar
But be careful, again there are some differences

§ Arithmetic: +, -, *, /, %
§ Bit manipulation: &, |, ^, ~, <<, >>
§ Comparison: ==, !=, <, <=, >, >=
§ Logic: !, &&, ||
§ Assignment: =, ++, --, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
§ Conditional: ? :
§ Type size: sizeof(type) returns size of data type in bytes

More operators for pointers, strings and in C++

Embedded Systems Group


University of Duisburg-Essen 13
Control Structures

§ And again Java borrowed much from C à they look similar


break, case, continue, default, do, if, else, for,
goto, return, switch, while

int i;
‘old’ style
for (i=0; i<10; i++) {
/* do something */
}

§ But yet again there are subtle but important differences (àlater)

Embedded Systems Group


University of Duisburg-Essen 14
A Comment on Comments

§ C used to know only multi line comments /* a comment */


§ Since C99 also supports single line comments // a comment
§ Note: you cannot nest comments (!)

/* start of comment
// this works end of
/* this does not work */ comment

*/

§ API doc: there are tools to use comments of style /** API */
like in Java but it‘s not part of the core C language

Embedded Systems Group


University of Duisburg-Essen 15
Building Our First Program

contains implementation
declares printf of printf

C
stdio.h Standard
Library

Prepro- Com-
hello.c hello.o Linker hello.exe
cessor piler

our source object code (native) execut-


code (main) of main able code

Embedded Systems Group


University of Duisburg-Essen 16
Building C Programs In General

header
libraries
files
...

source Prepro- Com- object


code file cessor piler code

executable
...

...

...

...
Linker
code

source Prepro- Com- object


code file cessor piler code

§ source code files compiled separately, then linked into one program
§ dynamic linking (by OS) at runtime is also possible
Embedded Systems Group
University of Duisburg-Essen 17
C Code Files

§ Header files (.h)


◦ Contains types, variables, function declarations, macros
◦ Thus: defines interfaces
◦ Copied (#include) into (several) source code / header files
§ Source Code files (.c)
◦ Contains types, variables, function definitions
◦ One main function in one source code file
◦ Thus: defines implementations
◦ Compiled into object code
§ Libraries
◦ Precompiled implementations, e.g. system libraries, DLLs
Embedded Systems Group
University of Duisburg-Essen 18
Comparison: Java Code Files

§ Source Code files (.java)


◦ Contain both definitions and declarations
◦ Usually one class per file
◦ Compiled into byte code (.class)

§ Libraries (.jar)
◦ Precompiled implementations, e.g. system libraries

No separate header files (!)

Embedded Systems Group


University of Duisburg-Essen 19
Comparison: Building Java Programs

Other classes /
Byte Code / jars

Source Byte Code


javac
Code (.class)

§ Separate class files, no static linking


§ Not executed directly by OS but by VM (java)
§ VM will search for other byte code at run time
§ Compiler needs access to full byte code at compilation time

Embedded Systems Group


University of Duisburg-Essen 20
Building Programs: Java vs. C

Java: everything is a .java file


§ Include other classes with import
§ Byte code of other class(es) is needed at compilation run time
§ At run time, byte code is loaded dynamically
C: usually separate files for declaration and definition
§ Declarations needed at compile time
§ Usually provided in header files (file extension “.h”)
§ Header files (!) included using include
§ Definitions compiled separately (file extension “.c”)
§ Linker uses object code of all files to create single executable
Embedded Systems Group
University of Duisburg-Essen 21
THE C PREPROCESSOR

Embedded Systems Group


University of Duisburg-Essen 22
The Preprocessor

§ Preprocessing occurs before program compiled


◦ Extra program called by the compiler
§ Purpose
◦ Inclusion of external files
◦ Definition of symbolic constants
◦ Macros
◦ Conditional compilation
◦ Conditional execution
§ All directives begin with #
◦ Can only have whitespace before directives
§ Directives not C(++) statements
◦ Do not end with ;

Embedded Systems Group


University of Duisburg-Essen 23
Preprocessor: Inclusion of External Files

§ Puts copy of file in place of directive


§ Two forms
◦ #include <filename>
▪ For standard library header files
▪ Searches predesignated directories
◦ #include "filename"
▪ Normally used for programmer-defined files
▪ Searches in current directory
§ Usage
◦ Loading header files
◦ Programs with multiple source files

Embedded Systems Group


University of Duisburg-Essen 24
Preprocessor: Symbolic Constants (1)

§ Symbolic constants
◦ Constants represented as symbols
◦ When program compiled, all occurrences replaced
§ Format
◦ #define identifier replacement-text
◦ #define PI 3.14159
§ Everything to right of identifier replaces text
◦ #define PI =3.14159
◦ Replaces PI with =3.14159
◦ Probably an error
§ Cannot redefine symbolic constants
Embedded Systems Group
University of Duisburg-Essen 25
Preprocessor: Symbolic Constants (2)

§ Advantages:
◦ Takes no memory

§ Disadvantages:
◦ Name not seen by debugger (only replacement text)
◦ Do not have specific data type

§ const variables preferred

Embedded Systems Group


University of Duisburg-Essen 26
Preprocessor: Macros (1)

§ Operation specified in replacement-text of #define


§ Intended for legacy C programs
§ Macro without arguments
◦ Treated like a symbolic constant
§ Macro with arguments
◦ Arguments substituted for replacement text
◦ Macro expanded
§ Performs a text substitution
◦ No data type checking

Embedded Systems Group


University of Duisburg-Essen 27
Preprocessor: Macros (2)
no whitespace between
Example: identifier and “(“ !
#define CIRCLE_AREA( r ) ( PI * ( r ) * ( r ) )
area = CIRCLE_AREA( 4 );
becomes

area = ( 3.14159 * ( 4 ) * ( 4 ) );

§ Use parentheses (!) – without them:


#define CIRCLE_AREA( r ) PI * r * r
area = CIRCLE_AREA( c + 2 );
becomes evaluates
area = 3.14159 * c + 2 * c + 2; incorrectly

Embedded Systems Group


University of Duisburg-Essen 28
Preprocessor: Macros (3)

§ Multiple arguments:
#define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) )
rectArea = RECTANGLE_AREA( a + 4, b + 7 );
becomes
rectArea = ( ( a + 4 ) * ( b + 7 ) );

§ #undef
◦ Undefines symbolic constant or macro
◦ Can be redefined later

Embedded Systems Group


University of Duisburg-Essen 29
Preprocessor: Conditional Compilation (1)

§ Control preprocessor directives and compilation


◦ Cannot evaluate cast expressions, sizeof, enumeration constants
§ Syntax: #if condition
...
#elif condition
...
#else
...
#endif
§ Condition can
◦ check if another identifier is defined with defined(name)
▪ #if defined(name) can be replaced with #ifdef name
◦ compare the value of an identifier with an integer
◦ be an arithmetic expression (+,-,*,/,&,|,^,<<,>>,!,||,&&)

Embedded Systems Group


University of Duisburg-Essen 30
Preprocessor: Conditional Compilation (2)

§ If condition evaluates to non-zero, part after #if or #elif is included


§ Otherwise next #elif is checked or part after #else is included
§ „…“ can be other preprocessor directives or C(++) code

§ Usage example 1: „Comment out“ code


◦ Cannot nest /* */
◦ Instead, use
#if 0
Please
code commented out
don‘t do
#endif this...
◦ To enable code, change 0 to 1
Embedded Systems Group
University of Duisburg-Essen 31
Preprocessor: Conditional Compilation (3)

§ Usage example 2: Debugging


#define DEBUG 1
#ifdef DEBUG
printf("Variable x = %d\n", x);
#endif

◦ Defining DEBUG enables code


◦ After code corrected
▪ Remove #define statement
▪ Debugging statements are now ignored
◦ Also possible to define DEBUG using a gcc command line switch:
▪ gcc -DDEBUG=1 -o program program.c
▪ No need to change the program, just recompile

Embedded Systems Group


University of Duisburg-Essen 32
Preprocessor: #error and #pragma

§ #error tokens
◦ Prints implementation-dependent message
◦ Tokens are groups of characters separated by spaces
▪ #error 1 - Out of range error has 6 tokens
◦ Compilation may stop (depends on compiler)
§ #pragma tokens
◦ Actions depend on compiler
◦ May use compiler-specific options
◦ Unrecognized #pragmas are ignored

Embedded Systems Group


University of Duisburg-Essen 33
Preprocessor: The # and ## Operators

§ # operator
◦ Replacement text token converted to string with quotes
#define HELLO(x) printf("Hello " #x "!\n");

◦ HELLO(world) becomes
▪ printf("Hello " "world" "!\n");
▪ Same as printf("Hello world!\n");
§ ## operator
◦ Concatenates two tokens
#define TOKENCONCAT( x, y ) x ## y

◦ TOKENCONCAT( O, K ) becomes
▪ OK

Embedded Systems Group


University of Duisburg-Essen 34
Preprocessor: Predefined Symbolic Constants

§ Cannot be used in #define or #undef


§ For more predefined symbolic constants see documentation
(for example http://gcc.gnu.org/onlinedocs/cpp/)

Symbolic Constant Description


__LINE__ The line number of the current source code line (an integer
constant).
__FILE__ The presumed name of the source file (a string).
__DATE__ The date the source file is compiled (a string of the form
"Mmm dd yyyy" such as "Jan 19 2001").
__TIME__ The time the source file is compiled (a string literal of the
form "hh:mm:ss").

Embedded Systems Group


University of Duisburg-Essen 35
DATA TYPES

Embedded Systems Group


University of Duisburg-Essen 36
Data Types

Data types describe variables (and values)

§ which values can be assigned to a variable (range)


§ how values are represented in memory
§ which operations can / should be executed on them

Is 0100000011111111...1 a really large integer value or 1.0?


Is a + b a floating point addition or string concatenation?
Is int x = 1.0; a programming mistake?

Embedded Systems Group


University of Duisburg-Essen 37
Data Types: Integers (1)

Integer types:
§ char
§ short int (or simply: short)
§ int
§ long int (or simply: long)
§ Since C99: long long int (or simply: long long)

Note: char is not a separate type for (Unicode) character data as it


is in Java (we’ll talk about strings later)!

Embedded Systems Group


University of Duisburg-Essen 38
Data Types: Integers (2)

§ By default, integer types are signed


◦ Except char, for which it’s implementation dependent
◦ Keyword unsigned to get unsigned type, e.g. unsigned short

§ Value range of types defined relatively not absolutely!


◦ sizeof(char) ≤ sizeof(short) ≤ sizeof(int)
≤ sizeof(long) ≤ sizeof(long long)
◦ char min. 8bit, short min. 16bit, long min. 32bit,
long long min. 64bit

§ C99 standard defines (optional) fixed size ints, e.g. int8_t,


uint16_t (and more, e.g. least & maximum width types)

Embedded Systems Group


University of Duisburg-Essen 39
Integer Literals

§ Prefix 0 for octal, prefix 0x/0X for hexadecimal


§ Suffix u/U for unsigned, s/S for short, l/L for long, ll/LL for long
long number
◦ Usually not needed since determined by variable type

Examples:
§ -3 : signed integer with base 10
§ 12Us : unsigned short integer
§ 0x12LL : signed long long integer with base 16 (hexadecimal)
§ Since C99 also binary literals

Embedded Systems Group


University of Duisburg-Essen 40
Character Literals

§ '<char>', escaped code (\a \b \f \n \r \t \v \\ \'), octal sequence


\<oct> or hexadecimal \x<hex>
Examples: ‘\n’, ‘b’, ‘\x0A’

§ Pitfall 1: Character constant is of type int, i.e. this is possible:


int i='M’;
§ Pitfall 2: In C++11 single character has type char (important for
overloading)

Embedded Systems Group


University of Duisburg-Essen 41
Pitfall: Comparing Signed / Unsigned

What‘s the output of this code?

unsigned int x = 1;
int y = -1;
if(y < x)
printf("of course it is");
else
printf("strange stuff");

Embedded Systems Group


University of Duisburg-Essen 42
Data Types: Unicode Text

§ „Old“ C: No Unicode support!


◦ Not too much you can do about it
◦ Except using your own code or an external library

§ Since C11: support for Unicode


◦ UTF16: char16_t
◦ UTF32: char_32_t
◦ UTF8 still uses char

Embedded Systems Group


University of Duisburg-Essen 43
Data Types: Floating Point

Floating point types:


§ float (single precision)
§ double (double precision)
§ long double (extended precision)
§ Exact meaning of precision depends on
implementation and platform

§ Note: no unsigned floating point types (why?)

Embedded Systems Group


University of Duisburg-Essen 44
Floating Point Literals

§ Either a „.“ must be included (e.g. 3.14) or „e“ (e.g. 1e3)


Used Suffix Resulting Data Type
none double
f|F float
l|L long double

§ Hexadecimal floating point literals possible but rarely used

Examples:
§ -3.0 : signed double with base 10
§ 17e2f : signed float with base 10 (17.e2f is ok, too)

Embedded Systems Group


University of Duisburg-Essen 45
Data Types: Void

Empty type: void


§ No values and cannot be accessed
§ Used for function declarations without return value and/or without
parameters
§ Will become important for pointers (see later)

Example: #include <stdio.h>

int main(void) {
char h[] = "Hello world\n";
printf("%s", h);
return 0;
}

Embedded Systems Group


University of Duisburg-Essen 46
Data Types: Complex Numbers

§ Since C99: support for complex numbers


◦ New type identifier _Complex
◦ Combined with float, double, long double, e.g. float _Complex
◦ New constant _Complex_I: imaginary unit I (I2 = -1)
◦ Optionally: _Imaginary for imaginary number

§ Naming due to backwards compatibility with old code


◦ In new programs: use complex and I
◦ Defined in header file complex.h along with further macros

Embedded Systems Group


University of Duisburg-Essen 47
Data Types: Complex Numbers

Pitfall 1:
§ C99 defines this as mandatory for hosted implementations but
optional for standalone (embedded chip might not need it)
§ C11 redefines it as optional in both cases
§ Check if macro constant __STDC_NO_COMPLEX__ is defined
à no support for complex.h
§ Further macro constants exist (e.g. _Imaginary supported?)

Pitfall 2:
§ C++ provides completely different (template) class
complex<T> defined in header file “complex” (w/o extension)

Embedded Systems Group


University of Duisburg-Essen 48
Data Types: Booleans

§ „Old“ C: no boolean type!


◦ Integer used instead
◦ Integer value of 0 means false, non-zero means true

§ Since C99: new boolean type


◦ _Bool with values 0 and 1
◦ Again naming due to backwards compatibility with old code
◦ In new programs: use bool with values true and false
◦ Defined in header file stdbool.h

§ Note: C++ has native type bool with values true and false

Embedded Systems Group


University of Duisburg-Essen 49
Data Types: Enumerations

§ Set of integers with identifiers


enum typeName {constant1, constant2=num ...};

§ Constants need unique names (in scope)


◦ enum construct does not establish namespace (!)

§ Constants start at 0 (default), incremented by 1


◦ Explicit values can be set
§ No type safety

Embedded Systems Group


University of Duisburg-Essen 50
Data Types: Enumeration Example

Does this work?

enum apple_t {ELSTAR=2, BOSKOOP=5, GRANNY_S=0};


enum orange_t {VALENCIA, NAVEL, BLOOD};

/* Mixing apples and oranges */


enum orange_t myFavorite = BOSKOOP;
/* Tasty citrus-flavored applesauce!? */
enum orange_t oops = (ELSTAR - BOSKOOP) / NAVEL;
/* Do not use the names at all and out of range */
myFavorite = 5;

Embedded Systems Group


University of Duisburg-Essen 51
Defining New Type Names: typedef

§ Keyword typedef
◦ Makes synonyms (aliases) for previously defined data types
▪ Does not create new type, only an alias
◦ Creates shorter type names
▪ Often used for pointers to certain type or for structs
(see next slides)

§ Example:
◦ typedef int age;
◦ Defines new type name age as synonym for type int

Embedded Systems Group


University of Duisburg-Essen 52
Typedef Example

Does this work?

typedef int age;


age myAge = 32;
int yourAge = 22;
if(myAge > yourAge)
printf("I am older than you");

Embedded Systems Group


University of Duisburg-Essen 53
Data Types (Intermediary) Summary

§ In C, meaning of data types depends on compiler and platform


◦ Size is defined relatively to each other
◦ No guarantee that Java int means the same as C int
§ Java does not have unsigned types
◦ Should we use them? (implicit casts…)
§ Before C99 standard, there was no boolean type
◦ Integer was used instead
§ Before C11 standard, there was no Unicode support
§ C is weakly typed, providing only restricted type safety

Embedded Systems Group


University of Duisburg-Essen 54

Вам также может понравиться