>And why cant i just assign values to ia and ib.
All function arguments are passed by value, this means that a copy is made of the original and you change the copy in the function:
Code:
#include <stdio.h>
int f ( int copy )
{
copy++;
}
int main ( void )
{
int i = 5;
f ( i );
printf ( "%d\n", i );
return 0;
}
Since i is passed by value, the copy is incremented by one, but i remains unchanged. The output of this program is 5.
Now, one can simulate pass by reference and modify the original object by passing it as a pointer:
Code:
#include <stdio.h>
int f ( int *copy )
{
*copy++;
}
int main ( void )
{
int i = 5;
f ( &i );
printf ( "%d\n", i );
return 0;
}
The output of this program is 6 because the address of i was passed by value. The pointer in f was a copy of the address of i, so when it increments the object it points to, the value of i changes. This change is obvious when f returns and i has the value of 6.
The scanf family does something similar, to read from input is simple, but if you pass scanf the copy of a variable it will not place the input in the correct place and your copy of i will remain empty:
Code:
#include <stdio.h>
void f ( int copy )
{
copy = 10;
}
int main ( void )
{
int i;
f ( i )
printf ( "%d\n", i );
return 0;
}
The output of this program is undefined, it is dependent on the random value placed in i when you declared it. Let's try this again with the address of i:
Code:
#include <stdio.h>
void f ( int *copy )
{
*copy = 10;
}
int main ( void )
{
int i;
f ( &i )
printf ( "%d\n", i );
return 0;
}
Since you pass the address of i to f, the value of 10 is placed at the address that i rests in. So the output of this program is 10. The scanf family works the same way and for the same reasons.
-Prelude