Function arguments (also known as parameters) are the values passed to functions when they are called. They allow functions to process input data and return output. In C, you can pass arguments to a function by value or by reference.
The syntax for function arguments is defined in the function declaration and definition. Arguments are enclosed in parentheses after the function name.
return_type function_name(argument1, argument2, ...) { // Function body return value; // optional }
Here, argument1, argument2, ...
are the parameters that the function takes as input when it is called.
#include// Function declaration with arguments void add(int a, int b) { printf("Sum: %d\n", a + b); } int main() { int x = 5, y = 3; add(x, y); // Calling function with arguments return 0; }
add()
takes two arguments, a
and b
, and prints their sum when called from main()
.
Function arguments can be categorized into two types:
In pass-by-value, the actual value of the argument is passed to the function. Changes made to the argument inside the function do not affect the original value.
#includevoid updateValue(int num) { num = num * 2; // This change will not affect the original variable in main printf("Updated value inside function: %d\n", num); } int main() { int a = 10; updateValue(a); printf("Original value in main: %d\n", a); // Output will still be 10 return 0; }
updateValue()
tries to modify num
, but since it's passed by value, the change won't affect the original variable a
in main()
.
In pass-by-reference, instead of passing the actual value, the address (or reference) of the variable is passed to the function. Changes made to the argument inside the function will affect the original value.
#includevoid updateValue(int *num) { *num = *num * 2; // Changes will affect the original variable in main printf("Updated value inside function: %d\n", *num); } int main() { int a = 10; updateValue(&a); // Passing the address of a printf("Original value in main: %d\n", a); // Output will be 20 return 0; }
updateValue()
takes the address of a
and modifies its value inside the function. The change will be reflected in main()
because the function modifies the value at the address.
In C, you cannot specify default values for function arguments directly, unlike some other programming languages. However, you can use function overloading (not directly supported in C but achievable through different function names or macros) or use variable-length arguments (variadic functions).
&
operator when passing variables by reference (e.g., &a
for a variable a
).Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!