DAY10 In-Depth Analysis of C Language Functions: Definition, Calling, Scope, and Parameter Passing

1. Core Value and Design Principles of Functions

1.1 Core Functions

  • Splitting Complex Logic: Break down large problems into smaller, independently implementable functions, reducing development difficulty.
  • Improving Code Reusability: Avoid writing the same logic repeatedly, minimizing redundant code.
  • Facilitating Maintenance and Debugging: Each function focuses on a single task, making problem localization more efficient.

1.2 Design Principles

  • High Cohesion: Each function is responsible for only one specific, logically independent task.
  • Low Coupling: Dependencies between functions should be minimized, with data passed through clear parameters to reduce direct associations.

2. Function Definition and Calling

2.1 Definition Syntax

return_type function_name(type parameter1, type parameter2, ...) {
    function_body; // Code implementing the functionality
    return expression; // Return result (can be omitted for void type)
}

2.2 Key Rules

  • Return Value Type: Supports int, char, short, long, double, float, void (no return value). The default return type is int.
  • Function Naming: Consists of letters, numbers, and underscores; cannot start with a number; should be meaningful.
  • Return Value Limitation: The return type cannot be an array. Code after return is not executed.

Example: Function with no declared return type (defaults to int)

// No return type declared, defaults to int
fun2() {
    return; // Legal, defaults to returning int type
}

2.3 Necessity of Function Declaration

If a function is defined after it is called, it must be declared first (only the function header, without the body), to inform the compiler of the function’s return type, parameter types, and number of parameters.

// Function declaration (ends with semicolon, parameter names can be omitted)
int add(int, int);
int mul(int, int);
int sub(int, int);

int main() {
    int result = add(10, 20); // Declared before call, compiler can recognize it
    return 0;
}

// Function definition (after the call)
int add(int a, int b) {
    return a + b;
}

2.4 Calling Rules

  • Calling Format: function_name(argument1, argument2, ...). Parentheses cannot be omitted even if there are no parameters.
  • Parameter Matching: The types of actual arguments and formal parameters must match or allow implicit conversion; names can be different.
  • Execution Flow: When the calling function (e.g., main) makes a call, the execution flow jumps to the called function. After the called function executes to return, it returns to the calling function to continue execution.

3. Variable Scope and Lifetime

3.1 Scope: The range where a variable can be accessed

(1) Local Variables
  • Definition Location: Inside a function, as function parameters, or within the nearest curly braces where they are defined.
  • Scope: Valid only within the code block where they are defined.
  • Storage Area: Stack area; space is automatically freed when going out of scope.
(2) Global Variables
  • Definition Location: Outside any function.
  • Scope: The entire project, accessible by all .c files.
  • Storage Area: Data area; space is allocated before the program runs and freed after the program ends.
(3) Scope Shadowing (Hiding)

When a local variable has the same name as a global variable, the “nearest principle” applies. The local variable shadows the global variable, making the global variable inaccessible directly.

int global_a = 20; // Global variable

int main() {
    int global_a = 10; // Local variable, shadows the global variable
    printf("%d\n", global_a); // Outputs 10, accesses the local variable
    return 0;
}

3.2 Lifetime: The process from variable memory allocation to deallocation

  • Local Variables: Become active from the point of definition; lifetime ends when the code block ends (corresponding closing brace), and memory is reclaimed.
  • Global Variables: Start from the preparation stage before program execution until the program ends; lifetime is the same as the program’s (global lifetime).

4. Variable Storage Classes

4.1 Common Storage Classes

Storage ClassDescriptionApplicable Scenarios
autoAutomatic variable (default), default for local variablesTemporary variables inside functions
registerSuggests compiler store variable in CPU register for faster accessFrequently used local variables (e.g., loop counters)
externDeclares an external variable/function, indicating its definition is in another source fileAccessing global variables or functions across files
staticStatic variable/function, modifies scope or lifetimeLocal variables needing retained value; global variables/functions with restricted access

4.2 Three Major Roles of the static Keyword

(1) Modifying Local Variables
  • Lifetime becomes global: From program start to end; space is not freed when the code block ends.
  • Scope remains unchanged: Still confined to the code block where it is defined.
  • If not initialized, the system automatically initializes it to 0.
(2) Modifying Global Variables
  • Scope is limited: Only valid within the source file where it is defined; other source files cannot access it (avoids global variable conflicts).
  • If not initialized, the system automatically initializes it to 0.
(3) Modifying Functions
  • Scope is limited: Can only be called within the source file where it is defined; other source files cannot access it.
  • Avoids function name conflicts and improves code security.

4.3 Usage of the extern Keyword

  • Declaring External Functions: Informs the compiler that the function is defined in another .c file; no implementation needed here.
    extern int add(int, int); // Declares that add function is defined elsewhere
    
  • Declaring External Global Variables: Informs the compiler that the variable is defined in another .c file; allows cross-file access.
    extern int GLOBAL_ADD; // Declares global variable GLOBAL_ADD is defined elsewhere
    

5. Two Ways of Function Parameter Passing

5.1 Pass by Value: Transfers only the value, does not modify the original argument

  • Principle: The actual argument copies its value to the formal parameter. The parameter and the argument are independent variables occupying different memory locations.
  • Characteristic: The called function can only read the value of the actual argument; it cannot modify the actual argument itself.

Example: Pass by Value cannot swap variable values

void swap(int a, int b) {
    int t = a;
    a = b;
    b = t;
    printf("Inside swap: a=%d, b=%d\n", a, b); // Outputs 5, 3 (parameters swapped)
}

int main() {
    int a = 3, b = 5;
    swap(a, b); // Arguments a, b pass values to parameters
    printf("Inside main: a=%d, b=%d\n", a, b); // Outputs 3, 5 (arguments unchanged)
    return 0;
}

5.2 Pass by Address/Reference: Can modify the original argument via pointers/arrays

  • Principle: The actual argument passes the memory address of the variable. The formal parameter accesses the memory where the actual argument resides via this address; essentially an “indirect operation” on the actual argument.
  • Applicable Scenarios: Need to modify the actual argument’s value; passing arrays (the array name is essentially the address of the first element).

Example: Array as Parameter (Pass by Address)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void input_array(int a[], int len) {
    srand(time(NULL));
    for (int i = 0; i < len; i++) {
        a[i] = rand() % 50; // Modifies the content of the argument array via address
    }
}

int main() {
    int a[10] = {0};
    int len = sizeof(a) / sizeof(a[0]); // Calculate array length
    input_array(a, len); // Pass the array's starting address (pass by address)
    // Print the modified array
    for (int i = 0; i < len; i++) {
        printf("a[%d] = %d\n", i, a[i]);
    }
    return 0;
}

Note: When an array is used as a function parameter, sizeof(a) returns the pointer size (not the total array size), so the array length must be passed manually.

6. Summary of Key Knowledge Points

  1. Function design follows “high cohesion, low coupling”; avoid implementing multiple functionalities in one function.
  2. Functions must be declared or defined before being called; parentheses cannot be omitted for parameterless functions.
  3. Local variables are stored in the stack (short lifetime), global variables in the data area (long lifetime). Local variables shadow global variables with the same name.
  4. static modifies local variables to extend lifetime; modifies global variables/functions to restrict scope. extern is used for cross-file declarations.
  5. Pass by Value transfers only the value (does not modify the argument). Pass by Address transfers the address (can modify the argument). Passing an array is essentially pass by address.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值