Yes, building a C++ binary with the -O3 flag can potentially change the results of your float operations.
The -O3 flag enables the compiler's optimizer to perform more aggressive optimizations, which can include reordering or combining floating-point operations. However, this can lead to differences in the results due to the non-associative nature of floating-point arithmetic.
According to the GCC documentation:
"The -O3 option may also enable other optimizations that are not valid for all standard-conforming programs, such as reordering floating-point operations to reduce rounding error accumulation."
The IEEE 754 floating-point standard specifies that floating-point operations should be performed in a specific order, but compilers may reorder these operations to improve performance. This can lead to differences in the results, especially when dealing with operations that involve rounding or cancellation.
As noted in the C++11 standard (section 5.4):
"The order of evaluation of the operands of any operator, including the order of evaluation of the operands of the + operator, is unspecified."
To mitigate these issues, you can use the following options:
-ffloat-store: This option forces the compiler to store floating-point values in memory after each operation, which can help reduce rounding errors.
-fexcess-precision=standard: This option tells the compiler to follow the IEEE 754 standard for floating-point operations, which can help reduce differences in results.
-O2 or lower optimization levels: Using a lower optimization level can reduce the likelihood of the compiler reordering or combining floating-point operations.
Keep in mind that these options may impact performance, so you should carefully evaluate the trade-offs for your specific use case.
Sources: