Optimize ternary operator

后端 未结 6 1976
野的像风
野的像风 2021-02-03 18:49

I came across this code written by someone else. Is this usage of the conditional operator recommended or commonly used? I feel it is less maintainable - or is it just me? Is th

6条回答
  •  抹茶落季
    2021-02-03 19:37

    Common or recommended? No.

    I did something similar, but I had my reasons:

    1. It was an argument into a third-party C function.
    2. I was not well versed in modern C++ at the time.
    3. I commented and formatted the f*** out of it because I knew SOMEONE besides me was going to read it...or I needed to know what it was doing years later.
    4. It was DEBUG CODE that was never going into a release.

      textprintf_ex(gw->GetBackBuffer(), font, 0, 16, WHITE, -1, "BUTTON: %s",
                             //If...                        Then Display...
                        (ButtonClicked(Buttons[STOP])    ?  "STOP"
                      : (ButtonClicked(Buttons[AUTO])    ?  "AUTO" 
                      : (ButtonClicked(Buttons[TICK])    ?  "TICK"
                      : (ButtonClicked(Buttons[BLOCK])   ?  "BLOCK"
                      : (ButtonClicked(Buttons[BOAT])    ?  "BOAT"
                      : (ButtonClicked(Buttons[BLINKER]) ?  "BLINKER"
                      : (ButtonClicked(Buttons[GLIDER])  ?  "GLIDER"
                      : (ButtonClicked(Buttons[SHIP])    ?  "SHIP"
                      : (ButtonClicked(Buttons[GUN])     ?  "GUN"
                      : (ButtonClicked(Buttons[PULSAR])  ?  "PULSAR"
                      : (ButtonClicked(Buttons[RESET])   ?  "RESET"
                      :  /*Nothing was clicked*/            "NONE"
                      )))))))))))
                   );
      

    The only reason I did not use an if-else chain was it would have made the code immense and harder to follow because all I needed to do was print a word to the screen.

提交回复
热议问题