Function Parameters in C

Function parameters are variables that accept values passed to the function when it is called. They allow functions to process different data each time they are executed.

Key Topics

1. Passing Parameters

Parameters are specified in the function definition and accept values (arguments) when the function is called.

Example: Function with Parameters

void greet(char name[]) {
    printf("Hello, %s!\n", name);
}

int main() {
    greet("Alice");
    greet("Bob");
    return 0;
}

Output:

Hello, Alice!
Hello, Bob!
                

2. Call by Value

In C, arguments are passed to functions by value, meaning a copy of the argument is made.

Example: Demonstrating Call by Value

void increment(int num) {
    num++;
    printf("Inside function: %d\n", num);
}

int main() {
    int value = 5;
    increment(value);
    printf("After function call: %d\n", value);
    return 0;
}

Output:

Inside function: 6
After function call: 5
                

3. Call by Reference

To modify the original variable, pass its address using pointers.

Example: Modifying Variable via Pointer

void increment(int *num) {
    (*num)++;
    printf("Inside function: %d\n", *num);
}

int main() {
    int value = 5;
    increment(&value);
    printf("After function call: %d\n", value);
    return 0;
}

Output:

Inside function: 6
After function call: 6
                

Best Practices

  • Use pointers to pass large structures or arrays to functions to save memory.
  • Use const qualifiers when passing pointers to prevent unintended modifications.
  • Keep parameter lists concise and meaningful.

Don'ts

  • Don't modify the values of parameters unless intended.
  • Don't pass uninitialized pointers to functions.
  • Don't ignore the use of pointers when needed for efficiency.

Key Takeaways

  • Function parameters allow functions to operate on different data.
  • Understanding call by value and call by reference is crucial in C.
  • Pointers enable functions to modify variables outside their scope.