Local Variables variables which are declared within a function are LOCAL to the function They can only be used within the piece of code of the function. formal parameters are ALSO local to a function formal parameter (local as well) double circle_area(double radius) { double area; area = PI * radius * radius; return area; } local variable From a function, we only get the return value Everything else is forgotten once we are done with the execution of the function However, ... (see later the use of & and *) 142 G -1
An Example #include<stdio.h> #include<stdlib.h> int addone(int val); int main(void) { int a = 1; int b; b = addone(a); printf("a=%i, b=%i",a,b); return EXIT_SUCCESS; } int addone(int a) a = a + 1; return a; a (local to main) is the actual parameter in the call of addone a (formal parameter) is local to addone (nothing to do with a in main!) What is printed by printf? a=1, b=2 142 G -2
Memory Organization Before b=addone(a); After b=addone(a); main a b 1 main a b anything main a b 1 2 1 anything 2 X addone a addone a addone a 2 X 1 Not available Not available Call by VALUE 142 G -3
Using functions: an example Computing the area of a washer: outer_radius inner radius area = area of outer circle - area of inner circle Algorithm: 1) User inputs the inner and outer radius 2) compute the area of the washer (use a function to compute the area of a circle) 3) Display the washer area 142 G-4
Static Call Graph main washer_area scanf printf circle_area 142 G-5
Local Variables: Summary Formal parameters and variables declared in a function are LOCAL to it cannot be accessed by other functions allocated (created) on function entry De-allocated (destroyed) on function return Formal parameters are initialized by copying the values of the actual parameters. Call BY VALUE A GOOD IDEA! localize information reduce interactions 142 G-6