With integers, C ++ 1 is divisible by 2, reliably equal to 0, and 3/2 = 1, 5/2 = 2, etc.?

There are two vectors of different but related sizes. The larger (2 * RESOLUTION) + INDEX_OFFSET (e.g., 2050), the less simply RESOLUTION (e.g., 1024). I believe this is safe enough to suggest that uint16_t can be used to store a vector index.

Iteration through a larger vector is performed by increasing resultIndex by 2. During each iteration, assignment to a smaller vector in the index (resultIndex - INDEX_OFFSET) / 2 .

In fact, the code is based on the assumption that if INDEX_OFFSET is odd or even, the specified division by 2 will always be rounded down, regardless of architecture. For example, if resultIndex is 0 or 1, then 0 is expected, if it is 2 or 3, then 1 is expected, and so on. Is this a safe assumption within the parameters above?

NB I acknowledge the existence of "Separation of integer types - are the results predictable?" but this does not seem to be an exact match.

+6
source share
1 answer

Yes; this is guaranteed by the language:

[C++11: 5.6/4]: binary operator / gives the quotient, and the binary operator % gives the remainder of dividing the first expression by the second. If the second operand / or % is zero, the behavior is undefined. For integral operands, the operator / gives an algebraic relation with any fractional part discarded; if the factor a/b is representable in the result type, (a/b)*b + a%b is equal to a .

In 3/2 both 3 and 2 are integer operands; the algebraic factor of this operation is 1.5 , and when you drop the fractional part .5 , you get 1 . This is true for your other examples and, well, all other examples.

+15
source

All Articles