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?

  1. A1 20
  2. B10 1
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. When the function f above is called three times in a row, which of the following is the return value of the third call?
  2. In C, which of the following correctly pairs the lifetimes of (1) a local variable declared inside a function without static, (2) a region allocated with malloc, and (3) a variable declared outside any function?
  3. int is 32 bits (maximum 2147483647). Which of the following is the largest n for which the function fact(n) above returns the factorial of n correctly, without overflow?
  4. int is 4 bytes and pointers are 8 bytes. When the value (address) of a pointer to int p is 0x1000, which of the following is the value of p + 3?
  5. int is 4 bytes and pointers are 8 bytes. Which of the following is the output when the program above is executed?