Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
1
Functions and Program Structure
(K+R Ch. 4)
C program structure
F ti Functions
Categories, scope and life time of variables (and functions)
C Preprocessing
9
2
Program Structure• C programs consist of a set of variables and functions.
• we have discussed variables expressions (ch2) and • we have discussed variables, expressions (ch2) and control flow (ch3).
• now want to combine these into a program (ch4)
• C programs consist of statements
• expression statements (ch2)
• control flow statements (ch3)
• block, function call statements (ch4)
10
Program structure ‐‐ Functions A function is a set of statements that may have:
a number of arguments ‐‐‐ values that can be passed to it
a return type that describes the value of this function in a return type that describes the value of this function in an expression
Communication between functions
by arguments and return values
by external variable (ch1.10, ch4.3)y ( , 4 3)
Functions can occur in any order
In a single source file
In multiple source file
11
3
Program structures ‐‐ Functionsreturn_type functionName (parameter type name, ……){block}
int sum (int i, int j){int s = i + j; return s; /* return i+j; */
}
void display (int i){ printf(“this is %d”, i);
}}
int main(){int x =2, y=3;display( sum(x, y));} /* this is 5 */
Communication by arguments and return values
Program structure ‐‐ functions
communication by external variables#include <stdio.h>
int resu; /* external variable */
void sum (int i, int j){
resu = i + j;
}
int main(){
int x =2, y =3;
sum(x,y);
printf(“%d + %d = %d\n”, x,y, resu);
}
4
Program structure ‐‐ functions
communication by external variables#include <stdio.h>
i t /* t l i bl */int resu; /* external variable */
void sum (int i, int j){ resu = i + j;
}display(){
printf(“this is %d\n”, resu);}}
int main(){int x =2, y =3;sum(x,y);display(); /* this is 5 */
}
Multiple source files
C program with two source filesf1 f2int sum (int x, int y){
return x + y;}
#include <stdio.h>
int sum(int, int);
int main(){int x =2 y =3;
f1.c f2.c
int x =2, y =3;printf(“%d + %d = %d\n”, x,y,sum(x,y));
}
15To compile: gcc f1.c f2.c gcc f1.o f2.c
5
Multiple source files
C program with two source filesf1 f2int resu;
int sum (int x, int y){
resu = x + y;}
#include <stdio.h>extern int resu;int sum(int, int);
int main(){int x =2 y =3;
f1.c f2.c
} int x =2, y =3;sum(x,y); printf(“%d\n”, resu);
}
16To compile: gcc f1.c f2.cTo compile: gcc f1.c f2.c gcc f1.o f2.c
C program structure
F ti Functions
Categories, scope and life time of variables (and functions)
C Preprocessing
17
6
Declaring Functions (review)
Declaring a function before using it, if it is defined in
library library
another source file of the program
later in the same source file
Declaring a function tells us its return type and arguments but not its code.g
int sum (int i, int j);
Like a function definition but with ‘;’ instead of a block18
Declaring Functions We can omit argument names
int sum(int, int);
The type of arguments is what matters
But, good practice recommends putting names
char *strcpy(char *, char *);
char *strcpy(char *dest, char *src);
What if we don’t want any arguments?
19
7
Type conversionstype function (){
return expr;return expr;}
If expr is not of type type, compiler produces a warning
converts expr (as if by assignment) to the return type of the function
should avoid
int function (){double x; return x; // return (int)x if you have to
}
20
Calling‐by‐Value In C, all functions are called‐by‐value
Value of the arguments are passed to functions, but not the arguments themselves (call by reference)
int sum (int x, int y)
{
int s = x + y;
return s;
…
int i =3
int j = 4
int k
… call sum()
running main()
21
}
main(){
int i=3, j=4, k;
k = sum(i,j);
}
…
int x = 3
int y = 4
int s
…
running sum()
8
Calling‐by‐Value does this code work?
#include <stdio.h>
void swap (int x, int y)
{ int temp;
temp = x;
x = y;
y = temp;
}
…
int i =3
int j = 4
… call swap()
running main()
22
}
int main(){
int i=3, j=4;
swap(i,j);
printf(“%d %d\n”, i,j);
}
int x = 3
int y = 4
int tmp
…
running swap()
C program structure
F ti Functions
Categories, scope and life time of variables (and functions)
C Preprocessing
23
9
Categories of variables
Two categories of variables Automatic (local, internal)
External (global)
Defined outside any function
Potentially available to
ll f( , )
Defined inside a function
int main(){
int k, char arr[20];
}
getReverse (int size){
i t t 0
#include <stdio.h>int resu;
void sum(int x, int y){resu = x + y;
}
all functions
Functions? (global / local?)
24
int count = 0;
while(count < size)
……
}
int main(){int x =2, y =3;sum(x,y);printf(%d + %d = %d\n”, x,y,resu)
}
Scope
Scope of a name (variable or function) – the part of program within which the name can be used
Functions are all global!
Automatic (local) variables: only exist within their block:{int x;{{int y; /* y defined here */
}/* y not defined here */
}/* x not defined here */
25
10
Scope –external (or global) Variables
What if we want a variable to be available to more than one function?
Declare it outside of a function:
Visible in all functions (later) in the file (scope)
#include <stdio.h>int resu;
void sum(int x, int y){resu = x + y;
main(){….}
int sp = 0;double val[MAXVAL];
26
resu = x + y;}
int main(){int x =2, y =3;sum(x,y);printf(%d + %d = %d\n”, x,y,resu)
}
void push(double f){val[sp++] = f;
}
double pop(void){return val[--sp];
}
Scope Multiple Files External variables (as well as functions) are visible in other C files
Other files wanting to use declare it with extern before use
calc.cextern int res;
void sum(int x,int y){
main.cint res;
void sum(int,int);
27
{res = x + y;
}int main() {sum(3,4);printf(“%d\n”,res);
}
11
External Variables External variables can be overridden:
int x;void add_n_to_x(int n) {x += n;
}void set x to m(int m) {
global “x”
void set_x_to_m(int m) {int x;x = m;
}
28
local “x”
Pros and cons of external variables Clean code
variables are always there, function argument list is short
Si l i ti b t f ti Simple communication between functions
Any code can access it. Hard to trace. Maybe changed unexpectedly
Make the program hard to understand
In function, global variables can be overridden
They make separating code into reusable libraries more difficult
Avoid using it unless necessary 29
12
Life time automatic variables
Come to life when the function it is in is invoked,
Vanishes when the function returns Vanishes when the function returns
Values are not retained between function calls.
int sum (int x, int y)
{
int s = x + y;
return s;
…
int i =3
int j = 4
int k
30
return s;
}
main(){
int i=3, j=4, k;
k = sum(i,j);
k = sum(k,j);
}
int x = 3
int y = 4
int s
…
vanish after sum() returns
call sum()
Life time external variables
Permanent, as long as the program stays in memoryPermanent, as long as the program stays in memory
Retain values from one function to the next
Can be used as an alternative for communication data between functions
But use it with caution!
31
13
Static have different meanings
Static declaration
Static have different meanings
For global variable or function, hide it from other files. Limit the scope to the rest of the source file
static int variable;
F l l i bl k i lif i i For a local variable, make its lifetime persistentfunction(){
static int i;
}
32
Static declaration By default, all global symbols (functions and global variables) in a source file are visible to the world.
Undesirable as it ‘pollutes’ the global namespace and may expose sensitive data.
Using static keyword in front of a global variable or function static resu;
static void sum(int)
33
14
static (Hiding global variable)
int x; /* visible to other files*/; / /
static int y; /* not visible to
other files */
void func1(void)
{
y++; /* but y can still bey++; /* but y can still be
accessed in this file */
}
34
static (Hiding global variable)
int x =5; #include <stdio.h>int y = 1;
void func1 (void){y++;
}
extern int xextern int y;void func1(void);
int main(){y = 10;} y = 10;func1()printf(“x=%d\n”, x);printf(“y=%d\n”,y)
}
35What are printed? 5 11
15
static (Hiding global variable)
int x =5; #include <stdio.h>static int y = 1
Void func1 (void){y++;
}
extern int xextern int y;void func1(void);
int main{y=10;y=10;func1()printf(“x=%d\n”, x);printf(“y=%d\n”,y)}
36What will happen? undefined reference to `y'
static (Persistent local Variables) Lifetime: External (global) variables: by their nature static.
That is they never vanish, value is persistent
Lifetime: Automatic(local) variables ‐‐ in functions
They are created when the function is called and vanish when the function returns
What if we want a local variable in a function to be persistent?
Declare it static
Alternative to a global variable
Scope does not change, still within the function 37
16
static (Persistent local Variables)
int unique int(void) {q _ ( ) {
static int counter;
return counter++;
}
The value of “counter” is preserved between calls to The value of counter is preserved between calls to “unique_int”
Question: initial value of “counter”?
38
Initialization of variables For global (static or no) and static local variable
Initialization takes place at the compiling time before Initialization takes place at the compiling time before program is invoked
Initialized to 0 if no explicit initial value is given
So the first call to unique_int() returns 0
For general (non‐static) local variables
If an explicit initial value is given, initialize it each time the function is invoked
If no explicit initial value, initial values are undefined (not initialized for you)
39
17
Summary of variables categories
Four different categoriesg External (global) variable
Static external variable
Local (automatic, internal) variable
Static local variable
What are the difference between them, in terms of scope
Life time
40
C program structure
Functions
Categories, scope and life time of variables (and functions)
C Preprocessing
41
18
How C Programs are Compiled
C programs go through three stages to be compiled:C programs go through three stages to be compiled:
Preprocessor ‐ handles #include and #define
Compiler ‐ converts C code into binary processor instructions (“object code”)
Linker ‐ puts multiple files together and creates an executable program
42
19
The c preprocessor Proprocess c files before compiling itProprocess c files before compiling it
Handles “#define” and “#include”
also #undefine, #if, #ifdef, #ifndef …
Removes comments Removes comments
Output c code
44
C preprocessor #include #define
C executables are built in three stagesC executables are built in three stages
preprocessor compilerpreprocesso
r
hello.c
Handles C t C Puts multiple
hello.o a.out
Handles #include
#define
Converts C code into binary processor instructions
Puts multiple files together and creates and executable program
20
preprocessing #include #define
# include <file> ‐‐ include <stdio.h> library header file # include “file” ‐‐ include “file.h” programmer defined
“includes” another file in the current file as if contents were part of the current file Textual replace. Nothing fancy
file. .header file, which is just c code, usually containsF ti D l ti Function Declarations
External variable declaration Macro definitions #define
Do it in one spot so other files can just include the header file
int printf () ….
int sprintf () ….
#define EOF -1
extern struct _TO_FILE t*stdin
# include <stdio.h>main()
{
int i;
printf(“this is
%d\n”,i);}
21
#define #define defines macros#
Macros substitute one value for another
e.g.
#define IN 1
state = IN;
becomes
48
becomes
state = 1;
# define directive Syntax # define name value
name called symbolic constant, conventionally written in upper case value can be any sequence of charactersvalue can be any sequence of characters
#define N 100main() {int i = 10 + N;}
#
main() {
int i = 10 + 100;
}
#define FOO barfunc(FOO, “FOO”, Foobar)
Textual replacement try yourself by cpp file.c or cpp file.c > outputFile
func(bar,”FOO”,Foobar)
22
#define Macros can also have argumentsMacros can also have arguments
e.g.
#define SQUARE(x) x*x
y = SQUARE(4);
becomes
y = 4*4;
50
y = 4*4;
e.g., PRINT(x,y) printf(“%d,%d\n”, x,y)
#defineBe careful with argumentsBe careful with arguments
SQUARE(5+2)
becomes
5+2*5+2 = 17 (!)
Use parentheses defensively, e.g.
#define SQUARE(x) ((x)*(x))
51
#define SQUARE(x) ((x)*(x))
((5+2)*(5+2)) = 49
23
#define How to define a macro MAX(A,B) to represent the How to define a macro MAX(A,B) to represent the maxmium value of A and B
#define MAX(A,B) ((A)>(B)? (A):(B))
52
‘#’ operator In macros, ‘#’ can be used to make a string
#define PRINT(x) printf(“%s\n”,#x)PRINT(hello there);
givesprintf(“%s\n”,“hello there”);
adds quotes, escapes double‐quotes, e.g.PRINT(“hello there”)
53
PRINT(“hello there”)givesprintf(“%s\n”,“\”hello there\””);
24
#undef A macro should only be defined once
#d fi X 5#define X 5
#define X 3 -- warning
However, what we can define, we can undefine
#define X 3
X is replaced with “3”
54
#undef X
X is not replaced
#define X 4
X is replaced with “4”
#if ‐ Conditional Compilation We can also test to see if a macro is definedWe can also test to see if a macro is defined
#define DEBUG /* no value needed */
#if defined(DEBUG)printf(“debugging\n”);
#endif
55
#endif
#if !defined(DEBUG)
printf(“not debugging\n”);
#endif
25
#if ‐ Conditional Compilation defined() and !defined() are so common we have constructs for them:constructs for them:
#define DEBUG
#ifdef DEBUG
printf(“debugging\n”);
#endif
56
#endif
#ifndef DEBUG
printf(“not debugging\n”);
#endif
#if ‐ Conditional Compilation#define FRANCE
main()main()
{ #ifdef US printf(“compiled for USA”);
#endif
#ifdef UK printf(“compiled for UK”);
#endif
#ifd f FRANCE i tf(“ il d f FR”)
57
#ifdef FRANCE printf(“compiled for FR”);
#endif
#ifndef GERMAN printf(“no Germ version”);
#endif }
26
C preprocessor
#include <> “” #
#define
#undefine
#if defined #endif
58
#if defined #endif
#ifdef #endif
#if !defined # endif
#ifndef #endif
C preprocessorpredefined macro names_ _LINE_ _
_ _FILE_ _
_ _DATE_ _
_ _TIME_ _
main(){
printf("%s %s\n", __TIME__, __DATE__);
printf("%s %d\n", FILE , LINE );
59
p ( \ , __ __,__ __);
}
21:45:54 Jan 28 2013
macro.c 7
Useful for debugging
27
C preprocessorpredefined macro names_ _LINE_ _ _ _FILE_ _
_ _DATE_ _ _ _TIME_ _ _ _FUNCTION_ _
Useful for debugging
fprintf (stderr, "Internal error: " "negative string length " "%d at %s, line %d.", length, __FILE__, __LINE__);
60
__FUNCTION__ gcc
__fun__ c99
Recursion C functions maybe invoked recursively
int length (String s)
if (s contains one letter)
return 1;
return 1 + length(subString(s,1));
length(ABCD)
= 1 + length(BCD)
= 1 + ( 1 + length(CD))
= 1 + ( 1 + ( 1 + length(D)))
= 1 + ( 1 + ( 1 + 1 )) = 4 61
28
Other small things Typedef
typedef int INTEGERtypedef int INTEGER
INTEGER x = 4;
man
man chmod cp …
f() l () man 3 scanf() strlen()
diff youslu myslu
62
63
29
Finished Ch1 – 4Finished Ch1 4
Other C materials before pointer
2D array, string manipulations
Common library functionsCommon library functions
64
Declaring Arrays
As variables
int k[5]; int k[5] = {1,5,3,2,25}; /*array initializer */int k[5] = {1}; /* valid. (rest is “0”) */int k[3] = {1,4}; /*valid (k[0]=1, k[1]=4,k[2]=0)int k[3] ={1,4,2,1 } /*invalid */int k[ ] ={1,5,3,2,25}; /*valid*/[ ] { , , , , }int k[ ]; /*invalid */
30
Accessing Arrays
You can only assign to array members individually
This means you cannot assign to an arrayThis means you cannot assign to an array
Array / strings can not be copied as a whole
int i, k[4], j[4];for (i=0; i<4; i++)
j[i]= i;
k = j; /* invalid */k = {1,2,3,4 }; /* invalid */
Strings == Character Arrays ! There is no separate “string” type in C
String s = “Hello”;
H e l l o \0
Strings are just arrays of char that end with ‘\0’
char s[]=“Hello”; /* size? length? */which is equivalent to
char s []= {‘H’,’e’,’l’,‘l’,’o’,’\0’}
char s[50];char s[50];s = “Hello”;s = {‘H’,’e’,’l’,‘l’,’o’,’\0’};
s[0]= ‘H’; s[1] = ‘e’ ….
31
Multi diminsion array, array of strings
int arr2D [3][2];
a[o][0] a[o][1]
int arr2D [3][2];
Size: type bytes * column * row
4 * 2 * 3 = 24 bytes
Initialization:
int arr2D [3][2] = {1 1 2 4 3 9};
a[1][0] a[1][1]
a[2][0] a[2][1]
int arr2D [3][2] = {1,1,2,4,3,9};
int arr2D [3][2] = {{1,1},{2,4},{3,9}}
Access: arry[o][2] = 5;
68
1 1
2 4
3 9
Multi dimension array, array of strings
Initialization: int arr2D [][3] = 1 1
Initialization: int arr2D [][3]
{1,1,2,4,3,9};
int arry3D [][2][10];
Array of “strings”
char messages[3][10]
2 4
3 9
H l l \0 char messages[3][10]
={“Hello”,
”Hi”,”There”};
69
0
1
2
H e l l o \0
H i \0
T h e r e \0
32
Multi dimension array, array of stringsset on the fly Array of “strings”
char messages[3][10]
={“Hello”0 H e l l o \0
={ Hello ,
”Hi”,”There”};
for (int i=0…3)
scanf(“%s”,message[i]);
printf(“%s”, message[0]);
printf(message[1]);
1
2
H i \0
T h e r e \0
printf(message[1]);
To get a line at a time:
gets(message[o]) fgets(message[0], 10, stdin)
puts(message[0]) fputs(message[0], stdout)70
Multi dimension array, array of stringsset on the fly for int i=0…3
scanf(“%s”,message[i]);
printf(“%s”, message[0]);
0
1
H e l l o \0
H i \0p ( , g [ ])
printf(message[1]);
To get a line at a time: gets(message[0]) fgets(message[0], 10, stdin)
1
2
H i \0
T h e r e \0
scanf(” %[^\n]s”, message[0]);
To print a string puts(message[0]) fputs(message[0], stdout)
71
Be careful the ‘\n’
33
Multi dimension array, array of stringsset in general Some very import functions
you might want to know
0
1
2
H e l l o \0
H i \0
T h e r e \0
To get from another string (literal) <string.h> strcpy(message[o], “hello”)
str[] = “Hi”; strcpy(message[1], str);
T h e r e \0
Defined in standard library, prototype <stdio.h> sprintf(message[2], “%s there!”, ”hi”); “hi there” sprintf(message[3], ”%s %d %f”, “john”,12,2.3);
sscanf(message[3], “%s %d %f”, name, &age, &wage );
72
String library functions
Defined in standard library, prototype <string.h>
unsigned int strlen() t ti ‘/0’ not counting‘/0’
strcpy() strcpy(toStr, fromStr); strncpy(toStr,fromStr,n)
strcat() strcat(s1, s2); s1s2strcat() strcat(s1, s2); s1s2 strncat (s1, s2, n)
int strcmp() strcmp(s1, s2); 0 if equal strncmp(s1,s2,n)
73
34
character library functions Defined in standard library, prototype <ctype.h>
i t i l h (i t h) t int isalpha(int ch) return non-zero, zero
int isdigit(int ch)
int isalnum(int ch)
int islower(int ch)
int isupper(int ch)
int tolower(int ch)
int toupper(int ch)
74
Utility library functions Defined in standard library, prototype <stdlib.h>
d bl f( i ) double atof(‘string’ s)
int atoi(‘string’ s)
long atol (‘string’s)
int rand(void) void srand(unsigned seed)
void abort(void)
void exit() EXIT SUCESS EXIT FAILURE void exit() EXIT_SUCESS, EXIT_FAILURE
int system(commandString)
int abs(int)
memloc, calloc, free 75
35
void say(char *path)
{
char buf[1024];
sprintf(buf, “aplay ./sounds/%s &", path);
system(buf);
}}
void initializeHardware(void)
{ /* initialize hardware */
if(connect_robot(1, MODEL_SCOUT2, "/dev/ttyUSB0", 38400) == FALSE){
(void) fprintf(stderr,"reactived: unable to connect to robot hardware\n");
say(“sth_wrong.wav");
exit(1);
}
enableSonars();
say(“wakingUp.wav”);
} 76
Diagnostics library functions Defined in standard library, prototype <assert.h>
id t(i t i ) void assert(int expression)
int x = -1;
assert(x > 0)print Assertion failed: expression, file file, line
lnumi f 20 i i `i 5'
Then abort()
Look at <time.h>
77
a.out: sprintf.c:20: main: Assertion `i < 5' failed.
Abort
36
math library functions Defined in standard library, prototype <math.h>
Need to link by -lm
double sin(x), cos(x), tan(x)
double asin(x) acos(x) atan(x) …
exp(x) ex
log(x) ln(x)
log10(x) log10(x)
pow(x,y)int
sqrt(x)
ceil(x), floor(x)
78
Some complier options
Option: ‐llibraryp y
Link with object library gcc main.c –lm
Links math object library (if use pow() round() sin()etc)
Don’t forget to use #include <math.h> at the beginning
79
37
80