ProgrammingHardHCL · Tech Mahindra pattern

What happens when this runs?

What happens when this runs?
int divide(int *result, int a, int b) {
    if (b == 0) return -1;
    *result = a / b;
    return 0;
}
int main(void) {
    int result;
    int status = divide(&result, 10, 0);
    if (status == 0) {
        printf("%d", result);
    } else {
        printf("error");
    }
}
  1. A. error
  2. B. Undefined behaviour: result is used uninitialised
  3. C. 5
  4. D. division by zero crash

Correct answer: A. error

divide() checks for b==0 BEFORE attempting the division, returning an error code (-1) without ever touching *result or performing 10/0. main() checks that status and, seeing it's nonzero, correctly takes the error branch without ever reading the (still uninitialised) result — a well-defined, defensive error-handling pattern.

More C Programming questions

Exams that ask this topic