Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An interview question on conditional operator

I recently encountered with this question: How to reduce this expression: s>73?61:60;.

The hint given was that Instead of using conditional operator we could use a simple comparison which will work fine.

I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself.

EDIT:The whole expression is this : s-=s>73?61:60

like image 722
whacko__Cracko Avatar asked Aug 08 '26 11:08

whacko__Cracko


1 Answers

Just like the other answers:

s -= (s > 73) + 60;

This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int.

like image 131
Carl Norum Avatar answered Aug 11 '26 04:08

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!