Function Basics

Functions are like recipes in a kitchen -- give them ingredients (parameters), they follow steps to process them, and serve a dish (return value). Encapsulating repeated logic into functions keeps code clean and efficient.

Function Definition

A function definition consists of four parts: return type, function name, parameter list, and function body.

C
int add(int a, int b) {
    return a + b;
}

If there are no parameters, write void in the parameter list:

C
int get_value(void) {
    return 42;
}

Function Calling

To call a function, follow the function name with parentheses and pass arguments:

C
int result = add(3, 5);
printf("%d\n", result);

When called, the program jumps to the function body, executes it, and returns to the call site upon encountering return or reaching the end of the function.

Functions can be nested -- the return value of one function can serve as the argument to another:

C
int x = add(add(1, 2), add(3, 4));

This is equivalent to add(3, 7), resulting in 10.

Parameters and Return Values

Parameters vs Arguments

The variables in the parentheses of a function definition are called parameters (formal parameters). The values passed when calling are called arguments (actual parameters).

C
int square(int n) {
    return n * n;
}

int main(void) {
    int x = 5;
    int y = square(x);
    return 0;
}

n is a parameter, x is an argument. Parameters are local variables within the function; the argument's value is copied to the parameter -- this is "pass by value". Modifying the parameter inside the function does not affect the argument.

C
void try_change(int n) {
    n = 100;
}

int main(void) {
    int x = 5;
    try_change(x);
    printf("%d\n", x);
    return 0;
}

The output is still 5, because n is only a copy of x.

Return Values

A function returns a result to the caller via the return statement. The return type must match the function declaration:

C
double circle_area(double r) {
    return 3.14159 * r * r;
}

A function can return an expression directly without storing it in a variable first. Once return executes, the function ends immediately; subsequent code is not executed:

C
int max(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;
}

Function Declaration (Prototype)

If a function is defined after the point where it is called, the compiler does not recognize the function name and will produce an error or implicitly assume it returns int. The solution is to declare the function prototype before the call:

C
int add(int a, int b);

int main(void) {
    int result = add(3, 5);
    return 0;
}

int add(int a, int b) {
    return a + b;
}

A declaration only includes the header followed by a semicolon; the function body is not needed. Parameter names can be omitted:

C
int add(int, int);

However, keeping parameter names improves readability and is recommended.

💡 Tip: In real projects, function declarations are typically placed in header files (.h), and function definitions in source files (.c).

void Functions

Functions that do not need to return a value use void as the return type:

C
void print_line(int len) {
    int i;
    for (i = 0; i < len; i++) {
        printf("-");
    }
    printf("\n");
}

In a void function, return can be omitted, or return; can be used to exit early:

C
void greet(int hour) {
    if (hour < 0 || hour > 23) {
        return;
    }
    if (hour < 12) {
        printf("Good morning\n");
    } else {
        printf("Good afternoon\n");
    }
}
⚠️ Note: A void function cannot return a value; return 5; will cause a compile error. Similarly, every execution path in a non-void function must have a return with the correct type.

Example

Determine whether an integer is even:

C
#include <stdio.h>

int is_even(int n) {
    return n % 2 == 0;
}

int main(void) {
    int nums[] = {3, 4, 7, 8, 11, 16};
    int i;
    int len = sizeof(nums) / sizeof(nums[0]);

    for (i = 0; i < len; i++) {
        printf("%d is %s\n", nums[i], is_even(nums[i]) ? "even" : "odd");
    }

    return 0;
}
▶ Try it Yourself
TEXT
3 is odd
4 is even
7 is odd
8 is even
11 is odd
16 is even

The return Statement in Detail

A function can have multiple return statements, but only one executes per call. return has two effects:

  1. Return a value to the caller
  2. Immediately terminate function execution
C
const char *grade(int score) {
    if (score >= 90) return "Excellent";
    if (score >= 80) return "Good";
    if (score >= 60) return "Pass";
    return "Fail";
}

The return value is copied to the call site. For basic types (int, double, etc.), the copy overhead is negligible. After a function returns, its local variables no longer exist, so you must not return a pointer to a local variable.

Multi-Parameter Functions

A function can have multiple parameters, separated by commas. The number and types of arguments must match the parameters exactly:

C
double bmi(double weight, double height) {
    return weight / (height * height);
}

Arguments are matched to parameters by position:

C
double result = bmi(70.0, 1.75);
⚠️ Note: When argument and parameter types do not match, the compiler may perform implicit conversion or issue a warning. It is best to keep types consistent.

Example

Calculate the number of days between two dates (simplified version, ignoring leap years and month differences, just demonstrating multi-parameter functions):

C
#include <stdio.h>

int day_of_year(int year, int month, int day) {
    int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int total = 0;
    int m;

    for (m = 1; m < month; m++) {
        total += days_in_month[m];
    }
    total += day;

    return total;
}

int days_between(int y1, int m1, int d1, int y2, int m2, int d2) {
    int first = day_of_year(y1, m1, d1);
    int second = day_of_year(y2, m2, d2);
    int diff = second - first;
    if (diff < 0) diff = -diff;
    return diff;
}

int main(void) {
    int d = days_between(2025, 3, 1, 2025, 6, 15);
    printf("%d days apart\n", d);
    return 0;
}
▶ Try it Yourself
TEXT
106 days apart

❓ FAQ

Q Can a parameter have the same name as an argument?
A Yes, they are variables in different scopes and do not affect each other. However, to avoid confusion, it is recommended to use different names.
Q Can a function omit the return type?
A In C89, omitting the return type defaults to int. C99 and later require an explicit return type. Always specifying the return type is a good habit.
Q What is the use of return; in a void function?
A It is used to exit the function early, skipping subsequent logic. It is similar to break in a loop.
Q Can a function return multiple values?
A A C function can only return one value. To return multiple results, use pointer parameters, structs, or arrays.

📖 Summary

📝 Exercises

  1. Write a function int max3(int a, int b, int c) that returns the largest of three integers.
  2. Write a function void swap_wrong(int a, int b) that attempts to swap two values. Verify in main whether it succeeds, and explain why.
  3. Write a function int digit_sum(int n) that calculates the sum of the digits of a positive integer (e.g., 123 returns 6). Test it in main.
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏