Functions & Parameter Passing
Functions are modular, reusable code units. C evaluates parameters in a strictly top-down sequence, making function prototypes important.
1 Function Prototypes (Declarations)
C compilers parse code files from top to bottom. If you call a function in your `main()` method that is defined lower down in the file, the compiler will throw an error. To prevent this, place a **Function Prototype** (a declaration of the function's name, parameters, and return type) at the top of the file before `main()`, and define the function body below.
2 Pass-by-Value vs. Pass-by-Reference (Using Pointers)
C strictly executes **Pass-by-Value** for all function calls. To modify a variable's value outside the function, you must pass its address (pointer reference) instead of its value:
- Pass-by-Value: Passing standard parameters copies the value. The original variable remains unchanged.
- Pass-by-Reference (Simulated): Passing pointer addresses allows the function to modify the original variable via dereferencing.
C — Functions and Parameter Passing
▶ Run Code
#include <stdio.h>
// Function prototype declarations
void changeValueVal(int x);
void changeValueRef(int *x);
int main() {
int score = 50;
changeValueVal(score);
printf("After pass-by-value: %d\n", score); // Remains 50
changeValueRef(&score);
printf("After pass-by-reference: %d\n", score); // Updated to 100
return 0;
}
// Function definitions
void changeValueVal(int x) {
x = 100;
}
void changeValueRef(int *x) {
*x = 100; // Modifies the original variable via dereferencing
}
3 Code Challenge
Challenge: Write a utility function called `swap` that accepts two integer pointers and swaps their values in memory. Declare two integers in `main()`, call `swap`, and print their values to confirm the swap succeeded.