36
In C language, parameters and arguments are closely related concepts in function calls, but they have distinct roles:
Parameters:
- Variables defined within a function’s declaration, acting as placeholders for values that will be provided when the function is called.
- They specify the types of data the function expects to receive.
- They are local to the function, meaning they only exist within its scope.
Arguments:
- Actual values or expressions passed to a function when it’s called.
- They are assigned to the corresponding parameters within the function.
- They can be variables, literals, or expressions from the calling code.
Key Differences:
- Scope: Parameters are local to the function, while arguments belong to the calling code’s scope.
- Timing: Parameters are defined when the function is declared, while arguments are provided when the function is called.
- Role: Parameters define the function’s interface, while arguments provide the specific input for each call.
Example:
C
int add(int x, int y) { // x and y are parameters
return x + y;
}
int main() {
int a = 5, b = 3;
int sum = add(a, b); // a and b are arguments
printf("Sum: %d\n", sum);
}
Explanation:
- The
add
function has two parameters,x
andy
, which act as placeholders for the values it will add. - In
main
, the values ofa
andb
are passed as arguments to theadd
function when it’s called. - Within
add
, the argumentsa
andb
are assigned to the parametersx
andy
, respectively. - The calculation
x + y
is performed using the values provided by the arguments. - The result (8) is returned from
add
and stored in thesum
variable inmain
.