ProgrammingHardProduct-company MCQ pattern
What happens when this runs?
What happens when this runs?
int main(void) {
int arr[3];
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
}- A. 0 0 0, since local arrays are always zero-initialised
- B. Undefined behaviour: arr is an uninitialised automatic array; every element has an indeterminate value
- C. Garbage values, but guaranteed to be the same three values on every run
- D. Compile-time error: arr must be initialised
Correct answer: B. Undefined behaviour: arr is an uninitialised automatic array; every element has an indeterminate value
Automatic (non-static, local) arrays are not zero-initialised unless explicitly given an initializer; each element holds an indeterminate value from whatever was previously in that stack memory. Reading any of them before writing is undefined behaviour, and the values may differ between runs, compilers, or optimisation levels.
More C Programming questions
- What happens when this runs? c void f(int p) { free(p); p = 10; } int main(void) { int x = malloc(sizeof(int)); f(x); printf("done"); }
- What happens when this runs? c int compute(int a, int b) { int result; if (a > b) { result = a - b; } return result; } int main(void) {…
- What happens when this runs? c int makeArray(void) { int local[10]; for (int i = 0; i < 10; i++) local[i] = i; return local; } int…
- What happens when this runs? c int arr[5] = {1, 2, 3, 4, 5}; int p = arr; int val = p[-1]; printf("%d", val);
- What happens when this runs? c int global; int main(void) { printf("%d", global); }
- 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) {…