Nearby lessons
76 of 124C - Function Arguments
Arguments are the actual values you pass when calling a function, as opposed to the parameters that receive them. Learn the difference, the type-conversion rules, argument evaluation order, and how main receives command-line arguments.
Arguments vs Parameters
The two words describe the same data at different moments:
| Parameter | Argument | |
|---|---|---|
| Appears in | The function definition | The function call |
| Also called | Formal parameter | Actual parameter |
| Is a | Variable name | Value or expression |
| Example | int add(int a, int b) | add(5, x + 2) |
Count and Order Must Match
The compiler checks the count and the types. It cannot check that you got the order right when the types are the same:
Automatic Type Conversion
An argument is converted to the parameter's type. Widening is safe; narrowing silently loses data:
Evaluation Order Is Unspecified
C does not define which argument is evaluated first. Code whose result depends on that order is broken, even if it appears to work:
Passing Arrays and Strings
You pass an array by giving its name, which is already an address. The size must go along as a separate argument:
Passing Addresses
When the function must modify your variable, the argument is &variable:
Command-Line Arguments
main can take two parameters: the argument count and an array of argument strings. argv[0] is always the program name:
Converting Command-Line Arguments
Everything in argv arrives as text. Use atoi or strtol to get numbers:
Variable Argument Lists
printf accepts any number of arguments. You can write such functions too, using <stdarg.h>:
Common Mistakes
- Wrong argument count — caught by the compiler, so easy to fix.
- Wrong argument order — not caught when types match. The commonest silent bug.
- Passing a value where an address is needed —
swap(a, b)instead ofswap(&a, &b). - Forgetting the array size — the function has no way to find the end.
- Relying on evaluation order —
f(i++, i++)is unspecified behaviour. - Not checking
argc— readingargv[1]when none was supplied dereferencesNULL.
argc before touching argv. argv[argc] is guaranteed to be NULL, so reading argv[1] with argc == 1 passes a null pointer straight into atoi — an immediate crash. Check the count, print a usage line, and return non-zero.- Parameters are in the definition; arguments are in the call.
- Argument count and order must match the parameters.
- An argument is converted to the parameter type, possibly losing data.
- The order in which arguments are evaluated is unspecified.
- main(int argc, char *argv[]) receives command-line arguments.