If I want to round an unsigned integer to the closest smaller or equal even integer, can I divide by 2 then multiply by 2?

The compiler is allowed to make any optimisiations it likes so long as it does not introduce any side effects into the program. In your case it can’t cancel the ‘2’s as then the expression will have a different value for odd numbers.

x / 2 * 2 is evaluated strictly as (x / 2) * 2, and x / 2 is performed in integer arithmetic if x is an integral type.

This, in fact, is an idiomatic rounding technique.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)