Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional initialization of a const variable

Tags:

People also ask

How do you initialize a const?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

Do const variables need to be initialized?

A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration.

Why a constant must be initialized when it is declared?

When a variable is declared as const it means that , variable is read-only ,and cant be changed . so in order to make a variable read only it should be initialized at the time it is declared.

Can const be redefined?

const cannot be updated or re-declared This means that the value of a variable declared with const remains the same within its scope.


The following base code is part of a quite large procedure:

int x = foo();
if (x == 0) x = bar();

x is not modified anywhere else, so I'd can do:

const int x = foo() == 0 ? bar() : foo();

But foo() is a very expensive and complex function so I can't call it twice due to performance and to the fact that it may generate a race condition and therefore obtain different values (it may involve reading external resources).

I'd like to make code as readable and, if possible, short, as possible. One option is to:

const int foo_ = foo(), x = foo_ == 0 ? bar() : foo_;

On the other hand, I'd like to avoid that kind of temporal variable mainly because foo() may depend on external resources, so using foo_ as a cached value in the rest of the code is not valid.

I'm posting the solution I'm using right now but I'd like to know if there are better options (none or few code cluttering, no temporal variables in the same scope, readability...). Thanks in advance!

PS: it must follow at least the C++11 standard, since it belongs to a cross-platform project.

I know it may be opinion based, but given the previous statements about simplicity (not cluttering code) and avoiding temporal variables (not for readability but for code safety), I'd like to know options to solve this problem.