ProgrammingVery hardProduct company OA
What is printed?
What is printed?
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int calls = 0;
int next(void) { calls++; return calls; }
int main(void) {
int r = MIN(next(), next());
printf("%d %d", r, calls);
}- A. 1 2
- B. 3 3
- C. 1 3
- D. 2 3
Correct answer: B. 3 3
MIN(next(), next()) expands to ((next()) < (next()) ? (next()) : (next())): the condition evaluates next() twice (giving 1 and 2 in some unspecified order), and whichever branch the ternary then picks calls next() a THIRD time for its value. So r is always the third call's return value, 3, and calls ends at 3 regardless of which operand of < was evaluated first.
More C Programming questions
- What is printed? c #if defined(DEBUG) const int mode = 1; #else const int mode = 0; #endif int main(void) { printf("%d", mode); }
- What is printed? c #define ISODD(x) (x % 2 == 1) int main(void) { printf("%d", ISODD(4 - 1)); }
- What is printed? c #define STR(x) #x #define XSTR(x) STR(x) #define VERSION 7 int main(void) { printf("%s %s", STR(VERSION)…
- What is printed? c #define SWAP(a, b) do { int t = a; a = b; b = t; } while (0) int main(void) { int x = 1, y = 2; if (x < y) SWAP(x, y)…
- What is printed? c #define A 1 #define B (A + 1) #undef A #define A 10 int main(void) { printf("%d", B); }
- What is printed? c #define FOO 10 #define BAR FOO + 5 int main(void) { int x = BAR 2; printf("%d", x); }