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
This is terrible code.
While it is often desirable to initialize a variable with a single expression (for example, so we can make it const
), this is no excuse to write code like this. You can move the complex logic into a function and call it to initialize the variable.
void
example(const int a, const int b)
{
const auto mything = make_my_thing(a, b);
}
In C++11 and later, you can also use a lambda to initialize a variable.
void
example(const int a, const int b)
{
const auto mything = [a, b](){
if (a == b)
return MyThing {"equal"};
else if (a < b)
return MyThing {"less"};
else if (a > b)
return MyThing {"greater"};
else
throw MyException {"How is this even possible?"};
}();
}