ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int g = 1;
int f(int n) {
    static int s = 10;
    int g = n;
    s += g;
    { extern int g; g += s; }
    return s;
}
int main(void) {
    int a = f(1);
    int b = f(2);
    printf("%d %d %d", a, b, g);
}
  1. A. 11 12 1
  2. B. 11 13 25
  3. C. 11 13 1
  4. D. 11 12 24

Correct answer: B. 11 13 25

s is static, so it is initialised once and keeps its value: 11 after f(1), 13 after f(2). The local g shadows the global inside f, but the inner block re-declares g with extern, which refers to the file-scope object (external linkage), so that block updates the GLOBAL: 1 + 11 = 12, then 12 + 13 = 25. '11 13 1' assumes the inner block modified the local g; '11 12 …' assumes s is re-initialised on every call.

More C Programming questions

Exams that ask this topic