In C, arguments are passed by value. This means that when you pass an argument to a function, a copy of that variable is made. For example
int main()
{
int x = 6;
repchar(x, 'r');
printf("%d\n", x);
return 0;
}
void repchar(int n, char c)
{
while (--n >= 0)
putchar(c);
}
This program prints the letter r six times, and then at the last printf
, prints out 6, not -1. The reason is that when repchar
was called, x
was copied. That way, when repchar
decrements n
, the caller's copy is not changed.
If we passed a pointer, however, n
would be modified.
int main()
{
int x = 6;
repchar(&x, 'r');
printf("%d\n", x);
return 0;
}
void repchar(int *n, char c)
{
while (--(*n) >= 0)
putchar(c);
}
Instead of the variable being copied, now the address of the variable is being copied. Inside of repchar, *n
is being counted down. This accesses the value that is being referenced by n
, which is the same address as x
and decrements it. As a result, the last printf will give -1.