Functions and calls
Why functions help, how a call sends an argument and gets a value back, the prototype, the call and the definition, and a complete program traced line by line.
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:
| Job | Function | Input | Result |
|---|---|---|---|
| Sensor conversion | adc_to_voltage(raw) | raw ADC count | volts |
| Safety decision | is_voltage_safe(mV, temp) | measurements | 0 or 1 |
| Controller setting | charge_current_ma(mV) | battery voltage | current limit |
| Report action | print_status(code) | fault code | a 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:
- The call sends the value 6. A value sent in a call is an argument (ארגומנט).
- The function receives it in
x. A variable that receives an argument is a parameter (פרמטר). During this call,xholds 6. The function computesx * x, which is 36. returnsends 36 back. The result is the return value (ערך מוחזר). The assignment stores it inanswer.
The code that makes the call is the caller (הקורא). Here the caller is main.
Prototype, call and definition
Every function appears in three places in the file:
| Piece | Example | What it does |
|---|---|---|
| Prototype (אב טיפוס) | int square(int x); | Tells the compiler the name and the types before main uses the function. Ends with a semicolon. |
| Call | answer = 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:
- the
#includedirective - the prototypes
main- 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;
}36Follow the computer:
- The program always starts in
main. int answer = square(6);callssquarewith the argument 6.mainstops and waits.- Control jumps to the definition of
square. The parameterxgets 6. return x * x;computes 36 and sends it back.- Control returns to the line of the call.
answerstores 36. printfprints 36, andreturn 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.
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:
| Call | Result | Why this test |
|---|---|---|
square(6) | 36 | a normal value |
square(0) | 0 | zero |
square(-4) | 16 | a negative value: minus times minus is plus |
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
| English | Hebrew | Meaning |
|---|---|---|
| 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.