Search code examples
ctypesref

Which types pass by reference and which by value?


If I pass an int it will be passed by value.
void something(int i)
If I pass some type of array it will be passed by reference.
void something(int i[])
OR void something(int *i);

Types like int will be passed by value, arrays will be passed as reference.

The first question is, are there any more types that will be passed by reference?
The second question is, what is the difference between the first pass of the array (int i[]) and the second one (int *i) ?

EDIT: I will clarify my question. Which other types that you pass to a function, such as arrays, will be changeable inside the function. (which is not exactly pass-by-ref, as you explained).

void something(int i[])
{
i[0]=5;
}

something(i);

This will change the array not only locally.

What about structs? unions? A pointer to them passes too?


Solution

  • Everything is passed by value, period.

    The difference is in how C treats array expressions. Except when it is the operand of the sizeof, _Alignof, or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

    So given a declaration like

    int a[10] = {0};
    

    whenever the expression a appears anywhere in your code other than &a, sizeof a, or _Alignof a, it will be converted to a pointer expression and the value of the expression will be the address of a[0], regardless of whether the expression is being passed to a function or not.

    So in a function call like

    foo(a);
    

    the expression a is converted to a pointer expression, and the value of the pointer expression (&a[0]) is passed to the function.

    Similarly, in a function parameter declaration, T a[] and T a[N] are interpreted as T *a; the parameter is being declared as a pointer, not an array, regardless of the array notation.