gpt4 book ai didi

c++ - gcc:警告:大整数隐式截断为无符号类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:32 25 4
gpt4 key购买 nike

#include<stdio.h>

int main()
{

unsigned char c;
c = 300;
printf("%d",c);
return 0;
}

输出是可预测的还是未定义的?

最佳答案

很抱歉第一个回答,这里是 C++ 标准的解释:)

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

这是可以预见的。这段代码有两点需要注意:一、unsigned char类型不能赋值:

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.

基本上:

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

其次,在printf的格式字符串中传递%d来打印unsigned char变量。
这个ysth做对了 ;) 没有未定义的行为,因为在 variadic arguments 的情况下会发生从 unsigned char 到 int 的提升转换!

注意:答案的第二部分是对 the comments of this answer 中所说内容的改写但这本来不是我的答案。

关于c++ - gcc:警告:大整数隐式截断为无符号类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2151305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com