ProgrammingSystems Programmer

Can you explain in detail the mechanisms of parameter passing in C functions: by value and by pointer? Provide examples of when each approach is justified.

Pass interviews with Hintsage AI assistant

Answer.

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.

Passing by Value

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! }

Passing by Pointer

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! }

When to Use a Pointer

  • You need to return multiple values.
  • Changing large structures (saving time and memory, no copying).
  • Working with arrays (they are always passed as pointers).

Trick Question.

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


In one project, the function updated the values of an array declared as 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.


In another case, due to passing a structure by value to a function, the entire large block of memory was copied several times, causing a performance drop for the application.


The developer expected that passing a scalar by "reference" (through a pointer) would guarantee the immutability of the original value, but mistakenly changed memory outside the scope via the pointer (a pointer arithmetic error), leading to unpredictable results.