ProgrammingHardIBM · Deloitte pattern
What happens when this runs?
What happens when this runs?
int compute(int a, int b) {
int result;
if (a > b) {
result = a - b;
}
return result;
}
int main(void) {
printf("%d", compute(3, 5));
}- A. -2
- B. Undefined behaviour: result is never assigned on this path (a > b is false) and is returned uninitialised
- C. 2
- D. 0
Correct answer: B. Undefined behaviour: result is never assigned on this path (a > b is false) and is returned uninitialised
When a=3, b=5, the condition a > b is false, so result is never assigned anything on this execution path; it still holds an indeterminate value from the stack. Returning (and the caller printing) that uninitialised value is undefined behaviour, not simply '0' or any other 'safe default'.
More C Programming questions
- 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) {…
- 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);