C Programming Basics

int f(void) {
    static int s = 0;
    int a = 0;
    s++;
    a++;
    return s * 10 + a;
}

When the function f above is called three times in a row, which of the following is the return value of the third call?

  1. A11
  2. B13
  3. C31
Show answer and explanation

Answer: C. 31

The static local variable s is initialized to 0 only once, before the program starts, and keeps its value after the function returns. So s increases to 1, 2 and 3 with each call. a, without static, is created anew at each call and starts from 0, so it is 1 every time. The return value of the third call is 3 × 10 + 1 = 31.

  • A. This is the value obtained if s also starts from 0 at each call. A static variable keeps its value.
  • B. This is the value obtained by swapping the behavior of the static s and the non-static a (s = 1, a = 3).
  • C. Correct. s increases to 3 and a is 1 every time, so 3 × 10 + 1 = 31.
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. 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?
  2. 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?
  3. 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?
  4. int is 4 bytes and pointers are 8 bytes. Which of the following is the output when the program above is executed?
  5. int is 4 bytes. Which of the following is the output when the code above is executed?