The C languageusers.polytech.unice.fr/~vg/ressources/C.pdf · Presentation V. Granet U.N.S.A. The C...
Transcript of The C languageusers.polytech.unice.fr/~vg/ressources/C.pdf · Presentation V. Granet U.N.S.A. The C...
The C language
Granet Vincent
December 6, 2016
0-0
0-1
Table of contents
1 Bibliography . . . . . . . . . . . . . . 12 Presentation . . . . . . . . . . . . . . . 33 Getting started . . . . . . . . . . . . . 84 Basic types . . . . . . . . . . . . . . . 185 Variable declarations . . . . . . . . . . 316 Expression . . . . . . . . . . . . . . . . 367 Statements . . . . . . . . . . . . . . . 458 The preprocessor (1) . . . . . . . . . . 619 Functions . . . . . . . . . . . . . . . . 6810 Arrays . . . . . . . . . . . . . . . . . . 8411 Structures and Unions . . . . . . . . . 9312 Pointers . . . . . . . . . . . . . . . . . 10513 Input/Output . . . . . . . . . . . . . . 12514 Separate compilation . . . . . . . . . . 13615 The preprocessor (2) . . . . . . . . . . 14416 C library . . . . . . . . . . . . . . . . 15317 Programming environment . . . . . . . 157
Bibliography
V. Granet U.N.S.A. The C language 1
Part 1: Bibliography
References
[1] American National Standard for Information
Systems. Programming Language – C, ANSI
X3.159-1989, 89.
[2] Brian W. Kernighan and Dennis M. Ritchie.
The C Programming Language. Prentice-Hall,
second edition, 1988. (also published in
French, ed. MASSON).
[3] Samuel P. Harbison and Guy L. Steele. C: A
Reference Manual. Prentice-Hall, second
edition, 1987. (also published in French, ed.
MASSON).
[4] P. Drix. Langage C, norme ANSI. Masson,
second edition, 1994. revue et augmente.
[5] J.P. Braquelaire. Mthodologie de la
programmation en langage C. Masson, 1995.
[6] FAQ C. see comp.lang.c and
http://www.eskimo.com/~scs/C-faq/top.html.
V. Granet U.N.S.A. The C language 2
Presentation
V. Granet U.N.S.A. The C language 3
Part 2: Presentation
History
❍ 1972 Dennis RITCHIE – Bell Laboratories
Algol 60
BCPL (1967, M. Richard)
B (1970, K. Thompson)
❍ System writing language
❍ Unix – Portability
❍ Traditional – K&R 1978 (obsolete)
❍ ANSI C: 1983 (X3J11) ⇒ 1989 (X3.159-1989)
⇒ ISO/IEC 9899:1990
V. Granet U.N.S.A. The C language 4
Part 2: Presentation
Main features
❍ Procedural typed language – type
constructors
❍ Separate compilation
❍ Archaic modularity model
❍ No input/output
❍ No dynamic allocation
❍ No concurrency
❍ C standard library
V. Granet U.N.S.A. The C language 5
Part 2: Presentation
Evaluation: advantages
❍ Simplicity
❍ Efficiency
❍ Extensive library
❍ Good portability (PPC 1978, root of most
public implementations)
❍ Also used as assembly language (C++, Eiffel,
Modula 3, ...)
❍ Availability on most systems
V. Granet U.N.S.A. The C language 6
Part 2: Presentation
Evaluation: drawbacks
❍ Two level syntax (preprocessor)
❍ Type checking is too permissive (but lint and
ANSI C)
❍ Use of pointers can be tricky
❍ Programmer must be responsible
❍ Old language concepts
V. Granet U.N.S.A. The C language 7
REFERENCES 7-1
¡
Getting started
V. Granet U.N.S.A. The C language 8
Part 3: Getting started
My first C program
/* Write "Hello , world !" on standard output */
#inc lude <stdio.h>
#inc lude <stdlib.h>
i n t main(void )
{
printf("Hello , world!\n");
return EXIT_SUCCESS;
}
Compilation with Gnu C compiler:
$ gcc -ansi -Wall -o hello hello.c
Execution:
$ hello
Hello world!
$
V. Granet U.N.S.A. The C language 9
Part 3: Getting started
compiler
cpp
hello.c
hello
gcc
gcc -ansi -Wall -o hello hello.c
V. Granet U.N.S.A. The C language 10
Part 3: Getting started
Multi-file program
main.c
extern void say_hello(void );
i n t {} main(void )
{
say_hello();
return EXIT_SUCCESS;
}
hello.c
#inc lude <stdio.h>
void say_hello(void )
{
printf("Hello , world!\n");
}
V. Granet U.N.S.A. The C language 11
Part 3: Getting started
Compiling multi-file program
Compilation:
$ gcc -ansi -Wall -o hello main.c hello.c
or
$ gcc -ansi -Wall -c hello.c
$ gcc -ansi -Wall -c main.c
$ gcc -o hello main.o hello.o
Execution:
$ hello
Hello, world!
$
V. Granet U.N.S.A. The C language 12
Part 3: Getting started
libc
gcc -o hello main.c hello.c
stdio.h
main.c
main.o
cpp
compiler
gcc
hello
cpp
compiler
gcc
hello.o
hello.c
ld (linker)
V. Granet U.N.S.A. The C language 13
Part 3: Getting started
Simplified version of cat
/* Not in C style */
#inc lude <stdio.h>
#inc lude <stdlib.h>
i n t main(void )
{
i n t c;
c = getchar ();
whi le (c != EOF) {
putchar(c);
c = getchar ();
}
return EXIT_SUCCESS;
}
V. Granet U.N.S.A. The C language 14
Part 3: Getting started
/* C style; assignment is an expression ! */
#inc lude <stdio.h>
#inc lude <stdlib.h>
i n t main(void )
{
i n t c;
whi le ((c = getchar ()) != EOF)
putchar (c);
return EXIT_SUCCESS ;
}
V. Granet U.N.S.A. The C language 15
Part 3: Getting started
Characters counting
#inc lude <stdio.h>
#inc lude <stdlib.h>
i n t main(void )
{
long nbchar = 0L;
whi le (getchar () != EOF)
nbchar ++;
printf("I’ve read %ld characters\n",
nbchar );
return EXIT_SUCCESS ;
}
V. Granet U.N.S.A. The C language 16
Part 3: Getting started
#inc lude <stdio.h>
#inc lude <stdlib.h>
i n t main(void )
{
long nbchar;
f o r (nbchar = 0; getchar () != EOF; nbchar +
/* Nothing */;
printf("I’ve read %ld characters\n", nbcha
return EXIT_SUCCESS ;
}
V. Granet U.N.S.A. The C language 17
Basic types
V. Granet U.N.S.A. The C language 18
Part 4: Basic types
C types
❍ void
❍ Scalar types
– Arithmetic types
∗ Integer types
∗ Real types
– Enumerated types
– Pointer types
❍ Function types
❍ Structured types
– Arrays
– Structures
– Unions
V. Granet U.N.S.A. The C language 19
Part 4: Basic types
void type
❍ No object can be of this type
❍ Used to define a function with no result
(procedure)
❍ Also used with pointers
V. Granet U.N.S.A. The C language 20
Part 4: Basic types
Integer types
❍ Signed integer or unsigned integer values
❍ Bit fields
❍ Boolean values (no boolean type in C!)
❍ Characters
V. Granet U.N.S.A. The C language 21
Part 4: Basic types
Signed integers
❍ short [ int ]
❍ int
❍ long [ int ]
❍ long long [ int ]
❍ −2n−1..2n−1 − 1, two’s complement
❍ −(2n−1 − 1)..2n−1 − 1, one’s complement
sizeof(short) 6 sizeof(int) 6 sizeof(long)
Examples:
123 (decimal ) 0173 (octal ) Ox7B (hexadecimal )
123L (long int)
Note: <limits.h> defines several minimums
and maximums for arithmetic types. For example,
#define INT MIN -32767
V. Granet U.N.S.A. The C language 22
Part 4: Basic types
Unsigned integers
❍ unsigned short [ int ]
❍ unsigned int
❍ unsigned long [ int ]
❍ unsigned long long [ int ]
❍ 0..2n − 1
sizeof(unsigned short) 6 sizeof(unsigned) 6 sizeof(unsigned long)
❍ arithmetic is modulo 2n (i.e. max + 1 == 0)
❍ signed + unsigned = unsigned (K&R)
❍ signed + unsigned = signed (K&R)
Examples:
123 (decimal ) 0173 (octal ) Ox7b (hexadecimal )
123u (unsigned int) 123ul (unsigned long)
V. Granet U.N.S.A. The C language 23
Part 4: Basic types
Characters
Character values can be used in integer expressions
❍ [ unsigned ] char
❍ character values are always positive
❍ representation depends on implementation
(signed, unsigned, pseudo-unsigned)
unsigned char c = 255;
i f (c/-1 == 1) printf("signed\n");
e l s e i f (c/-1 == 0) /* K & R*/
printf("unsigned \n");
e l s e i f (c/-1 == -255)
printf("unsigned (ansi) or pseudo -unsign
e l s e fprintf (stderr ,"weird\n");
❍ EOF problem
Examples:
’a’ ’z’ ’\141’ (a-ascii ) ’\077’ (?-ascii )
’\’’ ’\\’
V. Granet U.N.S.A. The C language 24
Part 4: Basic types
’\a’ (audible bell )
’\b’ (backspace ) ’\f’ (form feed )
’\n’ (newline ) ’\r’ (carriage return )
’\t’ (horizontal tab ) ’\v’ (vertical tab )
V. Granet U.N.S.A. The C language 25
Part 4: Basic types
Reals
❍ float
❍ double
❍ long double
sizeof(float) 6 sizeof(double) 6 sizeof(long double)
Examples:
0. .0 2.123 3e1 1.3E-12 2e+23
12.34f 0e-34F 0.0L 98.e-4l
V. Granet U.N.S.A. The C language 26
Part 4: Basic types
Internal representations
❍ Sizes of simple types are not specified by the
language (they depend on the machine)
❍ By definition sizeof(char) == 1
sizeof(char) 6 sizeof(short) 6 sizeof(int) 6 sizeof(long)
8, 16, 32, 32 Sparc Sun (32 bits)
8, 16, 32, 64 PC (64 bits)
sizeof(float) 6 sizeof(double) 6 sizeof(long double)
32, 64, 64 DEC Alpha (32 bits)
32, 64, 128 PC (64 bits)
V. Granet U.N.S.A. The C language 27
Part 4: Basic types
Enumerated types (1/2)
Similar to Pascal enumerated types
enum color {green , red , blue };
Identifiers represent integer constants, and the
compiler automatically binds them to constant in
increasing order (starting from 0 by default)
enum color {green=0, red=1, blue =2};
V. Granet U.N.S.A. The C language 28
Part 4: Basic types
Enumerated types (2/2)
Values for constants of an enumeration may also
be specified by the user:
enum color {green = 20, red = -10, blue};
/* blue == -9 */
enum spaces {
bell=’\a’, bspace=’\b’, newline=’\n’,
creturn=’\r’, tab=’\t’, vtab=’\v’
};
Enumeration values may be equal:
enum color {green=20, red=-10, blue =-10};
V. Granet U.N.S.A. The C language 29
Part 4: Basic types
Enumeration constant identifiers must be different
across several enum types inside a scope
V. Granet U.N.S.A. The C language 30
Variable declarations
V. Granet U.N.S.A. The C language 31
Part 5: Variable declarations
Identifiers
Character set is a superset of ISO 646-1983
(and also trigraph notion)
Syntax
❍ Sequence of letters or digits (first character
must be a letter)
❍ Underscore ” ” is considered as a letter
❍ Case sensitive
Examples:
ident Ident IDENT
foo x1 x123 _1234 foo_foo
MAX __DATE__ (macros )
V. Granet U.N.S.A. The C language 32
Part 5: Variable declarations
Keywords
32 keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const∗ float short unsigned
continue for signed∗ void∗
default goto sizeof volatile∗
do if static while
Note: * ANSI C.
Cannot be used as identifiers
V. Granet U.N.S.A. The C language 33
Part 5: Variable declarations
Variable declarations
/* simple declarations */
i n t x;
char c;
f l o a t foo1 , foo2 , foo3;
/* declarations with initialization */
unsigned in t addr = 0xFFFFu;
double x1, x2 = 123.45;
char c1 = ’a’, c2 = ’b’, c3 = ’c’;
/* constant declarations */
const double PI = 3.14159265;
const max = 100; /* int by default */
/* with user defined types */
enum color {green , red , blue} light = red;
enum {empty , full} state; /* anonymous type */
const declarations declare variables which cannot
be changed. Memory space is allocated!
V. Granet U.N.S.A. The C language 34
Part 5: Variable declarations
Naming types: typedef
❍ typedef is used to give a name to a type
typede f i n t Integer ;
typede f enum {false , true} boolean ;
typede f enum {green , red , blue} color;
Integer i, j, k;
boolean b = true;
color light = blue;
typedef does not define a new type, simply a syn-
onym
V. Granet U.N.S.A. The C language 35
Expression
V. Granet U.N.S.A. The C language 36
Part 6: Expression
❍ Arithmetic operators
Integers Reals
Unary + - + -
Binary + - * / % + - * /
☞ no overflow checking
❍ Relational operators
== !=
> >= < <=
☞ type of operands: arithmetic or pointer
type of result: int (0 or 1)
❍ Logical operators
|| && !
☞ type of operands: all scalar types
type of result: int (0 or 1)
☞ the second operand is not evaluated, if the
result can be deduced from the first
operand
V. Granet U.N.S.A. The C language 37
Part 6: Expression
❍ Bitwise operators
~ | ^ &
☞ type of operands: int
❍ Shift operators
<< >>
☞ left shift is 0-filled
☞ right shift fills by 0 if its first operand is
unsigned, otherwise fills (maybe) by copy
of sign bit
❍ Conditional operator
☞ the only ternary operator of the language
condition ? expr1 : expr2
min = a < b ? a : b;
V. Granet U.N.S.A. The C language 38
Part 6: Expression
❍ Assignment operators
– Simple assignment
=
operand types: arithmetic, pointer,
struct or union
☞ result type: (non converted) left
operand type
– Compound assignment
a op= b ⇔ a = a op b (a is only
evaluated once)
+= -= *= /= %=
&= ^= |=
<<= >>=
– Incrementation - decrementation (by 1)
x++ x-- (postfixed)
☞ result is value of x before
incrementation (or decrementation)
++x --x (prefixed)
☞ result is value of x after incrementation
(or decrementation)
V. Granet U.N.S.A. The C language 39
Part 6: Expression
❍ sizeof operator
sizeof expr or sizeof(type)
int a;
printf("%d %d\n",sizeof a, sizeof(int));
☞ expr is not evaluated, and object size must
be computed at compile time
❍ Comma operator
expr1 , expr2 , ... exprn
☞ result is the value of the last expression
(i.e. exprn)
– used when several expressions must be
evaluated in some place where only one is
permitted
f o r (i=0, j=MAX ; i<j ; i++, j--) {
/* .... */
}
V. Granet U.N.S.A. The C language 40
Part 6: Expression
Precedence and order of evaluation
16 () function call
16 [] indexation
16 . field selection
16 -> indirect field selection
15 ++ -- postfixed incr/decr
14 ++ -- prefixed incr/decr
14 sizeof size
14 (type) casting
14 ~ bitwise negation
14 ! negation
14 - opposite
14 & address of
14 * indirection
13 L * / % multiplicative operators
12 L + - additive operators
11 L << >> shifts operators
10 L < <= > >= relational operators
9 L == != equality operators
8 L & bitwise and
7 L ^ bitwise exclusive or
6 L | bitwise or
5 L && and
4 L || or
3 R ?: conditional
2 R = += -= *= /= %= assignments
2 R <<= >>= &= ^= |=
1 L , comma
V. Granet U.N.S.A. The C language 41
Part 6: Expression
Implicit type conversions (1/2)
Applied when operand types of an expression are
different.
Rules are rather complex!
❍ Unary conversionsinteger types shorter than int ⇒ int
signed integer types same size as int ⇒ int
unsigned integer types same size as int ⇒ int
float ⇒ double (K&R)
❍ Binary conversions1 if operands are not arithmetic
or same types ⇒ no conversion
2 if one op long double ⇒ long double
3 if one op double ⇒ double
4 if one op float ⇒ float
5 if one op unsigned long ⇒ unsigned long
6 if one op long ⇒ long
7 if one op unsigned int ⇒ unsigned int
8 else operand types are int ⇒ no conversion
V. Granet U.N.S.A. The C language 42
Part 6: Expression
Implicit type conversions (2/2)
❍ Assignment conversions
type of left and right parts are identical ⇒no conversion
left part right part
all arithmetic types all arithmetic types
all pointer types integer constant 0
all pointer types void *
pointer to T array T
pointer to function function
❍ Function parameter conversions
Unary conversions are applied
float ⇒ double
V. Granet U.N.S.A. The C language 43
Part 6: Expression
Explicit conversions (cast)
(T) expression
to convert the result of expression into a value of
type T
( i n t ) 2.0 /* convert 2.0 to int (i.e. 2) */
3 / ( f l o a t ) 4 /* = 0.75 whereas 3/4 = 0 */
no explicit conversion to struct or union
integer ⇒ integer
real ⇒ integer
pointer ⇒ integer
real ⇒ real
integer ⇒ real
pointer ⇒ pointer
integer ⇒ pointer (0 and void *)
array ⇒ pointer (implicit)
function ⇒ pointer (implicit)
any type ⇒ void (but unusable)
V. Granet U.N.S.A. The C language 44
Statements
V. Granet U.N.S.A. The C language 45
Part 7: Statements
Elementary statement
expression;
; is an instruction terminator
to define an empty statement just put a ;
whi le ((c = getchar ()) != SPACE)
/* do nothing */ ;
V. Granet U.N.S.A. The C language 46
Part 7: Statements
Compound statement
{[ list of declarations ]
[ list of statements ]
}
- to group several statements
whi le (a<b) {
a++; b--;
}
- to define local variables
i f (x>0) {
f l o a t a,b;
a=x; /* .... */
}
- to delimit a function body
V. Granet U.N.S.A. The C language 47
Part 7: Statements
i n t main(void )
{ /* ....} */
V. Granet U.N.S.A. The C language 48
Part 7: Statements
If statement (1/2)
☞ i f (logical_expression )
instruction
i f (logical_expression )
instruction
e l s e
instruction
☞☞ use a compound statement if several
statements are needed in a branch
☞ logical expression is an integer expression
which value is:
0 ⇔ false
not 0 ⇔ true
V. Granet U.N.S.A. The C language 49
Part 7: Statements
If statement (2/2)
i f (x == 0) y = 0;
i f (x > y) max = x; e l s e max = y;
i f (isdigit(c)) {
printf("c is a digit\n");
n = c - ’0’;
}
i f (x == 1)
i f (y == 1)
printf("x and y are equal to one\n");
e l s e
a = b = 0;
i f (x == 1) {
i f (y == 1)
printf("x and y are equal to one\n");
} e l s e
a = b = 0;
V. Granet U.N.S.A. The C language 50
Part 7: Statements
Switch statement (1/2)
☞ switch (integer_expression ) {
case value1: [ instructions 1 ]
case value2: [ instructions 2 ]
...
case valuen: [ instructions n ]
[ de f au l t : [ instructions n+1 ] ]
}
❍ the switch expression value is an integer or
enum
❍ case label values are constant expressions
compatible with the switch expression
❍ switch exit with break (or return, goto, ...)
instruction.
V. Granet U.N.S.A. The C language 51
Part 7: Statements
Switch statement (2/2)
i n t c;
switch (c) {
case ’_’: printf("For C, ’_’ is a ");
case ’a’:
case ’A’:
.
.
.
case ’z’:
case ’Z’: printf("letter\n");
break ;
case ’ ’:
case ’\n’:
case ’\t’: printf("space\n");
break ;
de f au l t : printf("other character \n");
}
V. Granet U.N.S.A. The C language 52
Part 7: Statements
Loops (1/2)
whi le (logical_expression )
instruction
do instruction
whi le (logical_expression );
f o r (initialization ; condition ; increment)
instruction ;
The For loop is strictly equivalent to:
initialization ;
whi le (condition) {
instruction ;
increment;
}
V. Granet U.N.S.A. The C language 53
Part 7: Statements
Loops (2/2)
i = 1;
whi le (i < MAX) {
n *= i;
i++;
}
i = 1; j = MAX;
do {
i++; j--;
} whi le (i < j);
f o r (i = 1; i < MAX; i++)
n *= i;
V. Granet U.N.S.A. The C language 54
Part 7: Statements
f o r ( ; ; )
/* infinite loop */;
V. Granet U.N.S.A. The C language 55
Part 7: Statements
Break statement
❍ Used to exit from a switch or a loop
statement
whi le (1) {
/* ... */
i f (exception) break ;
/* ... */
}
f o r (i = 0; i < MAX; i++)
i f (t[i] == item) break ;
V. Granet U.N.S.A. The C language 56
Part 7: Statements
f o r (i = 0; i < MAX; i++)
switch (t[i]) {
case 0: /* .... */;
case 1: break ; /* probably wrong */
/* .... */
}
V. Granet U.N.S.A. The C language 57
Part 7: Statements
Continue statement
❍ Used in loops
❍ Go to the next iteration
❍ In for loop, incrementation part is done first
❍ In while and do loops, test part is executed
immediatly
f o r (i = 0; i < MAX; i++) {
i f (t[i] < 0) cont inue ;
/* ... */
}
V. Granet U.N.S.A. The C language 58
Part 7: Statements
whi le (i++ < MAX) {
switch (t[i]) {
case 0: /* .... */;
case 1: cont inue ;
/* .... */
}
/* .... */
}
V. Granet U.N.S.A. The C language 59
Part 7: Statements
Goto statement
❍ To avoid
❍ But exceptions
{
/* ... */
i f (exception)
goto Error;
/* ... */
/* ... */
Error: /* ... */;
}
V. Granet U.N.S.A. The C language 60
The preprocessor (1)
V. Granet U.N.S.A. The C language 61
Part 8: The preprocessor (1)
❍ Called before the compiler proper
❍ Directives start with a sharp
#command-name [ arguments ]
❍ Main functions:
– macro definitions and replacement
(#define)
– file inclusion (#include)
– conditional compilation (#if, #ifdef,
#ifndef)
❍ To write a multi-line directive use a backslash
(\)
❍ E option of gcc to stop after the
preprocessing stage
V. Granet U.N.S.A. The C language 62
Part 8: The preprocessor (1)
Simple macro definition
❍ To define constants
❍ #define identifier character sequence
#de f i n e FALSE 0
#de f i n e EOF (-1)
#de f i n e PI 3.141592653
#de f i n e SIZE 1024
#de f i n e SIZE2 (2 * SIZE)
#de f i n e begin {
#de f i n e end ;}
#de f i n e then
#de f i n e procedure void
❍ One may forget a macro definition
#undef SIZE
#undef then
V. Granet U.N.S.A. The C language 63
Part 8: The preprocessor (1)
Simple macro replacement
❍ replacement is only textual
i n t buf[SIZE], big_buf [SIZE2];
procedure foo(void )
begin
i f (x < SIZE) then begin
x++; z++
end
end
After pre-processing:
i n t buf [1024] , big_buf [(2 * 1024)];
void foo(void )
{
i f (x < 1024) {
x++; z++
;}
;}
V. Granet U.N.S.A. The C language 64
Part 8: The preprocessor (1)
Definition in compilation command line
❍ D compiler option provides a way to define
macros without modifying the source file
% gcc -ansi -DMAXSIZE=100 -DDEBUG file.c
V. Granet U.N.S.A. The C language 65
Part 8: The preprocessor (1)
Predefined macros
DATE current compilation date of source file
TIME current compilation time of source file
FILE current source file name
LINE current source file line number
STDC must be defined in ANSI C
❍ These macros cannot be redefined or
undefined
V. Granet U.N.S.A. The C language 66
Part 8: The preprocessor (1)
Inclusion of source files
❍ Two notations
#include "filename"
#include <filename>
❍ The first one researches the file in the current
directory, and in case of failure, in the
standard directories
❍ The second form researches only in the
standard directories
#inc lude "mine.h"
#inc lude "../../ stack.h"
#inc lude <stdio.h>
#inc lude <sys/stat.h>
#inc lude "stdio.h"
☞ an included file may itself contain inclusion
directives
V. Granet U.N.S.A. The C language 67
Functions
V. Granet U.N.S.A. The C language 68
Part 9: Functions
Function definition (1/3)
❍ Traditional form (K&R)
[result_type] fname([arg_list])
[arg_types]
{[local declarations]
[instructions]
}
i n t max(a, b)
i n t a,b;
{
return a > b ? a : b;
}
❍ This form is now obsolete
V. Granet U.N.S.A. The C language 69
Part 9: Functions
Function definition (2/3)
❍ ANSI C form
result_type fname(arg_decl_list)
{[local declarations]
[instructions]
}
i n t max( i n t a, i n t b)
{
return a > b ? a : b;
}
❍ No embedded functions
a function without argument is declared f() in
K&R style, and f(void) in ansi style.
V. Granet U.N.S.A. The C language 70
Part 9: Functions
Function definition (3/3)
❍ Result type
– void
– any scalar type: integer, real, pointer,
enumeration
– structure and union
– but no array (only address)
– default result type is int (K&R)
❍ Argument types
– any scalar type: integer, real, pointer,
enumeration
– structure and union
– array
the size may not be specified
int strlen(char s[MAX])
int strlen(char s[])
– types of formal and effective arguments
must be compatible
V. Granet U.N.S.A. The C language 71
Part 9: Functions
Argument passing
❍ Only one transmission mode: by value
void f( i n t x)
{
x++;
printf("In function f: %d\n", x);
}
i n t main(void )
{
i n t a = 1;
f(a);
printf("After call to f: %d\n", a);
return EXIT_SUCCESS ;
}
In function f: 2
After call to f: 1
V. Granet U.N.S.A. The C language 72
Part 9: Functions
❍ Evaluation order of arguments is not
guaranteed
V. Granet U.N.S.A. The C language 73
Part 9: Functions
Argument matching
❍ Formal arguments: implicit unary conversion
(if needed)
❍ (K&R): no checks on effective arguments
(number and type)
❍ ANSI C: the number and type of effective
arguments are checked
V. Granet U.N.S.A. The C language 74
Part 9: Functions
void f(a,b) /* K&R form */
i n t a; double b;
{ }
void g( i n t a, double b) /* ANSI form */
{ }
i n t main(void )
{
f(1); /* no compilation error */
f(1,2,4,5); /* no compilation error */
f("abc", "zzz"); /* no compilation error */
f(1.5 ,2); /* potential problem */
f(1,2); /* potential problem */
g(1); /* compilation error */
g(1,2,4,5); /* compilation error */
g("abc", "zzz"); /* compilation error */
g(1.5 ,2); /* 1.5 is converted into int */
g(1,2); /* 2 is converted into double */
}
V. Granet U.N.S.A. The C language 75
Part 9: Functions
Returning from a function
Return statement: return [expr];
❍ return statement may appear anywhere in
the function body
❍ if function result type is void, expr is omitted
❍ if function result type is void, and there is no
return statement, a default return is
implicitly set at the end of the function body
❍ if function result type is T, expr must exist
and be of (converted, if possible) T type
i n t f(void )
{
return 12.6;
/* that is return (int) 12.6 (i.e. 12) */
}
V. Granet U.N.S.A. The C language 76
Part 9: Functions
Variables (1/4)
❍ Global variable
Definition: outside any block
Lifetime: static = the whole program
execution
Scope: from the declaration place to the
end of the file (unless masked)
❍ Local variable
Definition: inside a block (variables
declared in main function are local)
Lifetime: automatic = execution time of
the block
Scope: the block and any nested blocks
(unless masked)
V. Granet U.N.S.A. The C language 77
Part 9: Functions
Variables (2/4)
i n t a;
void f(void ) {
i n t b;
x++; /* x is unknown */
a++; /* incrementing global variable */
b++; /* incrementing local variable */
}
i n t x;
i n t main(void ) {
i n t a; /* mask global variable */
x++; /* incrementing global variable */
a++; /* incrementing local variable */
return EXIT_SUCCESS ;
}
V. Granet U.N.S.A. The C language 78
Part 9: Functions
Variables (3/4)
❍ Static variable
Definition: inside a block, prefixed by
static
Lifetime: the whole program execution
Scope: the block and any nested blocks
(unless masked)
❍ Register variable
Definition: inside a block (argument or
variable), prefixed by register
Lifetime: execution time of the block
Scope: the block and any nested blocks
(unless masked)
Note: set in register if possible (only
scalar values)
V. Granet U.N.S.A. The C language 79
Part 9: Functions
Variables (4/4)
i n t f(void )
{
r e g i s t e r i n t c;
s t a t i c i n t x = 0;
whi le ((c = getchar ()) != EOF)
putchar (c);
return x++;
}
i n t main(void )
{
printf("%d %d\n", f(), f());
/* ⇒ 1 0 */
return EXIT_SUCCESS ;
}
V. Granet U.N.S.A. The C language 80
Part 9: Functions
Function declarations
❍ Function declaration = to give its prototype
(i.e. its header)
Useful if one calls
- a function defined later in the same source
file
- a function defined in another source file
❍ Two forms:
K&R: type fname();
ex: double cos();
ANSI C: type fname(arg type list);
ex: double cos(double);
❍ If neither the definition nor the declaration of
the function are available, the compiler
performs an implicit declaration assuming int
as return type and no arguments checking
V. Granet U.N.S.A. The C language 81
Part 9: Functions
Variable number of arguments (1/2)
❍ List of arguments denoted by ... after the
last named argument (one at least)
❍ A set of macros
#include <stdarg.h>
va start(va list ap, last named parameter)
va arg(va list ap, type)
va end(va list ap)
/* va_list ap represents the current argument*/
V. Granet U.N.S.A. The C language 82
Part 9: Functions
Variable number of arguments (2/2)
#inc lude <stdarg.h>
i n t max( i n t first , ...)
/* return the maximum of positive integers;
the list ending up with -1
*/
{
i n t maxi = 0;
va_list ap; /* current argument */
va_start (ap , first);
whi le (first != -1) {
i f (first > maxi) maxi = first;
first = va_arg(ap , i n t );
}
va_end(ap);
return maxi;
}
i n t main(void ) {
x = max(2, 56, 67, 1, 16, -1);
x = max(12, 14, 4, -1, 20 , 30, -1);
}
V. Granet U.N.S.A. The C language 83
Arrays
V. Granet U.N.S.A. The C language 84
Part 10: Arrays
Characteristics
❍ Only one dimension
❍ Multi-dimensional arrays are represented by
arrays of arrays
❍ Integer index only
❍ Low bound is always 0
❍ Index within the bounds of array’s index
range IS NOT checked at running time!
❍ Can be initialized with aggregates
❍ C compiler must be able to calculate
statically the size of the array
V. Granet U.N.S.A. The C language 85
Part 10: Arrays
i n t t[10]; /* t[0] t[1] ... t[9] */
f l o a t m[3][8];
/* m[0][0] m[0][1] ... m[0][7]
m[1][0] m[1][1] ... m[1][7]
m[2][0] m[2][1] ... m[2][7]
*/
V. Granet U.N.S.A. The C language 86
Part 10: Arrays
Initialization
char t[4] = { ’A’, ’B’, ’C’, ’D’ };
f l o a t m[2][3] = { { 0.0, 0.1, 0.2 },
{ 1.0, 1.1, 1.2 }};
❍ Missing elements are initialized to 0
char t[4] = {’A’, ’B’}; /* t[2]==t[3]==’\0’ */
f l o a t m[2][3] = { { 0.0 },
{ 1.0, 1.1, 1.2 }};
/* m[0][1] == m[0][2] == 0.0 */
❍ First dimension can be omitted, size of array
is automatically calculated by the compiler
V. Granet U.N.S.A. The C language 87
Part 10: Arrays
char t[] = { ’A’, ’B’, ’C’, ’D’ };
i n t m[][3] = { { 0, 1, 2 },
{ 3, 4 }
{ 5 } };
/* m = ‘\tmpmat {}‘ */
V. Granet U.N.S.A. The C language 88
Part 10: Arrays
String (1/3)
❍ Array of char
❍ String litteral constants are in double quotes
❍ Ends with a nul character (’\0’)
sizeof "abc" == 4
❍ It is not a type by itself
char s1 [10] = {’1’,’2’,’3’,’4’,’\0’};
char s2 [10] = "1234";
"I’m a string"
"" /* an empty string */
"\t \" Hello World \"\n"
"a multi -line ...\
string !!!"
V. Granet U.N.S.A. The C language 89
Part 10: Arrays
String (2/3)
❍ C compiler automatically sets ’\0’ at the
end of litteral string constant
❍ Don’t forget to set it when defining string
from array of characters
❍ No predefined operators on strings
❍ Standard library provides a lot of string
functions (concatenation, copy, ...) ;
string.h
❍ These string functions do not manage
memory space allocation (except strdup)
V. Granet U.N.S.A. The C language 90
Part 10: Arrays
String (3/3)
i n t strlen( char s[])
/* calculate the length of the string s */
{
i n t i = 0;
whi le (s[i] != ’\0’)
i++;
return i;
}
V. Granet U.N.S.A. The C language 91
Part 10: Arrays
void strcpy( char s1[], char s2[])
/*
copy the string pointed to by s2
to the string pointed to by s1
*/
{
i n t i = 0;
whi le ((s1[i] = s2[i]) != ’\0’)
i++;
}
V. Granet U.N.S.A. The C language 92
Structures and Unions
V. Granet U.N.S.A. The C language 93
Part 11: Structures and Unions
Structures (1/3)
❍ Collection of objects, which may be of
different types
❍ Called records in Pascal
s t r u c t complexe {
double real , imag;
};
s t r u c t complexe x, y;
s t r u c t {
/* anonymous type */
i n t day , month , year;
char month_name [10];
} d;
typede f s t r u c t {
double real , imag;
} complexe ;
V. Granet U.N.S.A. The C language 94
Part 11: Structures and Unions
Structures (2/3)
❍ Variables of struct type can be initialized
with aggregates
– K&R: only static variables
– ANSI: static and automatic variables
V. Granet U.N.S.A. The C language 95
Part 11: Structures and Unions
s t r u c t complexe {
double real , imag;
} x = { 1.4, 3.5 };
s t r u c t {
/* anonymous type */
i n t day , month , year;
char month_name [10];
} d = { 2, 3, 1997, "March" } ;
s t r u c t S1 {
i n t x;
s t r u c t { double d; char c; } y;
i n t z[5];
};
s t r u c t S1 x = { 1, { 10.9 } };
/*
same as struct S1 x =
{ 1, { 10.9, ’\0’},
{ 0, 0, 0, 0, 0 } };
*/
V. Granet U.N.S.A. The C language 96
Part 11: Structures and Unions
Structures (3/3)
❍ Field access: member operator “.”
s t r u c t complexe x;
x.real = 12.5; x.imag = 0.5;
i n t leap( s t r u c t date d)
{
return d.year % 4 == 0 && d.year % 100 != 0
|| d.year % 400 == 0;
}
s t r u c t person {
char name[NAMESIZE ];
long i n t n_insee;
s t r u c t date birthdate;
} p;
strcpy(p.name ,"John");
p.birthdate.year = 1986;
V. Granet U.N.S.A. The C language 97
Part 11: Structures and Unions
Bit fields
❍ Bit fields can be used to access memory word
at bit level
❍ Fields have to be unsigned integer values
within a machine word
���������������
���������������
segments page offset
31 29 23 15 0
Virtual address on XBQ-43
s t r u c t virtual \_address {
unsigned offset : 16;
unsigned page : 8;
unsigned segment : 6;
unsigned : 1; /* unused */
unsigned supervisor : 1;
};
❍ Portabililty problem
❍ & operator cannot be applied to bit fields
V. Granet U.N.S.A. The C language 98
Part 11: Structures and Unions
Unions (1/4)
❍ Unions provide type union
❍ Variants in Pascal records
union StringInt {
char string[MAXSIZE ];
i n t i;
};
union StringInt x, y;
But also
V. Granet U.N.S.A. The C language 99
Part 11: Structures and Unions
union StringInt {
char string[MAXSIZE ];
i n t i;
} x, y;
union {
/* anonymous type */
char string[MAXSIZE ];
i n t i;
} x, y;
V. Granet U.N.S.A. The C language 100
Part 11: Structures and Unions
Unions (2/4)
❍ Static variables of union type can be
initialized with aggregates in ANSI C
❍ Only the first member is initialized
enum sexe { m, f };
s t a t i c union {
s t r u c t { enum sexe kind; i n t shape; } X;
s t r u c t { enum sexe kind; double shape; } Y;
} U = { f, 100 };
V. Granet U.N.S.A. The C language 101
Part 11: Structures and Unions
Unions (3/4)
❍ Field access with member operator ”.”
❍ Only one member is accessible at a time
union { i n t i , double d } u;
u.i = 20; /* access to u.d allowed , but undefined */
...
u.d = 1.1; /* access to u.i allowed , but undefined */
❍ Use a selector
V. Granet U.N.S.A. The C language 102
Part 11: Structures and Unions
s t r u c t person {
char last_name[20], first_name[20];
s t r u c t date birthdate;
enum { f, m } sexe; /* selector */
union {
char maiden_name [20];
enum { false , true } army;
} info;
} p;
p.sexe = f; strcpy(p.info.maiden_name ,"Monroe");
p.sexe = m; p.info.army = false;
V. Granet U.N.S.A. The C language 103
Part 11: Structures and Unions
Unions (4/4)
❍ Size of an union object = memory space for
representing its largest member (+ eventually
alignment requirements)
struct {
};double c;int b;char a;
c
union {
};double c;int b;char a;
������������������������������������
������������������������������������
������������������
����������������������
������������
����������������
char = 8 bits, int = 32 bits, double = 64 bits
a b
abc
V. Granet U.N.S.A. The C language 104
Pointers
V. Granet U.N.S.A. The C language 105
Part 12: Pointers
❍ A pointer contains the address of an object.
The access to the pointed object is thus
performed indirectly
❍ Pointers are typed ⇒ Compatiblity needed
for assignment!
❍ Conversions
– implicit to any pointer to void * (and
back)
– any other pointer types need an explicit
cast
❍ #define NULL ((void *) 0)
in <stddef.h>
❍ Heavy use of pointers. Programs are
– more compact
– more efficient
– but far less readable!
– but error prone!
V. Granet U.N.S.A. The C language 106
Part 12: Pointers
Examples
i n t *p1, *p2; /* two pointers to integer */
char *p3 , p4; /* one pointer to char , one char */
char **s; /* pointer to pointer to char */
void *r; /* pointer to void (generic ) */
f l o a t *s[10] /* array of 10 pointers to real */
f l o a t (*t)[10] /* pointer to an array of 10 reals */
i n t (*pfunc)( void ); /* pointer to function with no
argument , returning an int */
i n t (*T[5])( void ); /* array of 5 such pointers */
V. Granet U.N.S.A. The C language 107
Part 12: Pointers
Basic operations on pointers
❍ * indirection (dereferencing)
❍ & address of (referencing)
i = 10;
pi = &i;
j = *pi;
(*pi)++;
q = pi;
pi i j q
10
10
10
10
11 10
1011
{ int *pi, i, j, *q = NULL;
}
V. Granet U.N.S.A. The C language 108
Part 12: Pointers
Arithmetic operators on pointers
❍ Comparison: == != < <= > >=
❍ Adding/substracting an integer:
– pointer + integer → pointer
– pointer − integer → pointer
– address scaling
❍ Substracting two pointers of same type
– pointer − pointer → integer
– the result is an algebraic number of
objects of the type
V. Granet U.N.S.A. The C language 109
Part 12: Pointers
Pointers and arrays (1/2)
❍ Pointers and arrays are closely related
concepts
❍ An array is a constant pointer to the first
element of the array
❍ t[i] ⇔ *(t+i)
❍ t[i][j] ⇔ *(*(t+i)+j)
i n t *p, t[8];
char *s = "hello";
char st[] = "hello";
p = t;
p = &t[0]; /* idem as above */
/*
t[2]==*(t+2)==*(p+2)==p[2]
s[2]==*(s+2)==*(" hello "+2)==" hello "[2]
*/
V. Granet U.N.S.A. The C language 110
Part 12: Pointers
Pointers and arrays (2/2)
❍ Difference between arrays and pointers
e l l o \0ht
e lh l o \0char *p = "hello";
char t[8] = "hello";
p
p++; /* OK */
t++; /* KO */
printf("%d %d\n", s i z e o f (p), s i z e o f (t));
/* 4 8 */
V. Granet U.N.S.A. The C language 111
Part 12: Pointers
Pointers and structures
❍ It is illegal for a structure to reference itself
❍ Recursive declarations use pointers
s t r u c t list {
i n t item;
s t r u c t list *next;
} *l;
❍ Access to structure (or union) members: ->
l->item is equivalent to (*l).item
V. Granet U.N.S.A. The C language 112
Part 12: Pointers
String functions with pointers
i n t strlen( const char *s)
/* calculate the length of a string s */
{
char *p = s;
whi le (*s++) /* empty body */;
return (s-1)-p;
}
V. Granet U.N.S.A. The C language 113
Part 12: Pointers
char *strcpy( char *s1 , const char *s2)
/*
copy the string pointed to by s2
to the string pointed to by s1
*/
{
char *p = s1;
whi le (*s1++ = *s2++) /* empty body */;
return p;
}
V. Granet U.N.S.A. The C language 114
Part 12: Pointers
Simulating call by reference
❍ When a function needs to return more than
one result
void swap( i n t *a, i n t *b)
{
i n t aux;
aux = *a; *a = *b; *b = aux;
} ...
i n t x, y;
...
swap (&x, &y); /* function call */
❍ Array is a pointer. There is no copying of
array elements!
V. Granet U.N.S.A. The C language 115
Part 12: Pointers
void reset( f l o a t t[], i n t n)
/* reset the t array to 0 */
{
i n t i = 0;
whi le (i<n) t[i++] = 0.0;
}
f l o a t ftab[MAX];
...
reset(ftab , MAX ); /* function call */
V. Granet U.N.S.A. The C language 116
Part 12: Pointers
Pointers and constants
❍ Constant pointer. Need to be initialized at
declaration time
i n t * const pconst = &x;
❍ Pointer to constant object. The object cannot
be modified through the pointer
const i n t *pconst;
❍ Constant pointer to constant object
const i n t * const pconst_to_const = &x;
const i n t i = 1;
i n t *p = &i; /* wrong */
V. Granet U.N.S.A. The C language 117
Part 12: Pointers
Pointers and functions (1/2)
❍ Function name = constant pointer to function
/* all following functions have no arguments */
/* function returning int */
i n t f(void );
/* function returning pointer to int */
i n t *f(void );
/* pointer to function returning int */
i n t (*f)(void );
/* array of pointers to function returning int */
i n t (*t[])( void );
/* function returning pointer to function
returning pointer to int */
i n t *(*f(void ))( void );
/* array of pointers to function returning
pointer to int
*/
i n t *(*t[])( void );
V. Granet U.N.S.A. The C language 118
Part 12: Pointers
Pointers and functions (2/2)
❍ Functions as arguments
#de f i n e MAX 100
extern void bubble( i n t *), quicksort( i n t *),
insertion( i n t *);
void (*sort_tab [])( i n t *) =
{ bubble , quicksort , insertion };
void sort( i n t *t, void (*f)( i n t *))
{
...; f(t); ...
}
i n t main(void )
{
i n t i=0, t[MAX];
whi le (i<3) sort(t, sort_tab [i++]);
return EXIT_SUCCESS;
}
V. Granet U.N.S.A. The C language 119
Part 12: Pointers
argc and argv (1/2)
❍ Execution support may pass two arguments
to main function when starting program
execution
❍ int argc = numbers of command-line
arguments
char *argv[] = the command-line
arguments
i n t main( i n t argc , char *argv [])
{ .... }
❍ Example
% a.out -opt file1 file2
\0\0
\0\0
NULL
a . o u t- o p tf i l e 1f i l e 2
argv[0]argv[1]argv[2]argv[3]
argc == 4
V. Granet U.N.S.A. The C language 120
Part 12: Pointers
argc and argv (2/2)
❍ Echo program
i n t main( i n t argc , char *argv [])
{
i n t i;
f o r (i = 1; i < argc; i++)
printf("%s%c", argv[i], i<argc -1 ? ’ ’ : ’\n’);
}
i n t main( i n t argc , char *argv [])
{
whi le (--argc > 0)
printf(argc >1 ? "%s " : "%s\n", *++argv);
}
V. Granet U.N.S.A. The C language 121
Part 12: Pointers
i n t main( i n t argc , char *argv [])
{
i f (argc >1) {
whi le (--argc > 1)
printf("%s " ,*++ argv );
printf("%s\n" ,*++argv );
}
}
V. Granet U.N.S.A. The C language 122
Part 12: Pointers
Dynamic memory allocation (1/2)
❍ Standard library functions
❍ Memory allocation
#inc lude <stdlib.h>
void *malloc(size_t size );
void *calloc(size_t nbelems , size_t size )
void *realloc (void *ptr , size_t new_size
These functions return a pointer to the
allocated memory space (initialized to 0 with
calloc), or NULL if they fail
❍ Memory desallocation
#inc lude <stdlib.h>
void free(void *ptr);
frees the memory space pointed to by ptr,
previously allocated by malloc, calloc or
realloc
V. Granet U.N.S.A. The C language 123
Part 12: Pointers
Dynamic memory desallocation (2/2)
#inc lude <stdlib.h>
typede f s t r u c t node {
i n t item;
s t r u c t node *left , *right;
} *tree;
tree new_leaf ( i n t x)
/* allocate a new leaf */
{
tree p = malloc( s i z e o f ( s t r u c t node ));
p->item = x;
p->left = p->right = NULL;
return p;
}
V. Granet U.N.S.A. The C language 124
Input/Output
V. Granet U.N.S.A. The C language 125
Part 13: Input/Output
Non formatted standard IO
❍ Reading characters and strings
i n t getchar (void );
char *gets( char *s);
❍ Writing characters and strings
i n t putchar ( i n t c);
i n t puts( char *s);
i n t puts( char *s)
{
r e g i s t e r i n t c;
whi le (c = *s++)
putchar (c);
return putchar (’\n’);
}
V. Granet U.N.S.A. The C language 126
Part 13: Input/Output
FILE (1/3)
❍ FILE type defines an IO stream for sequential
or direct IO
❍ Streams are buffered
❍ #include <stdio.h>
❍ Standard files: stdin, stdout and stderr
❍ Opening a file
– FILE *fopen (char *path, char *mode);
path: file name (depending on OS)
mode: "r" "w" "a" "r+" "w+" "a+" ...
– return a pointer to a file descriptor, or
NULL if it fails
❍ Closing a file
– int fclose(FILE *stream);
– upon successful completion 0 is returned,
otherwise EOF
V. Granet U.N.S.A. The C language 127
Part 13: Input/Output
FILE (2/3)
❍ Reading a file
i n t getc(FILE *stream ); /* a macro */
i n t fgetc(FILE *stream );
i n t ungetc( i n t c, FILE *stream );
char *fgets( char *s, i n t size , FILE *str
size_t fread(void *buf , size_t size ,
size_t nbelt , FILE *stream );
i n t feof(FILE *stream );
❍ Writing a file
i n t putc( i n t c, FILE *stream ); /* a macro
i n t fputc( i n t c, FILE *stream );
i n t fputs( const char *s, FILE *stream );
size_t fwrite(void *buf , size_t size ,
size_t nbelt , FILE *stream )
❍ Direct IO
i n t fseek(FILE *stream , long offset , i n t
long ftell(FILE *stream );
void rewind(FILE *stream );
V. Granet U.N.S.A. The C language 128
Part 13: Input/Output
whence may be SEEK\_SET SEEK\_CUR or
SEEK\_END
V. Granet U.N.S.A. The C language 129
Part 13: Input/Output
FILE (3/3)
❍ Example
V. Granet U.N.S.A. The C language 130
Part 13: Input/Output
#inc lude <stdio.h>
i n t main( i n t argc , char *argv [])
{
i n t c;
FILE *src , *dest;
/* check */
i f (argc != 3) {
fprintf(stderr , "Usage: copy file file\n");
exit (1);
}
i f ((src = fopen(argv[1], "r")) == NULL) {
fprintf(stderr , "Can ’t read \n",argv [1]);
exit (1);
}
i f ((dest = fopen(argv [2], "w")) == NULL) {
fprintf(stderr , "Can ’t write %s\n",argv [2]);
exit (1);
}
/* copy */
whi le ((c = getc(src)) != EOF)
putc(c, dest );
fclose(src); fclose(dest);
}
V. Granet U.N.S.A. The C language 131
Part 13: Input/Output
Formatted text IO (1/3)
❍ Printf functions
i n t printf( const char *format , ...)
i n t fprintf (FILE *stream , const char *fo
i n t sprintf ( char *buf , const char *form
i n t vprintf ( const char *format , va_list
i n t vfprintf (FILE *stream , const char *f
va_list ap);
i n t vsprintf ( char *str , char *format , va
❍ Scanf functions
i n t scanf( const char *format , ...);
i n t fscanf(FILE *stream , const char *for
i n t sscanf( const char *buf , const char
i n t vscanf( const char *format , va_list a
i n t vsscanf ( const char *str , const char
va_list ap);
i n t vfscanf (FILE *stream , const char *fo
va_list ap);
❍ These functions have a variable number of
arguments to write or read under the control
V. Granet U.N.S.A. The C language 132
Part 13: Input/Output
of a ”format” string. Result is the number of
characters printed or read
V. Granet U.N.S.A. The C language 133
Part 13: Input/Output
Formatted text IO (2/3)
❍ Conversions
%d %i int, short, long
%u unsigned, unsigned long
%o octal
%x %X hexadecimal
%c char
%s string
%p void *
%n int *
%f %e %E %g %G real
%[...] set of characters (scanf)
%% character % itself
Between % and the format, some characters may
appear: - 0 + # int int.int * (for printf
functions) ; int h l L * (for scanf functions)
❍ For printf functions, other characters are
printed unchanged
❍ For scanf functions, spaces match any amount
of white spaces, including none. Everything
else matches only itself.
V. Granet U.N.S.A. The C language 134
Part 13: Input/Output
Formatted text IO (3/3)
#include <stdio.h>
int main(void)
{int i = 123; unsigned u = 63; float f = -12.34;
char s[20];
printf("%d, %f, %o, :%s:\n", i, f, u, "hello");
printf("%+d, %e, %X, :%16s:\n", i, f, u, "hello");
printf("%+d, %1.2f |%010x| :%-*s:\n",
i, f, u, 16,"hello");
scanf("%d %f %s\n", &i, &f, s);
printf("i = %d, f = %f, s = %s\n", i, f, s);
scanf("%2d %f %*d %2s", &i, &f, s);
printf("i = %d, f = %f, s = %s\n", i, f, s);
}
/* with input:
25 54.32e-1 hello
54320 0456 67xx89
*/
123, -12.340000, 77, :hello:
+123, -1.234000e+01, 3F, : hello:
+123, -12.34 |000000003f| :hello :
i = 25, f = 5.432000, s = hello
i = 54, f = 320.000000, s = 67 /* s is a string */
V. Granet U.N.S.A. The C language 135
Separate compilation
V. Granet U.N.S.A. The C language 136
Part 14: Separate compilation
C program structure
❍ Modularity is based on files
program = set of files (modules)
file = list of declarations
declaration = type declarations
variable declarations & definitions
function declarations & definitions
label declarations
directives to the preprocessor
❍ Identifier declaration associates an identifier
to an object of the language
V. Granet U.N.S.A. The C language 137
Part 14: Separate compilation
Multi-file programming (1/4)
RULES FOR VISIBILITY
❍ Prefix by static functions and global
variables local to a module
❍ Functions and global variables visible in all
modules have to be DEFINED only ONCE.
For global variables, definition may include
initialization
❍ Functions and global variables to use in a
module and defined in other modules have to
be REFERENCED by a reference declaration
prefixed by extern
❍ Use a complete prototype for function
reference declarations
V. Granet U.N.S.A. The C language 138
Part 14: Separate compilation
V. Granet U.N.S.A. The C language 139
Part 14: Separate compilation
Multi-file programming (2/4)
/* file stack.c: stack implementation */
typede f s t r u c t {
i n t elts[MAX], /* element stack */
sp; /* index of top of the stack */
} STACK;
s t a t i c STACK stack; /* local to this module */
i n t code_error = 0; /* global error type */
s t a t i c i n t full_stack(void )
/* local function: check if stack is full */
{ ... }
i n t push( i n t x)
/* push x value on top of the stack */
/* return -1, if it fails , and set error code */
{ ... }
\END{texC}
\end{boxedcmd }
\begin{boxedcmd }\ footnotesize{}
\begin{texC}
/* file main.c: use of stack */
extern i n t push( i n t );
extern i n t code_error;
i n t main(void )
{
i f (push (3) == -1)
fprintf(stderr ,"push error: %d\n", code_error);
}
V. Granet U.N.S.A. The C language 140
Part 14: Separate compilation
Multi-file programming (3/4)
❍ Use header files
/* file stack.h */
#i f n d e f STACK_H
#de f i n e STACK_H
extern i n t code_error;
extern i n t push( i n t );
extern i n t pop(void );
...
#end i f STACK_H
V. Granet U.N.S.A. The C language 141
Part 14: Separate compilation
#inc lude "stack.h"
i n t main(void )
{
i f (push (3) == -1)
fprintf(stderr ,"push error: %d\n",code_error);
}
V. Granet U.N.S.A. The C language 142
Part 14: Separate compilation
Multi-file programming (4/4)
����������������������������������������������������������������������������
���������������������������������������������������������
���������������������������������������������������������
main.c
stack.h
stack.c
compilation
linkage
main.o stack.o
myprog libc
compilation and linkage:
% gcc -ansi -c -Wall stack.c
% gcc -ansi -c -Wall main.c
% gcc -o myprog main.o stack.o
V. Granet U.N.S.A. The C language 143
The preprocessor (2)
V. Granet U.N.S.A. The C language 144
Part 15: The preprocessor (2)
Macros with arguments (1/2)
#define identifier(x1,x2,..,xn) character sequence
❍ To define in-line pseudo-functions
#define getchar() getc(stdin)
#define putchar(c) putc(c, stdout)
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
❍ Replacement is purely textual
whi le ((c = getchar ()) != EOF)
m = min(m, c);
/* after replacement : */
whi le ((c = getc(stdin )) != (-1))
m = ((m) < (c) ? (m) : (c));
}
V. Granet U.N.S.A. The C language 145
Part 15: The preprocessor (2)
Macros with arguments (2/2)
❍ Priority problem ⇒ use parenthesis
#de f i n e square(x) x*x
... x = square(y+1); ...
/* after replacement : */
x = y + 1 * y + 1; that is x = y + (1 * y) + 1;
}
❍ Not a function call: beware of side-effects
m = max(x++, y++);
/* after replacement : */
m = ((x++) > (y++) ? (x++) : (y++));
/* x or y is incremented twice! */
❍ Beware of performance
V. Granet U.N.S.A. The C language 146
Part 15: The preprocessor (2)
x = max(t[abs(i)][j*3+1], t[i+3][j+1]);
/* indexes are evaluated several times */
V. Granet U.N.S.A. The C language 147
Part 15: The preprocessor (2)
“Stringification” in macros
❍ Prefix operator #
#de f i n e PRINT(x) printf("%s = %d\n", #x, x)
PRINT (1+2*3);
/*
⇒ printf ("%s = %d\n", "1+2*3", 1+2*3);
⇒ will print on stdout : 1+2*3 = 7
*/
Two adjacent strings are concatenated:
#de f i n e PRINT(x) printf (#x " = %d\n", x)
PRINT (1+2*3);
/*
⇒ printf ("1+2*3" " = %d\n", 1+2*3);
⇒ printf ("1+2*3 = %d\n", 1+2*3);
⇒ will print on stdout : 1+2*3 = 7
*/
V. Granet U.N.S.A. The C language 148
Part 15: The preprocessor (2)
Conditional compilation (1/2)
❍ Code parametrization
❍ Do not compile useless code
#if-header
then-code
#endif
#if-header
then-code
#else
else-code
#endif
#if-header
then-code
#elif static-expression
elif-code
#endif
where if-header is:
#if static-expression
#ifdef identifier (true if id is defined)=
#ifndef identifier (true if id is not defined)=
V. Granet U.N.S.A. The C language 149
Part 15: The preprocessor (2)
Conditional compilation (2/2)
#i f n d e f MAXSIZE
#de f i n e MAXSIZE 512
#end i f
s t r u c t exec { /* a.out header */
#i f __u370
i n t a_magic; /* magic number */
i n t a_stamp; /* The version of a.out */
#e l s e
short a_magic; /* magic number */
#end i f
...
}
#i f MAXSIZE > 1024
#erro r MAXSIZE must be less than 1024
#e l s e
i n t buf[MAXSIZE ];
#end i f
To avoid multiple inclusions
V. Granet U.N.S.A. The C language 150
Part 15: The preprocessor (2)
#i f n d e f INCL_H
#de f i n e INCL_H
/* Contents of incl.h file */
#end i f
V. Granet U.N.S.A. The C language 151
Part 15: The preprocessor (2)
#line and #pragma
❍ #line constant [ file ]
Used by generators of C programs for
purposes of error diagnostics. Re-assign the
line counter
❍ #pragma
provides a way to transmit implementation
informations to the compiler
V. Granet U.N.S.A. The C language 152
C library
V. Granet U.N.S.A. The C language 153
Part 16: C library
Characters: ctype.h
isalnum isalpha isascii isblank iscntrl
isdigit isgraph islower isprint ispunct
isspace isupper isxdigit
Strings: string.h
bcopy memchr memcmp memcpy
memmove memset strcasecmp strcat
strchr strcmp strcoll strcpy
strcspn strdup strfry strlen
strncat strncmp strncpy strncasecmp
strpbrk strrchr strsep strspn
strstr strtok strxfrm index
rindex
Mathematics: math.h
acos acosh asin asinh atan atanh
atan2 ceil cos exp fabs floor
frexp hypot log log10 modf pow
rint sin sqrt tan tanh
V. Granet U.N.S.A. The C language 154
Part 16: C library
Input/Output: stdio.h
clearerr fclose fdopen feof ferror
fflush fgetc fgetline fgetpos fgets
fileno fopen fprintf fpurge fputc
fputs fread freopen fropen fscanf
fseek fsetpos ftell fwrite getc
getchar gets getw mktemp perror
printf putc putchar output puts
putw remove rewind scanf setbuf
setbuffer setlinebuf setvbuf sprintf sscanf
strerror tempnam tmpfile tmpnam ungetc
vfprintf vfscanf vprintf vscanf vsprintf
vsscanf
General: stdlib.h
abort abs atof atoi atol
bsearch calloc div exit free
getenv labs ldiv malloc putenv
qsort rand realloc setenv srand
strtod strtol strtoul unsetenv system
V. Granet U.N.S.A. The C language 155
Part 16: C library
Assertion: assert.h
assert
Variable number of arguments: stdarg.h
va arg va end va start va list
Non local goto: setjmp.h
setjmp longjmp
Signals: signal.h
signal raise
Date and Time: time.h
asctime clock ctime difftime gmtime
localtime mktime newctime strftime tzset
V. Granet U.N.S.A. The C language 156
Programming environment
V. Granet U.N.S.A. The C language 157
Part 17: Programming environment
Tools
cc gcc compilers
emacs GNU editor (c-mode)
gdb GNU debugger
make make utility to maintain groups of
programs
lint C program checker
prof performance test program
V. Granet U.N.S.A. The C language 158