Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there reason we are able to define [static const int] in a class definition, but not other static const types? [duplicate]

Tags:

c++

Possible Duplicate:
Why aren't static const floats allowed?

Is there any reason why this is not possible in C++? It confuses me.

static const int A = 100; //no error
static const float B = 2.0f; //error, can't define this type in class definition.
like image 442
xcrypt Avatar asked Nov 14 '22 12:11

xcrypt


1 Answers

Static constants of integral types can be initialized inside a class definition. That doesn't mean that the object actually exists, since you haven't provided a definition yet, but because the compiler knows the value of the object, you can sometimes get away with it.

That is, if you're not attempting to take the address of the variable or pass it by reference, but only use its value, then you don't need to provide a defintion at all, and the compiler simply substitutes the value wherever you use the variable.

C++11 introduces the constexpr keyword which allows you to do the same for a much wider variety of types.

like image 101
Kerrek SB Avatar answered Nov 16 '22 02:11

Kerrek SB