What is the preferred way to initialize a const automatic variable? I can think of several.
if
statement(note: later I learned this is UB):
const std::string s;
if( condition ) { const_cast<std::string&>(s) = "first"; }
else { const_cast<std::string&>(s) = "second"; }
?:
operator:
const std::string s = ( condition ) ? "first" : second;
immediately invoked function expression:
const std::string s = [ & ] ()
{ if( condition ) return "first" else return "second" } ();
C++ Core Guidelines advise to use lambdas for complex initialization, especially of const variables.
Your if
statement example does not initialize any const
, as s
is not const
.
Regarding other options (this is mainly subjective), here are my guidelines:
Use the ?:
(ternary operator) when the expression is short and easy to read. In your case, I think it would be fine.
Use a IIFE (immediately invoked function expression) or refactor the initialization to a function which returns a value when the initialization logic is long and complex and when it would negatively impact readability of the function where the variable is initialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With