ProgrammingHardTCS NQT · Infosys pattern

What happens when this runs?

What happens when this runs?
int global;
int main(void) {
    printf("%d", global);
}
  1. A. Undefined behaviour: global is uninitialised
  2. B. 0, since global (file-scope, static-duration) variables are zero-initialised by default
  3. C. Garbage value, same as an uninitialised local
  4. D. Compile-time error: global must be explicitly initialised

Correct answer: B. 0, since global (file-scope, static-duration) variables are zero-initialised by default

Unlike automatic (local) variables, objects with STATIC storage duration (file-scope or static locals) that have no explicit initializer are guaranteed by the C standard to be zero-initialised before main() even starts running. global reliably prints 0, with no undefined behaviour at all here.

More C Programming questions

Exams that ask this topic