Um, do you know pointers? I'll assume you do ^o^
There are two ways to pass argument. Pass-By-Value and Pass-By-Reference.
Maybe you are usually using pass-by-value.
#include <stdio.h>
void foo(int i)
{
printf("[foo] `i` was %d\n", i);
i++;
printf("[foo] Now `i` is %d\n", i);
}
int main()
{
int i = 0;
printf("[main] `i` was %d\n", i);
foo(i);
printf("[main] Now `i` is %d\n", i);
}
Output is: (live example)
[main] `i` was 0
[foo] `i` was 0
[foo] Now `i` is 1
[main] Now `i` is 0
Yes, the i
of main()
is not changed! Why?
Because i
is passed by value. When foo(i)
runs, the value of i
is copied and foo
use the copy, not original i
. So it cannot be changed.
However, you've seen the function which changes argument - for example, scanf
.
int main()
{
int i = 0;
scanf("%d", &i); /* `i` is changed!! */
}
How can it be changed? Because scanf
uses pass-by-ref. Look at this example.
#include <stdio.h>
void foo(int *pi)
{
printf("[foo] `i` was %d\n", *pi);
(*pi)++; /* please be careful ^o^ */
printf("[foo] Now `i` is %d\n", *pi);
}
int main()
{
int i = 0;
printf("[main] `i` was %d\n", i);
foo(&i);
printf("[main] Now `i` is %d\n", i);
}
Output is: (live example)
[main] `i` was 0
[foo] `i` was 0
[foo] Now `i` is 1
[main] Now `i` is 1
How is it possible? Because we passed the pointer of i
, not the copy of i
. foo
has the pointer of i
, so it can access the i
, which main
has. We call it pass-by-reference.
I hope that it can help you!