Contrary to popular belief, initializing a static const integral in the class definition isn't sufficient to generate the necessary definition required by other code. As witnessed by the compilation error reported by the provided code, a separate definition is still mandatory:
#include <algorithm> #include <iostream> class test { public: static const int N = 10; }; int main() { std::cout << test::N << "\n"; std::min(9, test::N); // Error: Undefined reference to `test::N' }
This problem stems from std::min's parameter taking mechanism: it captures values by const reference. If it took by value, no separate definition would be needed.
Though defining the static const member outside the class fixes the issue, there's a better solution: using the constexpr keyword. This eliminates the need for a separate definition and handles other edge cases.
class test { public: static constexpr int N = 10; };
The above is the detailed content of Why Do Static Const Integer Members Require Separate Definitions in C ?. For more information, please follow other related articles on the PHP Chinese website!