ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
int global = 100;
int *getGlobal() {
    return &global;
}
int main() {
    int *p = getGlobal();
    *p = 200;
    printf("%d %d", global, *getGlobal());
}
  1. A. 200 200
  2. B. 100 100
  3. C. 200 100
  4. D. 100 200

Correct answer: A. 200 200

Unlike a local variable, global has static storage duration and lives for the whole program, so returning its address is always safe. Modifying *p changes global itself (200), and a fresh call to getGlobal() still returns the same address, so *getGlobal() also reads 200.

More C Programming questions

Exams that ask this topic