Gcc: warning: large integer implicitly truncated to unsigned type

#include<stdio.h> int main() { unsigned char c; c = 300; printf("%d",c); return 0; } 

Is the output predictable in any way or is it undefined ??

+6
c ++ c gcc
source share
2 answers

Sorry for the first answer, here is an explanation with C ++ standards :)

Is the output in any way predictable or is it undefined ??

This is predictable. There are two points in this code: First, the assignment of a value that the unsigned char type cannot contain:

 unsigned char c; c = 300; 

3.9.1 Basic types (Page 54)

Unsigned unsigned integers must obey the laws of arithmetic modulo 2n, where n is the number of bits in the value representation of this particular integer size. 41)
...
41) This means that unsigned arithmetic is not overflowing, because the result that cannot be represented by the unsigned integer type is equal to the reduced modulus number, which is one greater than the largest value that the unsigned integer type can represent by the result.

Basically:

 c = 300 % (std::numeric_limits<unsigned char>::max() + 1); 

Second, pass %d to the printf format printf to print the unsigned char variable.
This ysth got this right;) There is no undefined behavior, because the advertising conversion from unsigned char to int occurs in case of variadic arguments !

Please note: the second part of the answer is a rephrasing of what was said in the comments of this answer , but this is not my answer initially.

+10
source share

The result of the appointment should be predictable:

3.9.1

4 Unsigned unsigned integers must obey the laws of arithmetic modulo 2 n where n is the number of bits in the representation of the values โ€‹โ€‹of this particular integer size. 17)

17) This means that unsigned arithmetic does not overflow, because a result that cannot be represented by the resulting unsigned integer type decreases modulo a number that is greater than one largest value that can be represented by the resulting integer integer.

In addition, sizeof (char) is defined as 1, and sizeof (unsigned char) = sizeof (char), so you should see the same result regardless of implementation (assuming you don't have bytes with funny sizes other than 8) .

However, the warning tells you that the result is probably not the one you intended (for example, maybe you overestimated the size of the unsigned type?). If this is what you intended, why not write 300 % (1 << CHAR_BIT) (assuming 300 is somehow important to you)?

+4
source share

All Articles