With c++ integers, does 1 divided by 2 reliably equal 0, and 3/2 = 1, 5/2 = 2 etc.?

StackOverflow https://stackoverflow.com/questions/14282989

  •  15-01-2022
  •  | 
  •  

Pergunta

There are two vectors of differing, yet related sizes. The larger is (2 * RESOLUTION) + INDEX_OFFSET (e.g. 2050) and the smaller is simply RESOLUTION (e.g. 1024). I believe it safe enough to assume that uint16_t can be used to contain the vector index.

Iteration through the larger vector is performed by incrementing resultIndex by 2. During each iteration, an assignment is made to the smaller vector at the index (resultIndex - INDEX_OFFSET) / 2.

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

N.B. I acknowledge the existence of 'Dividing integer types - Are results predictable?' but it does not seem to be an exact match.

Foi útil?

Solução

Yes; this is guaranteed by the language:

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

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top