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?
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 ofT” will be converted (“decay”) to an expression of type “pointer toT“, and the value of the expression will be the address of the first element of the array.So given a declaration like
whenever the expression
aappears 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 ofa[0], regardless of whether the expression is being passed to a function or not.So in a function call like
the expression
ais 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[]andT a[N]are interpreted asT *a; the parameter is being declared as a pointer, not an array, regardless of the array notation.