I have an exam at uni from C and I was looking through the exams from the previous years and I stumbled over this problem:
What is the value of d
after executing the following sequence?
int a=36, b=20, c=30, d;
d = c?(a? a: c):(b? c: b);
There was another exercise like this, but in those parenthesis there were other expressions:
d = (a>b) ? ((a>c)? a: c): ((b>c)? b: c);
I put the 2 codes in ChatGPT and it told me that they are called ternary operators.
I understand that in the second example we are comparing a
with b
, a
with c
, b
with c
, then we are giving d
a value based on the comparisons. But in the first example, there are no comparisons, only variables. Moreover, the test will be on paper, so I won't be able to run the code on a computer. How do I read the syntax of the first example, what does it mean? Am I still comparing the 3 variables, or is it something different?
I ran the codes on CodeBlocks and on VS for both exercises, with the same values (a = 36
, b = 20
, c = 30
), and they both gave me the same answer:
d = (a>b) ? ((a>c)? a: c): ((b>c)? b: c); //d = 36
and
d = c?(a? a: c):(b? c: b); //d was still 36.
I don't understand how did I get that answer from the second exercise.