Reputation: 339
I was hoping to convert a constant from degrees to radians (at compile time), so I opted to use a constexpr. However, my program would not compile and so I tried to debug the problem with a few tests. These tests continue to produce errors during compilation.
The problem appears to be correlated with floating point arithmetic when many significant digits are involved.
I tried a quick google search, and I read section 10.4 (Constant Expressions) in Stroustrup's book. Any help would be greatly appreciated. I must be missing something obvious.
Test code:
void testConstantExpressions() {
constexpr double x0 = 1.0;
constexpr double y0 = 2.0;
constexpr double z0 = 4.0;
constexpr double w0 = x0 / (y0 / z0);
std::cout << w0 << std::endl;
constexpr double x1 = 1.0;
constexpr double y1 = 2.2;
constexpr double z1 = 4.0;
constexpr double w1 = x1 / (y1 / z1);
std::cout << w1 << std::endl;
constexpr double x2 = 1.0;
constexpr double y2 = 4.0;
constexpr double z2 = 2.3;
constexpr double w2 = x2 / (y2 / z2);
std::cout << w2 << std::endl;
}
Compiler:
g++ -Wall -c -g -O2 -std=c++11 -frounding-math main.cpp -o main.o
main.cpp: In function ‘void testConstantExpressions()’:
main.cpp:30:32: error: ‘(1.0e+0 / 5.5000000000000004e-1)’ is not a constant expression
constexpr double w1 = x1 / (y1 / z1);
^
main.cpp:36:38: error: ‘(4.0e+0 / 2.2999999999999998e+0)’ is not a constant expression
constexpr double w2 = x2 / (y2 / z2);
^
make: *** [main.o] Error 1
Upvotes: 11
Views: 1583
Reputation: 18954
It's because you specified -frounding-math. You told the compiler you might change rounding mode at runtime, so it can't round at compile time. Did you really mean to?
Upvotes: 6