LECTURE 15: Scope of Names (Read Section 6.3, p.296-297)

 

Example 1.

 

#include<stdio.c>

 

int main(void)

{

int a, b;

 

printf(“(%d,%d)\n”,a,b); // will display 2 junk values

a = 5;

b = 10;

printf(“(%d,%d)\n”,a,b); // will display (5,10)

a = strange_function(a,b);

printf(“(%d,%d)\n”,a,b); // will display (0,10)

}

 

int strange_function(int a, int b)

{

printf(“(%d,%d)\n”,a,b); // will display (5,10)

 

b = b – 2*a;

printf(“(%d,%d)\n”,a,b); // will display (5,0)

 

return(b);

}

 

Explanation:

-          upon declaration of a and b in main function, memory is reserved to store values of variables a and b;

-          the values of a and b are based on the current content of these memory locations, which is some junk value;

-          upon call to strange_function, two new memory locations are reserved to hold values of input arguments a and b. Important: these memory locations are going to be reserved until the program exits the strange_function; any changes to values of a and b within strange_function will occur only in these two reserved memory locations – values of a and b from main function will remain unchanged!

-          values of the input arguments a and b are 5 and 10;

-          value of b that is returned by strange_function (b = 0) will be stored in variable a from main function; therefore, the final display will show (0,10)!!

 

Example 2.

 

#include<stdio.c>

 

int main(void)

{

int a, b;

 

printf(“(%d,%d)\n”,a,b); // will display 2 junk values

a = 5;

b = 10;

printf(“(%d,%d)\n”,a,b); // will display (5,10)

a = strange_function(a,b);

printf(“(%d,%d)\n”,a,b);

}

 

int strange_function(int c, int d) // the only difference from Example 1

{

printf(“(%d,%d)\n”,a,b); // Run time error, program will crash!!

 

b = b – 2*a;

printf(“(%d,%d)\n”,a,b);

 

return(b);

}

 

Note: program crashed because strange_function could see only input arguments c and d; variables a and b created in main are not visible by strange_function!!

 

Example 3.

 

#include<stdio.c>

 

int main(void)

{

int a, b;

 

printf(“(%d,%d)\n”,a,b); // will display 2 junk values

a = 5;

b = 10;

printf(“(%d,%d)\n”,a,b); // will display (5,10)

a = strange_function(a,b);

printf(“(%d,%d)\n”,a,b); // will display (-15,10)

}

 

int strange_function(int b, int a) // the only difference from Example 1

{

printf(“(%d,%d)\n”,a,b); // will display (10,5)

 

b = b – 2*a;

printf(“(%d,%d)\n”,a,b); // will display (10,-15)

 

return(b);

}

 

Note: values of b and a in strange_function will be assigned the corresponding values from the function call in the main function (look at p.133-134 from the textbook: Argument list correspondence)!