C and C ++ can work on different architectures and machine types. Therefore, they can have different representations of numbers: two complements, and the complement of Odessa is the most common. In general, you should not rely on a specific view in your program.
For unsigned integer types ( size_t , which is one of them), the C standard (and, it seems to me, standard C ++) defines exact overflow rules. In short, if SIZE_MAX is the maximum value of type size_t , then the expression
(size_t) (SIZE_MAX + 1)
0 guaranteed, and so you can be sure that (size_t) -1 is equal to SIZE_MAX . The same is true for other unsigned types.
Please note that this is true:
- for all unsigned types,
- even if the base machine does not represent the number in Two additions. In this case, the compiler must verify that the identifier is true.
In addition, this means that you cannot rely on specific views for signed types.
Edit: to answer some of the comments:
Say we have a piece of code, for example:
int i = -1; long j = i;
Assignment j has type conversion. Assuming that int and long are of different sizes (most [all?] Of 64-bit systems), the bit patterns in memory locations for i and j will be different because they have different sizes, the Compiler ensures that the values โโof i and j are -1 .
Similarly, when we do:
size_t s = (size_t) -1
Type conversion occurs. -1 is of type int . It has a bit pattern, but it does not matter for this example, because when the conversion to size_t occurs due to a throw, the compiler will translate the value according to the rules for the type ( size_t in this case), Thus, even if int and size_t are of different sizes, the standard ensures that the value stored in s above is the maximum value that size_t can take.
If we do this:
long j = LONG_MAX; int i = j;
If LONG_MAX greater than INT_MAX , then the value in i is determined by the implementation (C89, section 3.2.1.2).