Functions, parameters, and return values
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Why functions
- A function is a named piece of work. You write it once and call it whenever you need it.
- Functions keep programs short and clear, and let you build big jobs from small ones.
- You have already used
printf— a function from<stdio.h>. Now you write your own.
Parameters and return values
- The values you pass in are the parameters. The value you hand back is the return value.
int max2(int a, int b)takes twointparameters and returns oneint.return x;ends the function right away and givesxback to the caller.
void functions, and building big from small
- A function that returns nothing has the return type
void. It does work but hands back no value. - One function can call another.
max3can callmax2twice to do its job. - Small functions that each do one thing are easier to read and to fix.
C copies your arguments
- When you call a function, C gives it a copy of each argument.
- So changing a parameter inside the function does not change the caller's variable.
- Keep this in mind — in a later lesson, pointers let a function reach the original.
#include <stdio.h>
void try_double(int x) {
x = x * 2; // changes only the COPY
}
int main(void) {
int n = 5;
try_double(n);
printf("%d\n", n); // still 5 — the original did not change
return 0;
}
Now you try
- Write each function with the exact name and parameters shown, and
returnthe right value. - You may call one of your functions from another.
- Do not write a
main— the checker provides one.
Write int max2(int a, int b) returning the larger of two numbers, and int max3(int a, int b, int c) returning the largest of three. Make max3 call max2. Do not write a main.
Click Run to see the output here.
Complete int power(int base, int exp) so it returns base raised to exp (assume exp >= 0). Use a loop. power(2, 10) is 1024. Do not write a main.
Click Run to see the output here.
Complete int clamp(int x, int lo, int hi) so it keeps x within [lo, hi]: return lo if x is below lo, hi if x is above hi, otherwise x. Do not write a main.
Click Run to see the output here.