פרמטרים, ערך מוחזר ומשתנים מקומיים
מה קורה בזיכרון בזמן זימון: מסגרות במחסנית, ערך מוחזר או void, פרמטרים שמקבלים עותק, טבלאות מעקב, ומשתנים מקומיים שנעלמים אחרי 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.
mainhas a frame with its variableanswer.- The call
square(6)puts a new frame on top. The parameterxlives there, with the value 6. returnremoves the frame ofsquare. Only the returned value, 36, survives, andmainstores it inanswer.
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.
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: 7count is still 7. Here is why:
mainstores 7 incount.- The call
add_one(count)sends the value ofcount, which is 7. - A new frame is created for
add_one. The parametervalueis a new box that gets a copy (עותק) of 7. value = value + 1;changes the copy to 8.countis in another frame, untouched.- The function prints
inside: 8and ends. Its frame is removed, andvaluewith it. mainprintscount: 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.)
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.
| Step | main: count | add_one: value | Output |
|---|---|---|---|
| before the call | 7 | not active | |
inside add_one | 7 | 8 | inside: 8 |
| after return | 7 | gone | main: 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.
main'svalueis 150.- The call copies 150 into the parameter
value, a new box in a new frame. The function returns 100. - Only the assignment
value = ...inmainchangesmain'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.
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 identifierKey words
| English | Hebrew | Meaning |
|---|---|---|
| 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.