Are multiple conditional operators in this situation a good idea?

前端 未结 21 2871
名媛妹妹
名媛妹妹 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:14

    Vehicle new_vehicle = getVehicleByType(arg);
    
    Vehicle getVehicleByType(char arg){
      if (arg == 'B') return bus;
      if (arg == 'A') return airplane;
      if (arg == 'C') return car;
      if (arg == 'T') return train;
      if (arg == 'H') return horse;
      return feet;
    }
    

    I like this better. The nested conditional is clever, but I think this is almost as concise and less likely to confuse a future reader. Sorry if the syntax is off, I'm not doing much C nowadays.

    EDIT: Fixed return type omission noted in comments. thx!

    EDIT: I'm not horrified at your version by the way. I did not exclaim WTF or OMG when i saw it. I just prefer mine a little more :)

提交回复
热议问题