Home > Blockchain >  Relation between static constant member variables and narrowing conversions in C
Relation between static constant member variables and narrowing conversions in C

Time:10-30

Coding in C 20, using a GCC compiler.

Based on the code shown below, the program will raise a narrowing conversion error/warning due to the int to char implicit conversion. However, if I add static const/constexpr to the int var {92}; line, the program runs without raising any errors/warnings.

  1. Why does this happen?
  2. When should I be using static const/constexpr member variables?
  3. Why are constexpr member variables not allowed?
#include <iostream>

class Foo {
    private:
        int var {92};
    public:
        void bar() {
            char chr {var};
            std::cout << chr << '\n';
        }
};

int main() {
    Foo foo;
    foo.bar();
} 

CodePudding user response:

Why does this happen?

Because list initialization (since C 11) prohibits narrowing conversions.

(emphasis mine)

  • conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in the target type

If you declare var as static const/constexpr, it becomes a constant expression and the value 92 could be stored in char, then the code works fine.

  • Related