Are multiple conditional operators in this situation a good idea?

前端 未结 21 2909
名媛妹妹
名媛妹妹 2020-12-15 06:23

I just saw this block of code on the Wikipedia article on conditional operators:

Vehicle new_vehicle = arg == \'B\' ? bus      :
                      arg ==         


        
21条回答
  •  心在旅途
    2020-12-15 07:11

    There's a lot of whitespace around the character constants that makes it a bit hard to read. I'd parenthesize the comparisons: (and maybe move the last value in line.)

    Vehicle new_vehicle = (arg == 'B') ? bus      :
                          (arg == 'A') ? airplane :
                          (arg == 'T') ? train    :
                          (arg == 'C') ? car      :
                          (arg == 'H') ? horse    :
                                         feet;
    

    Now it looks great.

提交回复
热议问题