ProgrammingHardTCS NQT · Infosys pattern
What happens when this runs?
What happens when this runs?
int x;
printf("%d", x);- A. 0, since C always zero-initialises local variables
- B. Undefined behaviour: x is an uninitialised automatic variable with an indeterminate value
- C. Compile-time error: x must be initialised before use
- D. Garbage value, but always the same on every run of the same binary
Correct answer: B. Undefined behaviour: x is an uninitialised automatic variable with an indeterminate value
Automatic (local, non-static) variables are NOT zero-initialised in C; x holds whatever indeterminate bit pattern happened to be in that stack memory. Reading an uninitialised variable like this is undefined behaviour, not just 'garbage but deterministic' — it may even appear to change between runs or optimisation levels.
More C Programming questions
- What happens when this runs? c char p; { char buf[20] = "hello"; p = buf; } printf("%s", p);
- What happens when this runs? c int a[5] = {1, 2, 3, 4, 5}; a[5] = 100; printf("%d", a[5]);
- What happens when this runs? c int p = NULL; printf("%d", p);
- What happens when this runs? c int p = malloc(sizeof(int)); free(p); printf("%d", p);
- What happens when this runs? c int f(void) { int x = 5; return x; } int g(void) { int y = 10; return &y; } int main(void) { int p = g()…
- What happens when this runs? c char buf[5]; strcpy(buf, "hello world"); printf("%s", buf);