90 דק׳

פונקציות וזימון

למה פונקציות עוזרות, איך זימון שולח ארגומנט ומקבל ערך בחזרה, אב טיפוס, זימון והגדרה, ותוכנית שלמה שעוקבים אחריה שורה אחר שורה.

למצגתלקריאה באתרבאנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

Why functions help

A charging station checks the voltage of three batteries. The safety rule is the same for each one: the voltage must be between 12000 and 14500 millivolts. Without functions, the rule is typed three times:

if (v1 >= 12000 && v1 <= 14500) {
    safe1 = 1;
}
if (v2 >= 12000 && v2 <= 14500) {
    safe2 = 1;
}
if (v3 >= 12000 && v3 <= 14500) {
    safe3 = 1;
}

Now the station manager changes the upper limit to 14400. You must find and edit three places, and it is easy to miss one.

A function (פונקציה) is a block of code with a name that does one job. We write the rule once, inside a function called is_safe, and use it three times:

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

is_safe gives back 1 when the voltage is safe and 0 when it is not. Change the rule once, inside the function, and every use gets the corrected rule.

You already use functions: printf and scanf are functions that someone else wrote. In this unit you write your own.

A function is a named job

Each function has an input and a result. Four functions from the software of a charging station:

JobFunctionInputResult
Sensor conversionadc_to_voltage(raw)raw ADC countvolts
Safety decisionis_voltage_safe(mV, temp)measurements0 or 1
Controller settingcharge_current_ma(mV)battery voltagecurrent limit
Report actionprint_status(code)fault codea printed message

The first three calculate a value and give it back. The last one performs an action: it prints, and gives nothing back. The next lesson looks at this difference.

One call, step by step

Using a function is called a call (זימון). Here is the smallest example:

int answer = square(6);
int square(int x)
{
    return x * x;
}

Three things happen:

  1. The call sends the value 6. A value sent in a call is an argument (ארגומנט).
  2. The function receives it in x. A variable that receives an argument is a parameter (פרמטר). During this call, x holds 6. The function computes x * x, which is 36.
  3. return sends 36 back. The result is the return value (ערך מוחזר). The assignment stores it in answer.

The code that makes the call is the caller (הקורא). Here the caller is main.

Step through the call: 6 travels from the call into x, the function computes 36, and 36 travels back into answer.לפתיחה במסך מלא

Prototype, call and definition

Every function appears in three places in the file:

PieceExampleWhat it does
Prototype (אב טיפוס)int square(int x);Tells the compiler the name and the types before main uses the function. Ends with a semicolon.
Callanswer = square(6);Runs the function with the argument 6.
Definition (הגדרת פונקציה)int square(int x) { return x * x; }Holds the work: the header and the body.

The first line of the definition is the header: the return type (int), the name (square) and the parameters in parentheses (int x). The prototype and the definition must use the same return type, name and parameter types.

The usual order in the file is:

  1. the #include directive
  2. the prototypes
  3. main
  4. the function definitions

The compiler reads the file from top to bottom. The prototype tells it about square before main uses it. If you put the whole definition above main, you do not need a prototype, because the compiler has already seen the function. In this course we keep main near the top and use prototypes.

A complete program

Here is the whole program. Type it in Visual Studio and run it with Ctrl+F5.

#include <stdio.h>
 
int square(int x);
 
int main(void)
{
    int answer = square(6);
    printf("%d\n", answer);
    return 0;
}
 
int square(int x)
{
    return x * x;
}
36

Follow the computer:

  1. The program always starts in main.
  2. int answer = square(6); calls square with the argument 6. main stops and waits.
  3. Control jumps to the definition of square. The parameter x gets 6.
  4. return x * x; computes 36 and sends it back.
  5. Control returns to the line of the call. answer stores 36.
  6. printf prints 36, and return 0; ends the program.

The definition of square sits below main, but it runs in the middle of main: a function's code runs only when it is called, and control comes back to the caller when it returns.

Click through the run: watch the highlighted line jump into square and back, and the memory on the right gain and lose the frame of square.לפתיחה במסך מלא

Test with different arguments

A function works for every argument; only the value of the parameter changes. Test it with a normal value, with zero, and with a negative value:

CallResultWhy this test
square(6)36a normal value
square(0)0zero
square(-4)16a negative value: minus times minus is plus
Choose an argument and watch it go through square. Predict square(-4) before you click it.לפתיחה במסך מלא

Use the returned value

A function can compute the right value while the program stays wrong, because the caller throws the value away. Tom's function clamp_high keeps a value at most 100:

int clamp_high(int value)
{
    if (value > 100) {
        return 100;
    }
    return value;
}

value starts as 150. Compare two callers:

clamp_high(value);          /* ignored: value stays 150 */
printf("%d\n", value);      /* prints 150 */
 
value = clamp_high(value);  /* stored: value becomes 100 */
printf("%d\n", value);      /* prints 100 */

In the first version the function returns 100, but nobody stores it, so the 100 is lost. Only the caller can store a returned value, with an assignment.

Key words

EnglishHebrewMeaning
functionפונקציהa named block of code that does one job
callזימוןrunning a function by its name: square(6)
argumentארגומנטthe value sent in the call
parameterפרמטרthe variable that receives the argument
return valueערך מוחזרthe result sent back to the caller
callerהקוראthe code that calls the function
prototypeאב טיפוסthe name and types, before main, ending with ;
definitionהגדרת פונקציהthe header and the body with the work

Practice

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