Thor
Thor

Reputation: 10058

examples of " a variable that can be easily mistaken for a constant variable but is in fact a non-constant variable "

I'm new to C++ and is trying to learn the concept of constant expression. I saw the quote below from C++ primer 5th Edition.

In a large system, it can be difficult to determine (for certain) that an initializer is a constant expression. We might define a const variable with an initializer that we think is a constant expression. However, when we use that variable in a context that requires a constant expression we may discover that the initializer was not a constant expression.

Could someone please give examples of a variable that can be easily mistaken for a constant variable but is in fact a non-constant variable? I want to be aware of the pitfulls of constant and non-constant variables and try to avoid them to the best of my ability.

Upvotes: 0

Views: 78

Answers (1)

Robin Krahl
Robin Krahl

Reputation: 5308

cppreference.com provides a good example for that problem:

// code by http://en.cppreference.com/w/User:Cubbi, CC-by-sa 3.0
#include <iostream>
#include <array>

struct S {
    static const int c;
};
const int d = 10 * S::c; // not a constant expression: S::c has no preceding
                         // initializer, this initialization happens after const
const int S::c = 5;      // constant initialization, guaranteed to happen first
int main()
{
    std::cout << "d = " << d << '\n';
    std::array<int, S::c> a1; // OK: S::c is a constant expression
//  std::array<int, d> a2;    // error: d is not a constant expression
}

Upvotes: 2

Related Questions