Professional Documents
Culture Documents
! A brief history of C
! C as a programming language
! C Programming
"main function
"constants, variables, data types
"operators, control structures
"functions
Programming in C "data structures
"pointer arithmetic
"structures
"dynamic memory allocation
Prof. Gustavo Alonso
Computer Science Department
ETH Zürich
alonso@inf.ethz.ch
http://www.inf.ethz.ch/department/IS/iks/
©Gustavo Alonso, ETH Zürich. Programming in C 3 ©Gustavo Alonso, ETH Zürich. Programming in C 4
This is C The C compilation model
! The Preprocessor accepts source code as source code
#include <stdio.h> Winner of the international input and
Obfuscated C Code Contest "removes comments
main(t,_,a) preprocessor
http://reality.sgi.com/csp/iocc "extends the code according to the
char *a;
{return!0<t?t<3?main(-79,-13,a+main(-87,1-_,
preprocessor directives included in the
source code (lines starting with #)
main(-86, 0, a+1 )+a)):1,t<_?main(t+1, _, a ):3,main ( -94, -27+t, a compiler
)&&t == 2 ?_<13 ?main ( 2, _+1, "%s %d %d\n" ):9:16:t<0?t<-72?main(_, ! The Compiler takes the output of the
t,"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+\ preprocessor and produces assembly code assembly code
,/+#n+,/#;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l q#'+d'K#!/\ ! The Assembler takes the assembly code
+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# ){n\ and produces machine code (or object assembler
l]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#\ code)
object libraries
n'wk nw' iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \ ! The Linker takes the object code, joins it code
;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;\ with other pieces of object code and
#'rdq#w! nr'/ ') }+}{rl#'{n' ')# }'+}##(!!/") libraries and produces code that can be linker
:t<-50?_==*a ?putchar(a[31]):main(-65,_,a+1):main((*a == '/')+t,_,a\ executed
+1 ):0<t?main ( 2, 2 , "%s"):*a=='/'||main(0,main(-61,*a, "!ek;dc \
executable code
i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}
©Gustavo Alonso, ETH Zürich. Programming in C 5 ©Gustavo Alonso, ETH Zürich. Programming in C 6
©Gustavo Alonso, ETH Zürich. Programming in C 9 ©Gustavo Alonso, ETH Zürich. Programming in C 10
before the main function. They can be "extern: the variable is defined in a global_variable = 1;
accessed from anywhere in the program. different module local_variable = 2;
Try to avoid global variables (a matter of "static: for local variables: makes them
programming style) last the entire program, for global {
variables: restricts the scope to the int very_local_variable;
! Local variables are valid and visible within current module very_local_variable = 3;
a particular block (a block is a set of C "register: try to use a CPU register for
}
statements enclosed within brackets { the variable
…}). Once the control flow is outside "auto: default for local variables
the block, the variable no longer exists }
©Gustavo Alonso, ETH Zürich. Programming in C 11 ©Gustavo Alonso, ETH Zürich. Programming in C 12
Expressions and priority Short-hand operators
! C allows for a short hand notation that introduces side effects. This is done through the
! +, -, *, /, % are the basic arithmetic ! Multiplication operators (*, /, %) have a prefix- or postfix operators ++, --
operators higher priority than the additive operators
Addition ! If ++ or -- are used as prefixes, the variable is modified before it is used in the evaluation
! (+, -). When evaluating an expression, of an expression:
x = 3 + 4; operators with a higher priority are
! Subtraction evaluated first:
x = 10 - 3; a = 3;
! Multiplikation x = 2 + 3 / 2 + 3; b = ++a + 3; /* b = 4 + 3 = 7 and a = 4 side effect */
/* x = 2 + 1 + 3 */
x = 3 * 4;
! Division x = (2 + 3) / (2 + 3); ! If ++ or -- are used as postfixes, the variable is first used to evaluate the expression and
x = 73 / 8; /* x = (5 / 5) = 1 */ then modified.
/* x=9, if int x */
x = 73.0 / 8.0; x = 4*(1/2); /* x = 0 */ a = 3;
/*x=9.125,if float x */ x = 4*1/2; /* x = 2 */ b = a++ + 3; /* b = 3 + 3 = 6 and a = 4 */
! Modulo
x = 73 % 8;
/* x=1, the reminder of the
! Almost all operators can be combined with =
division */ a += b; /* a = a + b */
a *= b; /* a = a * b */
©Gustavo Alonso, ETH Zürich. Programming in C 13 ©Gustavo Alonso, ETH Zürich. Programming in C 14
0 1 0 1 1 1 0 1 1 1 0 1 0 0 0 0 1 0 1 1 1
1 0 0 1 1
1 1 1 0 1
! With a << b the bits in the variable a are displaced b positions to the left (the new bits
are filled with 0).
! With & one can set bits to 0. a a* = 2 b a << 3
! With ^one can reverse the valu of bits (0 becomes 1 and 1 becomes 0) 1 0 1 1 1 0 1 0 1 1 0 1 0 0 0 0
! With | one can set bits to 1.
©Gustavo Alonso, ETH Zürich. Programming in C 15 ©Gustavo Alonso, ETH Zürich. Programming in C 16
Comparison and logical operators if statement
! The comparison operators return a 1 or a 0 depending on the result of the comparison. The ! The if – then – else statement can be
comparison operators in C are used with or without the else. The two
forms are: true false
if (expression) expression
"< (smaller than)
statement1
"> (greater than) Statement 1 Statement 2
"<= (smaller or equal than) if (expression)
">= (greater or equal than) statement1
"== (equal than) else
statement2
"!= (not equal than) if (a >= 3) a = a - 3;
if (a == 3) a = a * 3;
! In both cases, when the expression is true, else a = a * 5;
! && and || are the logical AND and OR operators then statement1 is executed. If the
( a != b) && (c > d) expression is false, then, in the first case,
(a < b) || (c > d) statement1 is skipped (not executed), and,
in the second case, statement2 after the if (a >= 3) { a = a - 3;
else is executed. if ( a == 3) a = a * 3;}
else a = a * 5;
©Gustavo Alonso, ETH Zürich. Programming in C 17 ©Gustavo Alonso, ETH Zürich. Programming in C 18
©Gustavo Alonso, ETH Zürich. Programming in C 19 ©Gustavo Alonso, ETH Zürich. Programming in C 20
Switch (example) for statement
char a = ‘A’; a = ‘A’; ! The for statement provides a compact way
switch (a) { switch (a) { to iterate over a range of values.
case ‘A’: x *= x; break; case ‘A’: x *= x; for (initialization; termination; increment) { initialization
case ‘B’: x /= x; break; case ‘B’: x /= x; statement
default: x += 5; default: x += 5; }
} } termination increment
! All elements in the for loop are optional: true
for (; ; ); false
! Once the case ‘A’ is found, x *= x is ! Once case ‘A’ is found, x *= x is ! break can be used to interrupt the loop statement
executed and then we continue after the executed. However, there is no break. This without waiting for the termination
switch statement. in all cases, only one means we continue executing statements condition to evaluate to true
case will be executed (either ‘A’ or ‘B’ or while ignoring the cases (the check is not
‘default’) performed anymore). Thus, the following ! continue can be used to skip execution of
! Note that a is of type char. It does not statements will also be executed the body of the loop and re-evaluate the for (int x =0; x < 100; x = x + 3){
matter, char is treated as an integer using termination condition if (x == 27) continue;
x /= x; else printf(“%d”,x);
type conversion }
x += 5;
©Gustavo Alonso, ETH Zürich. Programming in C 21 ©Gustavo Alonso, ETH Zürich. Programming in C 22
©Gustavo Alonso, ETH Zürich. Programming in C 25 ©Gustavo Alonso, ETH Zürich. Programming in C 26
1 4 7 2 5 8 3 6 9
©Gustavo Alonso, ETH Zürich. Programming in C 27 ©Gustavo Alonso, ETH Zürich. Programming in C 28
More on arrays Pointers
! Arrays can be initialized when they are ! Strings are arrays of characters terminated ! A variable has a name, an address, a type, ! Pointers are used with the * and &
defined: with the null character \0 and a value: operators:
"the name identifies the variable to the int* px; /*px = pointer to an integer*/
/* a[0] = 3, a[1] = 7, a[2] = 9 */ char str[6] = {‘h’,’a’,’l’,’l’,’o’,’\0’} programmer
int a[3] = {3, 7, 9}; "the address specifies where in main int x; /*x is an integer */
char str[6] = "hello"; memory the variable is located (i.e.,
/* liste[0]=0.0, …, liste[99]=0.0 */ the beginning of the memory region
float list[100] = {}; ! For string manipulation, however, use the reserved for this variable ) px = &x; /* px gets the address of x */
string.h library "the type specifies how to interpret the /* or px points to x */
int a[3][3] = { ! In C, arrays are just a syntactic data stored in main memory and how
{ 1, 2, 3} convenience to make programming easier. long the variable is x = *px; /* x gets the contents of */
{ 4, 5, 6} Arrays are, for the compiler, the same as "the value is the actual data stored in
{ 7, 8, 9}
/* whatever x points to */
pointers (the array name is a pointer to the variable after if has been
}; the beginning of the array) interpreted according to a given type
! Pointers are language constructs that allow
programmers to directly manipulate the
1 2 3 4 5 6 7 8 9 address of variables
©Gustavo Alonso, ETH Zürich. Programming in C 29 ©Gustavo Alonso, ETH Zürich. Programming in C 30
int* int
*nummer = 8; /* CAREFUL, 8 is not a pointer but an integer */
nummer_ptr = &nummer;
3
nummer_ptr nummer
5
int x = *nummer_ptr;
7 7
x nummer_ptr nummer
nummer_ptr nummer
©Gustavo Alonso, ETH Zürich. Programming in C 31 ©Gustavo Alonso, ETH Zürich. Programming in C 32
Pointers (III) Pointers (IV)
int int* int
*y_ptr = 6;
7 6 y_ptr
x nummer_ptr nummer
int*
©Gustavo Alonso, ETH Zürich. y_ptr Programming in C 33 ©Gustavo Alonso, ETH Zürich. Programming in C 34
p_ptr_ptr p_ptr_ptr
p_ptr_ptr = &nummer_ptr; 7 6 7 5
x nummer_ptr nummer x nummer_ptr nummer
int* int*
y_ptr y_ptr
©Gustavo Alonso, ETH Zürich. Programming in C 35 ©Gustavo Alonso, ETH Zürich. Programming in C 36
Pointers, arrays and strings Troubles with pointers
! An array is in reality a pointer: ! Strings can be manipulated through What is printed by the following code? What is printed by the following code?
int a[10], y; pointers:
char* message; #include <stdio.h> #include <stdio.h>
int* px; void f(int *aa, int *bb) { void g(int *aa, int *bb) {
px = a; /* px points to a[0] */ message = “This is a string”;
*bb = 8; bb[2] = aa[-2];
px++; /* px points to a[1] */ ! message is a pointer that now points to the aa[1] = bb[2]; *aa++ = 17;
px=&a[4]; /*px points to a[4] */ first character in the string “This is a aa = bb; *++aa = 10;
string” } }
y = *(px+3) /*y gets the value*/ ! Again, use the string.h for string
/* in a[3] */ manipulation rather than doing it directly main() { main() {
! The pointer arithmetic in C guarantees that (you will avoid many errors) int a[5] = { 1, 2, 3, 4, 5 }, *b; int blap[7] = { 1, 2, 3, 4, 5, 6, 7 };
if a pointer is incremented or decremented, b = a + 2; int *c = blap + 3;
the pointer will vary according to its type. f(a,b); g(c,blap);
For instance, if px points to an array, printf("%d %d %d %d %d\n", printf("%d %d %d %d %d %d %d\n",
px++ will always yield the next element a[0], a[1], a[2], a[3], a[4]); blap[0], blap[1], blap[2], blap[3],
independently of what is the type stored in
} blap[4], blap[5], blap[6]);
the array
}
©Gustavo Alonso, ETH Zürich. Programming in C 37 ©Gustavo Alonso, ETH Zürich. Programming in C 38
©Gustavo Alonso, ETH Zürich. Programming in C 39 ©Gustavo Alonso, ETH Zürich. Programming in C 40
struct Functions
! C is a modular language where the main ! General syntax:
unit of composition is the function
inhalt
char[50]
inhalt
char[50]
inhalt
char[50] ! A function has the following elements: returntype function_name(def of parameters) {
"a return type: specifies the type of the localvariables
value returned by the function when it functioncode
anzahl anzahl anzahl terminates }
"a function name: identifies the
int int int
function for the programmer ! An example:
preis preis preis "arguments of defined types: float findaverage(float a, float b) {
float float float ... parameters to pass to the function, float average;
which can be
average=(a+b)/2;
liste_kisten[0] liste_kisten[1] liste_kisten[2] • by value: the function gets the a return(average);
copy of the value of the }
liste_kisten[0].inhalt liste_kisten[1].inhalt liste_kisten[2].inhalt parameters but cannot modify the
liste_kisten[0].anzahl liste_kisten[1].anzahl liste_kisten[2].anzahl actual parameters
! In ANSI C functions must be declared as prototypes
liste_kisten[0].preis liste_kisten[1].preis liste_kisten[2].preis • by reference: the function gets the before they are defined:
address (reference) of the float findaverage(float a, float b)
parameters and can modify them
©Gustavo Alonso, ETH Zürich. Programming in C 41 ©Gustavo Alonso, ETH Zürich. Programming in C 42
©Gustavo Alonso, ETH Zürich. Programming in C 45 ©Gustavo Alonso, ETH Zürich. Programming in C 46
©Gustavo Alonso, ETH Zürich. Programming in C 47 ©Gustavo Alonso, ETH Zürich. Programming in C 48