Find maximum of three number in C without using conditional statement and ternary operator

前端 未结 13 1998
日久生厌
日久生厌 2020-11-29 22:25

I have to find maximum of three number provided by user but with some restrictions. Its not allowed to use any conditional statement. I tried using ternary operator like bel

13条回答
  •  孤独总比滥情好
    2020-11-29 23:14

    UPDATE: Looking at this 4 years later, I see that it fails badly if two or more of the values happen to be equal. Replacing > by >= changes the behavior, but doesn't fix the problem. It might still be salvageable, so I won't delete it yet, but don't use this in production code.


    Ok, here's mine:

    int max3(int a, int b, int c)
    {
        return a * (a > b & a > c) +
               b * (b > a & b > c) +
               c * (c > a & c > b);
    }
    

    Note that the use of & rather than && avoids any conditional code; it relies on the fact that > always yields 0 or 1. (The code generated for a > b might involve conditional jumps, but they're not visible from C.)

提交回复
热议问题