Functions and scope
Declare functions with prototypes, pass values in, return values out, and respect where variables are visible.
- Write a prototype and a matching function definition.
- Pass arguments in and return a single value out.
- Distinguish local scope from global scope.
- Describe what a header file shares between files.
In plain English
A function is a named block of code that takes inputs and can give back a result. A prototype declares the function signature, which is its return type, name and parameters, so the compiler knows how it is called before it sees the body. Parameters are the inputs a caller passes in, and a return value is what the function hands back. Scope is the region of the program where a name is visible: a local variable declared inside a function exists only while that function runs, while a global variable is visible everywhere in the file. A header file is a text file that holds declarations, usually prototypes, so many source files can share the same interface.
Step by step
- 1Write a prototype above main and the definition below it.
- 2Call the function and print its return value.
- 3Add a local variable and watch it disappear when the function returns.
- 4Add a global variable and read it from a second function.
- 5Move the prototype into a header and include it.
#include <stdio.h>
int add(int a, int b);
int add(int a, int b) {
int sum = a + b;
return sum;
}
int global = 100;
void show(void) {
int local = 5;
printf("local = %d, global = %d\n", local, global);
}
int main(void) {
printf("%d\n", add(2, 3));
show();
return 0;
}Common mistakes
- Calling a function before the compiler has seen its prototype makes the compiler guess the signature and often warn.
- Changing a parameter inside a function does not change the variable the caller passed in, because C passes by value.
- Declaring a variable inside one function and using it in another fails, because local scope ends when the function returns.
- Putting a definition instead of a prototype in a header duplicates the body across files and causes linker errors.
Write a maximum function
Write a prototype and a definition for a function max2 that returns the larger of two ints, then call it and print the result.
int max2(int a, int b);
int main(void) {
printf("TODO\n");
return 0;
}What happens when a function changes one of its parameters?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.