Why Functions?
- Structure (procedural style)
- Libraries (e.g. stdio, stdlib)
- Recursion
Question
Is a programming language more powerful with additional
If not, which concept we know makes a difference?
What are Functions?
- sub-programs with
local variables
return value
- main is also a function
int main(int argc, char** argv);
Functions in C
- programs - set of functions
- no nested functions (unlike PASCAL)
Function Declaration - Syntax
return_type function_name(type_param1 param1, ..., type_paramN paramN) {
/*
local declarations
*/
/*
body of the function
*/
return some_value;
}
Example: return type int
float plus(int i, float f) {
float sum; /* local variable */
sum = i+f;
return sum;
}
Example: return type void
void printInt(int i) {
printf("%i\n",i); /* no return */
}
Scoping Rule
Prototypes
The order of the function declarations matters:
#include<stdio.h>
int f2() {
f1();
printf("f2!\n");
}
int f1() {
printf("f1!\n");
}
int main() {
f2();
}
We need prototypes for backward calls:
#include<stdio.h>
/* prototype for f1, declares its name
and type for the rest of the program */
int f1();
int f2() {
f1();
printf("f2!\n");
}
int f1() {
printf("f1!\n");
}
int main() {
f2();
}
Parameter Passing
- parameters:
local variables to the function,
initialized to values from
the calling procedure
(call by value);
- other languages have different
rules: call by reference, copy-in/copy-out,...
Calling Procedure
Calling Stack...
Examples