Are multiple conditional operators in this situation a good idea?

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

    The conditional operator version is clean, simple, and it's immediately obvious to anybody who knows C or C++ what is happening. Its other virtue is that it returns a value immediately, which means it can be put in the initialization (like this example is).

    A switch statement would be more clumsy. It would require that the variable be declared and then initialized, usually a bad idea if it can be avoided. It would take more typing, and would have more places for bugs to creep in. It wouldn't be as clear, since it would be necessary to look at each case to see that it said something like new_vehicle = foo; break;.

    If you're going to do this look up here only, then having the conditional version right there is good, as it immediately shows what's happening. If it's going to occur more than once, consider putting it in a function, so that there's only one place to update if anything changes (such as, say, 'R' for carriage or 'L' for helicopter).

提交回复
热议问题