Parameters: giving a function information
A function can take inputs, called parameters. List them in the brackets, each with its type:
#include <stdio.h>
void greet(int age) {
printf("You are %d years old.\n", age);
}
int main() {
greet(12);
greet(40);
return 0;
}Output
You are 12 years old. You are 40 years old.
When we call greet(12), the value 12 is copied into age and the function runs.
Several parameters are separated by commas:
#include <stdio.h>
void printBox(int width, int height) {
for (int r = 0; r < height; r++) {
for (int c = 0; c < width; c++) {
printf("#");
}
printf("\n");
}
}
int main() {
printBox(5, 2);
printf("\n");
printBox(3, 3);
return 0;
}Output
##### ##### ### ### ###
return: giving back a result
A function can calculate something and return it. Write the type of the result in front of the name instead of void:
#include <stdio.h>
int square(int n) {
return n * n;
}
double average(int a, int b) {
return (a + b) / 2.0;
}
int main() {
int s = square(6);
printf("6 squared is %d\n", s);
printf("Average of 3 and 4 is %.1f\n", average(3, 4));
printf("%d\n", square(2) + square(3));
return 0;
}Output
6 squared is 36 Average of 3 and 4 is 3.5 13
Think of it like this: A function with
returnis like a vending machine: you put something in (the parameters) and it gives you something back (the return value).
return also ends the function immediately. Any code after it in the function doesn't run:
#include <stdio.h>
int isEven(int n) {
if (n % 2 == 0) {
return 1;
}
return 0;
}
int main() {
printf("%d %d\n", isEven(10), isEven(7));
return 0;
}Output
1 0
Common mistake: Calling a function that returns a value but not using the value:
square(6);on its own works out 36 and then throws it away. Store it or print it.