Assert (3/2 == 1): Does it work?

I just found out that the rounding behavior of the division operator was not defined before C ++ 11. The solution is to use std::div. ( Safe rounding to the next smaller size )

My programs always assumed that it /would just crop the fractional part. As a quick fix, I would like to include a statement to get at least an error if someone compiles on a platform that has different rounding behavior.

Will assert(3 / 2 == 1)or static_assert(3 / 2 == 1)do the job? Or will these constants be optimized using internal compiler arithmetic, which may differ from what the machine actually does?

+4
source share
1 answer

"I just found out that the rounding behavior of the division operator was not defined before C ++ 11." This is not so if both arguments are positive integers.

3 / 2 == 1is an expression of a compile-time constant with a value true, so the code will compile as assert(true).

Consider using static_assertcompiler time assertions.

+9
source

Source: https://habr.com/ru/post/1617741/


All Articles