#How does condition ? x : y work?

8 messages · Page 1 of 1 (latest)

eternal rampart
#

I received the following question in an interview:
Given the following code, what is the value of y and what is the value of x at the end of the program?

#define min(a, b) a < b ? a : b

int x = 0;
int y = min(x++, 5);

printf("%d %d\n, x, y);

I understand why x will be 2 at the end of the program, since the preprocessor will replace the macro with:

x++ < 5 ? x++ : 5

And x will be incremented twice, but why is y 1? In my head the increments haven't gone off yet when y receives its new value, so it would be 0. What happens behind the scenes?

vivid shuttleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

fiery willow
#

I find such interview questions evil. I have faced such questions and worse, and felt relieved when I didn't get the job.

#

We are programmers. Not compilers.

eternal rampart
upper forge
#

In

x++ < 5 ? x++ : 5

there's a sequence point before ?. Meaning, x++ < 5 will be evalutated fully first before choosing one of the branches. Then, x < 5 is the truth value to choose the branch off of, and before going there, x is incremented by 1. Since x had started with 0, x < 5 is truthful, and x will be 1 before choosing the "true" branch, i.e., x++. Then x's then-value will be what this entire ternary evaluates to, i.e., 1. After that, x will be incremented by 1, i.e., it will be 2.

eternal rampart
#

Aha, that makes sense. Thank you!

#

!solved