C Functions
A function is a named block of code that does one job. You have used functions from the start: main, printf, scanf. Writing your own lets you name a job, use it many times and keep each part of the program small enough to understand.
Defining and calling a function
A function definition gives the type of the value it returns, its name, its parameters in brackets and its body. Calling it runs the body.
#include <stdio.h>
void greet(void) {
printf("Hello from a function!\n");
}
int main(void) {
greet();
greet();
return 0;
}Hello from a function! Hello from a function!
void before the name means the function returns nothing; void in the brackets means it takes nothing.
Returning a value
A function can compute a value and give it back with return. The call then stands for that value.
#include <stdio.h>
int square(int x) {
return x * x;
}
double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
int main(void) {
printf("square(6) = %d\n", square(6));
int s = square(3) + square(4);
printf("3*3 + 4*4 = %d\n", s);
printf("average = %.2f\n", average(81, 77, 90));
return 0;
}square(6) = 36 3*3 + 4*4 = 25 average = 82.67
return ends the function at once. A function that returns a value must reach a return on every path; with -Wall the compiler warns when it might not.
A function with a decision
#include <stdio.h>
int isPrime(int n) {
if (n < 2) return 0;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) return 0;
}
return 1;
}
int main(void) {
printf("Primes below 30:");
for (int n = 1; n < 30; n++) {
if (isPrime(n)) printf(" %d", n);
}
printf("\n");
return 0;
}Primes below 30: 2 3 5 7 11 13 17 19 23 29
Why use functions?
- Reuse: write the code once, call it many times.
- Readability:
if (isPrime(n))reads like a sentence; the details are hidden in the function. - Testing: a small function with one job is easy to check on its own.
- Teamwork: different people can write different functions.
A good rule: if a block of code needs a comment to say what it does, it may want to be a function with that name.
Practice exercises
- Write
int maximum(int a, int b)and use it to find the largest of three numbers. - Write
double celsiusToFahrenheit(double c)and print a table from 0 to 100 degrees in steps of 10. - Write
void printLine(int n)that printsndashes, and use it to draw a box. - Write
int digitSum(int n)that adds up the digits of a number.