Now that we have a basic understanding of how variables in the main() function are stored in the stack, what happens if we introduce new variables in a different function? How do the variables in various functions interact with one another in the computer’s memory?
In the following video, we will explore how functions and their variables interact with memory:
If you cannot see this codecast, please click here.
Check Your UnderstandingCheck Your Understanding
1.
Suppose you have defined a function “add” as follows:
int add (int a, int b) {
int sum;
a = 2;
sum = a+b;
return(sum);
}
In your main program, you have declared integer variables a and b and given them the values a = 9 and b = 3. You then call the function add(a,b). What is the value it returns?
I’ll give you a window to try things out in, but you definitely shouldthink this through first by hand before you use the computer to verify your answer. I really want you to think about this first. That’s why you’ll need to write the entire program if you want to use the window below.
Suppose you have defined a function “add” as follows (this is almost the same function as in the previous question):
int add (int a, int b) {
int sum;
a = 10;
sum = a+b;
return(sum);
}
In your main program, you have declared integer variables a and b and given them the values a = 2 and b = 4. You then call the function add(a,b). What is the value of the variable a in your main program after execution of the function add()?
Another window to try things out... As before, I really want you to think about this first. That’s why you’ll need to write the entire program if you want to use the window below.