Please explain in easy terms why this code doesnt work: #include <stdio.h> void swap(int…
- User
Please explain in easy terms why this code doesnt work: #include <stdio.h>
void swap(int a, int b);
int main(void) { int x = 1; int y = 2;
printf("x is %i, y is %i\n", x, y); swap(x, y); printf("x is %i, y is %i\n", x, y);}
void swap(int a, int b) { int tmp = a; a = b; b = tmp; }
- Assistant
The code you have doesn't work in terms of swapping the values of
xandybecause of the way C passes arguments to functions. In C, function arguments are passed by value, which means that a copy of the argument is passed into the function rather than the original variable itself. - User
Why do I have to use &x instead of just x in scanf in the following code #include <stdio.h>
int main(void) { int x; printf("x: "); scanf("%i", &x); printf("x, %i", x); }
- Assistant
The reason you have to use
&xinstead of justxin thescanffunction is related to how variables are accessed and modified in C.When you declare
int x;, you are allocating space in memory to hold an integer, andxis the name you use in your program to refer to that location in memory.When you call
scanfwith the%iformat specifier, the function expects to receive the address of an integer variable where it will store the value input by the user. This is becausescanfneeds to modify the variable you provide—it doesn't just read a value, it writes the value read from standard input (usually the keyboard) to the variable.In C, the
&operator is the "address-of" operator, and when you use it with a variable name, like , it gives you the address in memory where that variable is stored. So is the address of the integer variable .