Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way of conditionally initializing a const

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" } ();
like image 971
Vorac Avatar asked Oct 17 '25 22:10

Vorac


2 Answers

C++ Core Guidelines advise to use lambdas for complex initialization, especially of const variables.

like image 178
Grisha Avatar answered Oct 19 '25 11:10

Grisha


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.

like image 27
Vittorio Romeo Avatar answered Oct 19 '25 13:10

Vittorio Romeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!