C Programming Basics
void f(int x) { x = 10; }
void g(int *p) { *p = 20; }
int main(void) {
int a = 1, b = 1;
f(a);
g(&b);
printf("%d %d\n", a, b);
return 0;
}Which of the following is the output when the program above is executed?
- A1 20
- B10 1
- C10 20
Show answer and explanation
Answer: A. 1 20
Function arguments in C are passed by value: calling f(a) copies the value 1 of a into x. Setting x to 10 inside f changes only the copy, and the caller's a stays 1. g(&b) passes the address of b, so *p = 20 inside g writes to b itself, and b becomes 20. To change a caller's variable inside a called function, a pointer is passed in this way.
- A. Correct. a, passed by value, does not change, and b, whose address was passed, becomes 20.
- B. This is the value obtained by swapping the roles of f and g. f, which receives a value, does not change a, and g, which receives an address, changes b.
- C. Only the parameter x (a copy of a) changes inside f, and a stays 1.