HOME HTML EDITOR C JAVA PHP

C Function Parameters and Arguments

**Parameters** are variables defined in the function's declaration that receive values when the function is called. These values are known as **Arguments**. By using parameters, you can create flexible code that can handle various inputs without changing the internal logic of the function.

1. Parameters vs. Arguments

While the terms are often used interchangeably, there is a technical difference that every professional C programmer should know:

2. Working with Multiple Parameters

You can pass as many parameters as you need, separated by commas. However, when calling the function, the number and order of arguments must match the parameters exactly.

void displayInfo(char name[], int age) {
    printf("Hello %s, you are %d years old.\n", name, age);
}

int main() {
    displayInfo("Alice", 25); // Correct order
    displayInfo("Bob", 30);
    return 0;
}

3. Pass by Value

By default, C uses a method called **Pass by Value**. This means the function receives a copy of the data. If you change the parameter's value inside the function, the original variable in the main() function remains unchanged.

void increment(int x) {
    x = x + 10;
}

int main() {
    int num = 5;
    increment(num);
    printf("%d", num); // Output: 5 (Original value is safe)
    return 0;
}

4. Pass by Reference (Using Pointers)

If you want a function to modify the original variable, you must pass the memory address (using pointers). This is known as **Pass by Reference**. It is highly efficient because it avoids copying large amounts of data.

void realIncrement(int* x) {
    *x = *x + 10; // Modifies the value at the address
}

int main() {
    int num = 5;
    realIncrement(&num); // Pass the address
    printf("%d", num); // Output: 15 (Original value changed!)
    return 0;
}

5. Array Parameters

When you pass an array to a function, C does not copy the entire array. Instead, it passes a pointer to the first element. This is why changes to an array inside a function will affect the original array.

void modifyArray(int arr[]) {
    arr[0] = 99;
}

int main() {
    int myNumbers[3] = {1, 2, 3};
    modifyArray(myNumbers);
    printf("%d", myNumbers[0]); // Output: 99
    return 0;
}

6. Summary of Parameter Handling

Feature Pass by Value Pass by Reference
What is passed? Copy of data Memory address
Original variable Protected/Unchanged Can be modified
Memory usage Higher for large data Lower (very efficient)
Pro Tip: When passing strings to functions, remember they are arrays of characters. Therefore, they are always passed by reference. If you want to ensure the function doesn't accidentally change your string, use the const keyword in the parameter: void printMsg(const char str[]).