How to pass arguments to functions
Pass values by value
C copies each argument into its parameter. Changing a scalar parameter does not change the caller's variable.
int twice(int value)
{
value *= 2;
return value;
}
Use a pointer to modify
Pass a valid object address when a function must update caller-owned data. Check a pointer before dereferencing when null is permitted.
bool increment(int *value)
{
if (value == NULL) {
return false;
}
++*value;
return true;
}
Pass array length separately
An array parameter becomes a pointer; the function cannot recover the array length with sizeof. Always pass the element count.
int sum(const int values[], size_t count)
{
int total = 0;
for (size_t i = 0; i < count; ++i) {
total += values[i];
}
return total;
}
Express read-only access
Use a pointer to const when the function reads caller data without modifying it. State who owns memory and how long it must remain valid.