A function is reusable code that performs a clear task. You have already used library functions such as printf(), strlen(), and sqrt(). Now we define our own functions.
Defining functions
Use returnType functionName to define a function. A function can receive input and return output.
#include <stdio.h>
int larger(int num1, int num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
int main(void) {
printf("%d\n", larger(4, 12));
printf("%d\n", larger(54, 33));
return 0;
}Output:
12
54return gives a result back to the caller and ends the current function call.
KNOWLEDGE QUIZ
Functions without return values
Some functions perform an action without returning a useful result.
#include <stdio.h>
void print_greeting(const char name[]) {
printf("Hello, %s!\n", name);
}
int main(void) {
print_greeting("Alice");
return 0;
}A function declared with void does not return a result; control returns to the caller when the function finishes.
Function calls
When a function is called, the program temporarily jumps into that function. When it finishes, execution returns to the original position. This can be understood through the call stack.
Caller → function → return
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
The following program splits the distance calculation into distance() and the helper function square(). One function can call another so a larger calculation becomes a set of focused steps.
#include <math.h>
#include <stdio.h>
double square(double value) {
return value * value;
}
double distance(double x1, double y1, double x2, double y2) {
return sqrt(square(x2 - x1) + square(y2 - y1));
}
int main(void) {
double x1, y1, x2, y2;
printf("Enter the first point, for example 0, 0: ");
scanf("%lf, %lf", &x1, &y1);
printf("Enter the second point, for example 3, 4: ");
scanf("%lf, %lf", &x2, &y2);
printf("Distance: %.1f\n", distance(x1, y1, x2, y2));
return 0;
}One possible run:
Enter the first point: 0, 0
Enter the second point: 3, 4
Distance: 5.0Nested calls: distance() asks square() twice
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
main()
Every C program starts in main(). Other functions must be declared or defined before they are called.
int main(void) {
printf("Program starts\n");
return 0;
}Write a function that returns an absolute difference
Write absolute_difference(num1, num2) and return the absolute difference.
- Define the function.
- Use if/else to return the non-negative difference.
- Print at least two calls.
Write a prime-checking function
Wrap prime checking in reusable is_prime(n).
- Return false for n <= 1.
- Check factors through sqrt(n).
- Read and report from main() function.
Calculate the day number within a year
Split the work into is_leap, days_in_month, and day_of_year.
- Implement leap-year logic.
- Return each month length.
- Call helpers from day_of_year and main.