Search code examples
pass-by-reference

Passing by reference and assigning into a variable


I was studying about passing by reference. It made me wonder what would happen in the following example (Written in pseudo-C which supports "by reference"):

int foo(int a) {
    a = 5;
    return a * 2;
}

int main() {
    int a = 1;
    a = foo(a);
    printf("%d",a);
    return 0;
}

What should be printed? if we only did foo(a); without assigning into a then we would get 5. but what would be printed when assigning? should it be 5 or 10?


Solution

  • Since you have a = foo(a); in your main() function, a will contain the result returned by foo(a). foo(a) will always return 10 no matter what a is.

    C does not support pass by reference. Changing a = foo(a); to just foo(a); would mean a would retain the value it had before it was passed to foo(), so it would be 1.

    One variation of C that supports pass by reference is C++. In C++, you could write foo() as:

    int foo(int &a) {
        a = 5;
        return a * 2;
    }
    

    The int &a syntax is used to denote that the parameter will be passed by reference. Now, foo will assign 5 to the referenced variable, but still always return 10.

    In this case a = foo(a); will result in a having the value 10, and foo(a); alone will result in a having the value 5.