I just learned that the rounding behavior of the division operator was not defined before C++ 11. The solution is to use std::div
. (Safely round to next smaller multiple)
My programs always assumed that /
would just truncate the fractional part. As a quick fix, I'd like to include an assertion so that I get at least an error if someone would compile on a platform which has a different rounding behavior.
Will assert(3 / 2 == 1)
or static_assert(3 / 2 == 1)
do the job? Or will those constants be optimized away by a compiler-internal arithmetic which might be different from what the machine actually does?
"I just learned that the rounding behavior of the division operator was not defined before C++ 11". That's not true if both arguments are positive integers.
3 / 2 == 1
is a compile time constant expression with value true
, so that code will compile as assert(true)
.
Consider using static_assert
for a compile-time assertion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With