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));
}
  1. A. -2
  2. B. Undefined behaviour: result is never assigned on this path (a > b is false) and is returned uninitialised
  3. C. 2
  4. 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

Exams that ask this topic