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");
}
}- A. error
- B. Undefined behaviour: result is used uninitialised
- C. 5
- 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
- Assume 32-bit int. What is printed? c int x = 3; int result = x++ + x++ - x++; printf("%d", result); printf(" valid: %s", "no, undefined…
- What is printed? c int main(void) { int a[3] = {1, 2, 3}; int b[3] = {1, 2, 3}; printf("%d", a == b); }
- What is printed? c int main(void) { char a[] = "test"; char b[] = "test"; printf("%d %d", a == b, strcmp(a, b) == 0); }
- What is printed? c int main(void) { int x = 100; long y = x; long long z = y 1000000000L; printf("%lld", z); }
- What is printed? c int main(void) { int n = 5; int result = 1; int i = 1; while (i <= n) { result = i; i++; } printf("%d", result); }
- Assume 32-bit int. What is printed? c int a = 4, b = 7; int max = (a > b) ? a : b; int min = (a < b) ? a : b; printf("%d %d %d", max, min…