Home >Backend Development >C++ >Why Can\'t C Classes Have Non-Integral Static Constants?
Non-Integral Static Constants in C Classes: Why Not?
In C , static const members of a class cannot be non-integral types. This behavior may seem puzzling, given that the language allows integral types like int and unsigned.
The Reason
The underlying reason for this restriction lies in optimization considerations. With integral types, the compiler often optimizes by inlining constant values directly into the surrounding code. This eliminates the need for a memory address for these constants, reducing the overhead of variables.
However, for non-integral types like double, the compiler cannot always perform such inlining. This is because operations on non-integral types may require floating-point calculations, which cannot be easily optimized. As a result, the compiler must create a memory address for the constant and access it through a variable.
Example
Consider the following code:
<code class="cpp">class No_Good { static double const d = 1.0; };</code>
Here, the compiler cannot inline the constant d, as double values require floating-point operations. Therefore, it must create a memory address for d, which is disallowed by the C standard.
Solution
To avoid this restriction, you can declare the constant as a function rather than a static member. For example:
<code class="cpp">class Now_Good { static double d() { return 1.0; } };</code>
This allows the compiler to inline the value of d when possible, while still maintaining the semantics of a constant.
The above is the detailed content of Why Can\'t C Classes Have Non-Integral Static Constants?. For more information, please follow other related articles on the PHP Chinese website!