Step 1 of 7
Define and call a function
As programs grow, putting everything in main gets messy fast. A function packages a piece of work under a name, so you can write it once and use it (call it) wherever it's needed. You've been calling functions all along: printf and scanf are functions someone else wrote.
A function definition has four parts:
int square(int x) {
return x * x;
}
- Return type (
int): the type of value the function hands back. - Name (
square): how you call it. - Parameters (
int x): inputs, each with a type and a name. Inside the function,xis a variable holding whatever value the caller passed. - Body: the code between the braces.
returnends the function and sends a value back.
#include <stdio.h>
int square(int x) {
return x * x;
}
int main(void) {
int a = square(7);
printf("%d\n", a);
printf("%d\n", square(3) + square(4));
return 0;
}
49
25
What happens during a call
When main reaches square(7), it pauses. The value 7 is copied into the parameter x, the body of square runs, and return x * x sends 49 back. The call square(7) is then replaced by that value, so int a = square(7); stores 49, and main carries on. A call is an expression, so it can be used anywhere a value can, like inside printf or another calculation.
Function steps on this site
From now on, some steps are function steps: you write only the function, and hidden tests call it with many different inputs and check what it returns. Don't write a main on those steps (the tests bring their own), and don't print anything the task didn't ask for; the tests look at the return value.
Your turn: complete add so it returns the sum of its two parameters.