ProgrammingHardTCS NQT · Infosys pattern
What happens when this runs?
What happens when this runs?
int global;
int main(void) {
printf("%d", global);
}- A. Undefined behaviour: global is uninitialised
- B. 0, since global (file-scope, static-duration) variables are zero-initialised by default
- C. Garbage value, same as an uninitialised local
- 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
- What happens when this runs? c void fillBuffer(char buf, int size) { for (int i = 0; i <= size; i++) { buf[i] = 'A'; } } int main(void) {…
- What happens when this runs? c int a = 5; int b = a++ + a++ + a++; printf("%d %d", a, b);
- What happens when this runs? c struct Point { int x, y; }; struct Point p = malloc(sizeof(struct Point)); printf("%d", p->x);
- What happens when this runs? c char concat(const char a, const char b) { char result[100]; strcpy(result, a); strcat(result, b); return…
- What is printed? c int a = 5, b = 2, c = 3; int result = a > b > c; printf("%d", result);
- What is printed? c int a = 1, b = 2, c = 3; int result = a == 1 && b == 2 || c == 100; printf("%d", result);