ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
#define SAFE_DIV(a, b) ((b) != 0 ? (a) / (b) : 0)
int main(void) {
int x = 10, y = 0;
printf("%d", SAFE_DIV(x, y));
}- A. Undefined behaviour: division by zero still occurs
- B. 0
- C. 10
- D. Compile-time error: cannot divide by a variable that might be zero
Correct answer: B. 0
SAFE_DIV(x, y) expands to ((y) != 0 ? (x) / (y) : 0). The ternary operator only evaluates ONE branch: since y != 0 is false, the division (x)/(y) is never actually performed at all, so there's no division-by-zero UB here — the macro safely returns 0 instead.
More C Programming questions
- What is printed? c #if 1 #define VALUE 100 #elif 0 #define VALUE 200 #else #define VALUE 300 #endif printf("%d", VALUE);
- What is printed? c #define ISPOSITIVE(x) ((x) > 0) #define ISNEGATIVE(x) ((x) < 0) #define ISZERO(x) ((x) == 0) int classify(int n) { if…
- Assume a 64-bit LP64 ABI. What is printed? c int findMax(int arr, int n) { int maxPtr = arr; for (int i = 1; i < n; i++) if (arr[i] >…
- Assume a 64-bit LP64 ABI. What is printed? c int binarySearch(int arr, int n, int target) { int lo = 0, hi = n - 1; while (lo <= hi) { int…
- Assume a 64-bit LP64 ABI. What is printed? c int sumArray(int arr, int n) { if (n == 0) return 0; return arr + sumArray(arr + 1, n - 1); }…
- Assume a 64-bit LP64 ABI. What is printed? c int compareInts(const void a, const void b) { int ia = (const int )a; int ib = (const int )b…