Search code examples
ccalling-convention

C (not C++) pass by value/reference interview question


I've got a list of questions I like to ask to probe a candidates C skills for embedded systems programming. One of the standard questions I have, which is also on a lot of public question lists is this but I'm starting to think it's a bad question:

"Explain or contrast pass-by-value and pass-by-reference in C"

I tell the interviewee that the question has nothing to do with C++ references and I'm looking for an explanation of passing a pointer to a variable vs. a variable and how the callee can modify the variable referenced by the pointer. Extra points for explanation about how passing pointers to structs is more efficient.

Here's the question: is there really "pass by reference" in C?

The signature of the callee clearly defines what's being passed. It's not like you can pass either x or &x to a function and have the compiler figure out what to do. So I would argue that everything is C is pass by value and pass-by-reference is really just passing the value of a pointer.

Is there something fundamentally different about

void f(int *xarg);
...
int x;
int *xp = &x;
f(xp);

vs.

f(&x);

Thanks, Andrew


Solution

  • There is no pass by reference in C.

    The closest you can get is pass by pointer, which is actually a pass by value (except that it is the pointer that is copied, not the pointed-to object).

    So, you are correct.