C: Function Basics

🗓 Last updated: 2026-11-30👤 Written by: Gray✓ Reviewed by: Dana🏷 Category: C Tutorial

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.

Reference entries in this section: int void return break

1. Function Definition

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

C
// Function definition
int add(int a, int b) {
    // Return result
    return a + b;
}

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

C
// Function definition
int get_value(void) {
    // Return result
    return 42;
}

2. Function Calling

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

TEXT
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
// Variable declaration
int x = add(add(1, 2), add(3, 4));

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


3. Parameters and Return Values

(1) 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
// Function definition
int square(int n) {
    // Return result
    return n * n;
}

// Function definition
int main(void) {
    // Variable declaration
    int x = 5;
    // Variable declaration
    int y = square(x);
    // Return result
    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
// Function definition
void try_change(int n) {
    n = 100;
}

// Function definition
int main(void) {
    // Variable declaration
    int x = 5;
    try_change(x);
    // I/O operation
    printf("%d\n", x);
    // Return result
    return 0;
}

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

(2) Return Values

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

C
// Function definition
double circle_area(double r) {
    // Return result
    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
// Function definition
int max(int a, int b) {
    // Conditional check
    if (a > b) {
        // Return result
        return a;
    }
    // Return result
    return b;
}

4. 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
// Function definition
int add(int a, int b);

// Function definition
int main(void) {
    // Variable declaration
    int result = add(3, 5);
    // Return result
    return 0;
}

// Function definition
int add(int a, int b) {
    // Return result
    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
// Function definition
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).


5. void Functions

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

C
// Function definition
void print_line(int len) {
    // Variable declaration
    int i;
    // For loop
    for (i = 0; i < len; i++) {
        // I/O operation
        printf("-");
    }
    // I/O operation
    printf("\n");
}

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

C
// Function definition
void greet(int hour) {
    // Conditional check
    if (hour < 0 || hour > 23) {
        // Return result
        return;
    }
    // Conditional check
    if (hour < 12) {
        // I/O operation
        printf("Good morning\n");
    } else {
        // I/O operation
        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:

▶ Try it Yourself
TEXT
3 is odd
4 is even
7 is odd
8 is even
11 is odd
16 is even

6. 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) {
    // Conditional check
    if (score >= 90) return "Excellent";
    // Conditional check
    if (score >= 80) return "Good";
    // Conditional check
    if (score >= 60) return "Pass";
    // Return result
    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.


7. Multi-Parameter Functions

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

C
// Function definition
double bmi(double weight, double height) {
    // Return result
    return weight / (height * height);
}

Arguments are matched to parameters by position:

C
// Variable declaration
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):

▶ Try it Yourself
TEXT
106 days apart

▶ Example 3: Sum Array via Function

▶ Try it Yourself

输出:

TEXT
Sum = 150

Reference entries in this section: int void return break

❓ 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

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

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