C ++ operation size_t with negative operand

So, there are three values ​​that a module operation can give you:

Then:

-7% 5 = 3 (math, remainder> = 0)

-7% 5 = -2 (C ++)

-7% (size_t) 5 = 4 (C ++)

Another example:

-7% 4 = 1 (math, remainder> = 0)

-7% 4 = -3 (C ++)

-7% (size_t) 4 = 1 (C ++)

When the left operand is positive, the answer between all three methods is the same. But for negative values, everyone seems to have their own methods. How is the value of module operations calculated in unsigned operands computed in C ++?

+4
source share
1 answer

This is what happens when you mix signed and unsigned values ​​- confusion!

[C++14: 5.6/2]: * / ; % . .

. ( , size_t , int, ):

[C++14: 5/10]: , , . , , . , :

  • (7.2), ; , .
  • long double, double.
  • , , double.
  • , float, float.
  • (4.5) .61 :
    • , .
    • , , .
    • , , , .
    • , , .
    • , .

, -7 std::numeric_limit<size_t>::max() + 1 - 7 ( , ), . , , 1.

+9

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


All Articles