In C, parameters in functions are always passed by value — that is, a copy of the value from the calling code is passed to the function. If you need to change the value of a variable outside the function, you use pointer passing.
When passing a scalar (for example, int), the function gets its copy:
void foo(int a) { a = 10; } int main() { int x = 5; foo(x); // x == 5, will not change! }
To change the value of a variable, use a pointer:
void foo(int* a) { *a = 10; } int main() { int x = 5; foo(&x); // x == 10, value has changed! }
Is an array a function parameter passed by reference?
Many answer "by reference", however, in C, an array in the function signature cannot be passed by reference; it actually degrades to a pointer.
Correct Answer:
When an array is passed to a function, a pointer to its first element is actually passed. This means the called function does not know the actual size of the array, and any changes to the elements of the array are reflected in the original array.
void foo(int arr[]) { arr[0] = 100; } int main() { int a[3] = {1,2,3}; foo(a); // a[0] will be 100! }
History
int arr[10], but in the calling code, the array was of smaller size. Because the function did not know the actual size, a buffer overflow occurred, damaging memory.