Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

c++ - 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 in any way predictable or its undefined??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Is the output in any way predictable or its undefined??

It is predictable. There are two points to look after in this code: First, the assignment of value that the type unsigned char can't hold:

unsigned char c;
c = 300;

3.9.1 Fundamental types (Page 54)

Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.41)
...
41) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

Basically:

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

Second, passing %d in the format string of printf to print unsigned char variable.
This one ysth got it right ;) There is no undefined behavior, because a promotional conversion from unsigned char to int happens in the case of variadic arguments!

Note: that the second part of the answer is a rephrasing of what have been said in the comments of this answer but it is not my answer originally.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...