Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert(3 / 2 == 1): Does this work?

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?

like image 490
Michael Avatar asked Jan 08 '23 02:01

Michael


1 Answers

"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.

like image 142
Bathsheba Avatar answered Jan 12 '23 00:01

Bathsheba