Lesson 1 of 8 · Functions and Arrays · 3 min read · Updated
Writing your own functions
Give a piece of work a name, and stop repeating yourself.
You have been using functions since lesson two — printf and scanf are functions someone else wrote. Now you write your own.
#include <stdio.h>
int square(int n)
{
return n * n;
}
int main(void)
{
printf("%d\n", square(5));
printf("%d\n", square(12));
return 0;
}
25
144
Reading a function definition
-
int — the return type
What kind of value the function hands back. Use
voidif it hands back nothing. -
square — the name
How you call it. Name it after what it does, not how it does it.
-
(int n) — the parameters
What it needs to do its job. Inside the function, n is an ordinary variable holding a copy of whatever was passed in.
-
return n * n;
The work, and the answer.
returnboth sends the value back and ends the function immediately.
Step 1 of 4
Arguments are copies
#include <stdio.h>
void try_to_change(int n)
{
n = 99; /* changes the copy only */
}
int main(void)
{
int x = 5;
try_to_change(x);
printf("%d\n", x); /* still 5 */
return 0;
}
Note
C passes arguments by value: the function gets a copy, and changing it does not touch the original. To change the caller's variable you need its address — which is what pointers are for, and why scanf needed that &.
Declare before you use
C reads your file top to bottom. If main calls a function defined below it, the compiler has not met it yet. A prototype at the top solves that.
#include <stdio.h>
int square(int n); /* prototype: signature only */
int main(void)
{
printf("%d\n", square(5));
return 0;
}
int square(int n) /* definition, further down */
{
return n * n;
}
After calling try_to_change(x) where the function sets its parameter to 99, what is x in main?
Create a free account to save your progress, or sign in.