Greg is right, but also wrong: C does not have any concept of references, that was introduced with C++ - so you are basically using the wrong terms which can get confusing. What your code is passing are pointers.
The thing you need to remember is that in C all function parameters are
passed by value
- which means that a copy of the variable content is passed, not the actual variable. So anything you do to that value inside the function will not change anything in the outside world:
int foo (int x)
{
printf("Begin foo x = %u\n", x);
x = x * 2;
printf("End foo x = %u\n", x);
return x;
}
int main()
{
int x = 666;
printf("Before call x = %u\n", x);
int y = foo(x);
printf("After call x = %u\n", x);
printf("After call y = %u\n", y);
}
Will give you this:
Before call x = 666
Begin foo x = 666
End foo x = 1332
After call x = 666
After call y = 1332
The changes are made to a copy of the value in the variable and don't affect the outside world.
Think about it: why do that do that? Because it would cause real problems if they didn't! If the actual variable was passed through, (i.e. the parameter was passed by
reference
) you would get this:
int main()
{
int x = 666;
printf("Before call x = %u\n", x);
int y = foo(x);
printf("After call x = %u\n", x);
printf("After call y = %u\n", y);
}
Will give you this:
Before call x = 666
Begin foo x = 666
End foo x = 1332
After call x = 1332
After call y = 1332
Which is not a problem at all. But ... what if I do this:
int y = foo(666);
Now
foo
has to change the value of a constant - and that would make code really difficult to understand:
foo(666)
printf("After call 666 = %u\n", 666);
Would have to give you
After call 666 = 1332
So if you can't affect the outside world when you pass a variable into a function, what do you do when you need to return two or more values?
Simple: you pass the address of a variable as a
pointer
to the variable! The function gets a copy of the pointer, which is fine - but the function can now change the value of the variable by using the pointer, which is the address of the variable.
int foo (int x, int* py)
{
printf("Begin foo x = %u, y = %u\n", x, *py);
x = x * 2;
*py = *py + 1;
printf("End foo x = %u, y = %u\n", x, *py);
return x;
}
int main()
{
int x = 666, y = 100;
foo(x, &y);
printf("After call x = %u, y = %u\n", x, y);
}
Will give you:
Begin foo x = 666, y = 100
End foo x = 1332, y = 101
After call x = 666, y = 101
Now go back to your code and look at what is happening!