Learning C Language from Scratch: Chapter 7: Functions and Scope

πŸŽ“ C Language Learning Column | Chapter 7: Functions and Scope – The Art of Organization in C Language

πŸ’¬ “Functions are like departments in a company,

each function only does what it is good at, and does not interfere with others.”

πŸ“Œ Chapter Navigation

Module You Will Understand
What is a function The “division unit” of a C program
Function definition and calling How to declare, pass parameters, and return
Variable scope The “life and death boundary” of variables inside and outside functions
Lifetime and storage types The differences between auto / static / extern
Return values and void functions Usage tips for different types of functions

1. Why do we need functions?

Imagine a world without functionsπŸ‘‡οΌš

#include <stdio.h>

int main(void) {
    printf("Enter two numbers:");
    int a, b;
    scanf("%d %d", &a, &b);
    int sum = a + b;
    printf("The sum is: %d", sum);
}

It doesn’t seem complicated, but if you want to calculate the average, difference, product…

You will quickly find that the code turns into a pile of spaghetti.

Thus, C language introduces “functions” as an organizational tool.

πŸ“˜ Each function is like an “independent little machine”,

input data β†’ processing β†’ output results.

2. The basic structure of a function

A function consists of three parts:

return_type function_name(parameter_list) {
    // function body
    return return_value;
}

Example:

int add(int x, int y) {
    int sum = x + y;
    return sum;
}

Usage:

int main(void) {
    int result = add(3, 4);
    printf("Result: %d\n", result);
}

πŸ“Œ add() function:

β€’

Takes two integers;

β€’

Calculates their sum;

β€’

Returns an integer.

3. The difference between function declaration and definition

Before using a function, the compiler must know its “signature”.

βœ… Method 1: Define before use (the simplest)

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

int main(void) {
    printf("%d", add(2,3));
}

βœ… Method 2: Declare before define (recommended)

int add(int, int); // Declaration

int main(void) {
    printf("%d", add(2,3));
}

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

πŸ“Ž Declaration tells the compiler what the function looks like,

definition tells it how the function works.

4. Scope: The “active range” of variables

“Scope determines who can see the variable.”

🌿 1. Local Variables

Defined inside a function, can only be used within that function:

void test() {
    int x = 5; // Local variable
    printf("%d", x);
}

Once you leave the function, x disappears.

🌍 2. Global Variables

Defined outside all functions, accessible by all functions:

int count = 0; // Global variable

void add() { 
    count++; 
}
void show() { 
    printf("%d\n", count); 
}

πŸ“Œ Note:

β€’

Global variables are stored in the global data area;

β€’

Lifetime = the entire duration of the program;

β€’

Abusing global variables can make the program hard to maintain (like “everyone in the office sharing one mailbox”).

5. Variable Lifetime (Storage Duration)

In C language, variables not only have “scope”, but also differ in “how long they last”.

Keyword Storage Location Lifetime Default Value
auto Stack Created when the function executes Undefined
static Global area Throughout the program’s runtime 0
extern Global area References external variables Uses externally defined values

🌱 1. auto (default)

void f() {
    int x = 0;  // auto
    x++;
    printf("%d\n", x);
}

Each time you call f(), x becomes 0 again.

🌳 2. static (static variable)

void f() {
    static int x = 0;
    x++;
    printf("%d\n", x);
}

Even if the function ends, x will not disappear.

Multiple calls to f() will output:

1
2
3

πŸ“Œ static allows the variable to “remember” the last value.

🌐 3. extern (external variable declaration)

When you want to share a variable across multiple files:

file1.c

int count = 0;

file2.c

extern int count;

extern indicates “this variable is defined in another file”.

6. Function return values and void type

β€’

int func() β†’ returns an integer

β€’

float func() β†’ returns a float

β€’

void func() β†’ does not return any value

void say_hello() {
    printf("Hello C!\n");
}

πŸ“Œ If a function does not return a value, you must write void,

Do not omit it, otherwise the compiler may mistakenly think it will return int.

7. Function calling mechanism (the secret of the stack)

Each time a function is called, the system will:

1.

Allocate space on the stack;

2.

Store parameters and return address;

3.

Release space after the function execution.

πŸ“Š Calling process (taking add(2,3) as an example):

main()
 β”œβ”€β”€ add(2,3)
 β”‚     β”œβ”€β”€ Save parameters x=2, y=3
 β”‚     β”œβ”€β”€ Execute sum = x + y
 β”‚     β”œβ”€β”€ Return sum
 └── main() receives return value

This is why recursive functions need to be careful –

the stack space is limited, too many layers will “overflow the stack”.

8. Good habits for functions

βœ… Each function should do one thing only;

βœ… Function names should be verbs, such as calculateSum();

βœ… Do not have too many parameters (consider using structures if more than 3);

βœ… Do not abuse global variables;

βœ… Remember to write function declarations (especially in multi-file projects).

🧠 Chapter Summary

Concept Description
Function The “organizational unit” of code
Declaration vs Definition The difference between “commitment” and “implementation”
Local Variable Born inside the function, dies outside
Static Remembers the last state
Extern Shares variables across files
Stack Calling Mechanism Function calls are completed on the stack

πŸ“Ž Thinking Exercises

1.

Write a max(a,b) function that returns the larger of two numbers.

2.

Write a count_calls() function that counts how many times it has been called (using static to implement).

3.

Try to split the global variable count into two files, using extern to connect them.

✨ Congratulations!

You now have the ability to build “modular C programs”.

In the next chapter, we will start building “real-world data structures” –

making C programs not only smart but also capable of remembering.

πŸ’‘

If you enjoy this “hardcore yet gentle” learning pace, remember to bookmark the column, and see you in the next chapter!~

Leave a Comment