see also: functions, variable scope, pointers
Suppose you want to write a function to exchange the values of two integer variables. It seems like that would be fairly trivial. For example, to swap x and y, you could just create an extra int variable, t, and write code that looks like this:t = x; x = y; y = t;That would certainly work. (Try giving x and y initial values & trace through the code if you don't see why the code works. Note that this approach is similar to what you did for the mandel() function in that programming assignment.)
So, you would probably suppose that you could write a function like this:
void swap (int x, int y) { int t = x; x = y; y = t; }Now, suppose your main() looks like this:
int main(void) { int a = 5; int b = 7; swap( a, b ); printf("a is %d and b is %d\n", a, b); }What will print? If swap works, we expect "a is 7 and b is 5" to print. But what actually happens? When the function swap is called, the values of a and b are passed into the functions. When swap begins, x is initialized to 5 and y is initialized to 7. The values of x and y are swapped...but the values of a and b (in main) are unaffected. The swap function does not work as written above because the arguments were passed 'by value.'
With pointers, we can pass the values 'by reference.' Passing by reference means that we'll pass the addresses of the variables instead of the values. Here's how swap and main should be written:
void swap ( int *px, int *py) { int t = *px; *px = *py; *py = t; } int main(void) { int a = 5; int b = 7; swap( &a, &b ); printf("a is %d and b is %d\n", a, b); }Now, the addresses of the variables a and b are passed into swap. In swap, t is set to the value of 'the data that px points to', which is just the value stored at the address of a, which is 5. Then the value stored at address px is changed to the value stored at address py. This sets a to the value of b. Finally, b is set to the value t, which was the value originally stored at a. So, the values of a and b were swapped.
In the beginning of this course, you were just told that you have to have an ampersand in a scanf statement. Now the reason why the & is necessary should be making more sense. Consider what the scanf function does. It reads input from stdin and puts it into a variable. So, scanf has to have access to that variable. Just as 'swap' needed to have the actual addresses of the variables it was supposed to swap, scanf must have the address of the variable in which it's supposed to place the input. So, if we want to give the variable x an integer value read from stdin, we write: scanf("%d", &x); You need to pass the address of the variable instead of the variable itself.