45 min

Parameters, return and local variables

What happens in memory during a call: stack frames, returning a value or void, parameters that receive copies, trace tables, and local variables that disappear after return.

Every call gets a frame

In the previous lesson, main called square(6) and got 36 back. Now we look at the memory while that happens.

Every function that is running has a stack frame (מסגרת מחסנית): a box in memory that holds its variables.

  1. main has a frame with its variable answer.
  2. The call square(6) puts a new frame on top. The parameter x lives there, with the value 6.
  3. return removes the frame of square. Only the returned value, 36, survives, and main stores it in answer.

All the frames together are the call stack (מחסנית קריאות). The newest frame is on top, and only the top frame is running; the frames below it wait. Visual Studio shows the call stack while you debug: Debug, Windows, Call Stack.

Click through: main's frame, the frame of square pushed on top, then removed by return.Open full screen

Return a value or perform an action

There are two kinds of functions.

A calculation gives back a result that the caller needs:

int is_safe(int voltage)
{
    return voltage >= 12000 &&
           voltage <= 14500;
}
safe1 = is_safe(v1);

An action does something, such as printing, and gives nothing back. Its return type is void (no value):

void print_status(int safe)
{
    if (safe) {
        printf("SAFE\n");
    } else {
        printf("STOP\n");
    }
}
print_status(safe1);

A call to a void function is a statement on its own. There is nothing to store, so x = print_status(safe1); is an error.

Use a return value for a result. Use void when no result must come back. Calculation functions usually do not print: a test can then compare the returned number with the expected one.

Parameters receive copies

What happens when a function changes its parameter? Run this program:

#include <stdio.h>
 
void add_one(int value)
{
    value = value + 1;
    printf("inside: %d\n", value);
}
 
int main(void)
{
    int count = 7;
    add_one(count);
    printf("main: %d\n", count);
    return 0;
}
inside: 8
main: 7

count is still 7. Here is why:

  1. main stores 7 in count.
  2. The call add_one(count) sends the value of count, which is 7.
  3. A new frame is created for add_one. The parameter value is a new box that gets a copy (עותק) of 7.
  4. value = value + 1; changes the copy to 8. count is in another frame, untouched.
  5. The function prints inside: 8 and ends. Its frame is removed, and value with it.
  6. main prints count: 7.

This is called pass by value (העברה לפי ערך): C always copies the argument into the parameter. Changing the parameter changes the copy, never the caller's variable. (Later in the course, pointers give a function a way to change the caller's variable on purpose.)

Step through add_one: the 7 copied into value, value changing to 8 while count stays 7, and the frame of add_one disappearing.Open full screen

A trace table

A trace table (טבלת מעקב) is the written version of the picture. Each row is a moment; each column is a variable or the output.

Stepmain: countadd_one: valueOutput
before the call7not active
inside add_one78inside: 8
after return7gonemain: 7

Two variables can hold the same number without sharing memory. count is 7 in every row.

Same name, two boxes

In the previous lesson we wrote value = clamp_high(value);. Here two different variables have the name value: one in main's frame and one, the parameter, in clamp_high's frame.

  1. main's value is 150.
  2. The call copies 150 into the parameter value, a new box in a new frame. The function returns 100.
  3. Only the assignment value = ... in main changes main's box to 100.

Same name, different boxes. A parameter's name is chosen by the function; the caller's variable can have any name.

Watch the two variables called value: one per frame.Open full screen

Local variables

A variable declared inside a function is a local variable (משתנה מקומי). It is created in the function's frame when the call starts and removed with the frame when the function returns.

int clamp_high(int value)
{
    int limit = 100;
    if (value > limit) {
        value = limit;
    }
    return value;
}
int result = clamp_high(150);

During the call, the frame of clamp_high holds two variables: value (a copy of 150) and limit (100). A parameter is also a local variable: one that starts with a copy of the argument. After return, both are gone. Only the returned 100 survives, because main stores it in result.

The place where a name can be used is its scope (תחום). The scope of a local variable is the block of its function. If main writes printf("%d\n", limit);, Visual Studio stops with:

error C2065: 'limit': undeclared identifier
Step through clamp_high(150): limit is created in the frame, value becomes 100, and both disappear after return.Open full screen

Key words

EnglishHebrewMeaning
stack frameמסגרת מחסניתthe memory of one running call
call stackמחסנית קריאותall the frames, newest on top
pass by valueהעברה לפי ערךthe parameter gets a copy of the argument
copyעותקa new box with the same number
local variableמשתנה מקומיexists only inside its function call
local scopeתחום מקומיwhere a name can be used: the block it is declared in
voidללא ערך מוחזרthe return type of a function that returns nothing
trace tableטבלת מעקבthe value of each variable, step by step

Practice

The full set of questions with answers is on the practice page.