cpp-best-practices/cppbestpractices

use ? operator

robertramey opened this issue · 4 comments

// Better Idea
const std::string somevalue = [&](){
    if (somecase()) {
      return "Value A";
    } else {
      return "Value B";
    }
  }();

// Better Idea
const std::string somevalue =  somecase()) ? "Value A" :  "Value B";
      return "Value A";

That's true for the simple case, but falls apart for more than one choice or more complex choices. I was just trying to keep the example simple.

I'll make an update to it.

const std::string somevalue = 
    somecase() ? 
        "Value A" 
   :  somecase2()  ?
        "Value B"
   :
       "Value C";

I'm just not seeing where using lambda will simplify things. But I guess it's a matter of taste

I personally think it's a lot more readable to not use the ?: but regardless, in the tests I've done the compiler is sometimes able to better optimize the lambda version depending on what you are doing. And I've never seen the lambda have worse performance than the nested ternary version

The only time where I've actually chained ternary operators was when constexpr required a single return statement:

constexpr const char* SomeEnumToString(Enum val) {
    return val == kEnumOption1 ? "Option 1" :
           val == kEnumOption2 ? "Option 2" :
           val == kEnumOption3 ? "Option 3" :
           "Invalid Option";
}

That's a similar scenario to the one mentioned before, but I think I would still prefer not to rely on that if only for the problems it presents to automatic formatting tools.