In C , one cannot declare a static const member of a class with a non-integral type. This restriction arises due to the specific design of the C language's static const data member mechanism.
Static const integral data members are typically stored in the code segment (or the read-only data segment) and can be used without memory allocation. However, for non-integral types like double, the compiler typically stores the value in the initialized data segment.
This approach ensures that integral types can be optimized efficiently by being inlined directly where they are used. However, for non-integral types, the compiler cannot guarantee whether it will inline the value or not. This uncertainty can lead to subtle runtime errors if the compiler decides to inline the value in certain instances but not in others.
To address this issue, the C designers included a restriction to ensure that static const members can only be of integral types. This way, programmers can be confident that integral const members are always inlined, allowing for reliable performance and avoiding potential runtime issues.
As a solution, you can declare a non-static function within the class that returns the desired value, as you did in your "Now_Good" example. This approach provides you with the functionality of a constant, while still adhering to the language design for static const members.
The above is the detailed content of Why Can't C Classes Have Non-Integral Static Const Members?. For more information, please follow other related articles on the PHP Chinese website!