且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GCC:警告:大整数隐式截断为无符号类型

更新时间:2022-10-15 17:12:04

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


  

以任何方式predictable输出
  或其未定义??


块引用>

这是predictable。这里有两点在这个code照顾:
首先,价值分配该类型 unsigned char型不能成立:

  unsigned char型℃;
C = 300;


  

3.9.1基本类型(第54页)


  
  

无符号整数,无符号的声明,
  应当服从算术法则
  模的2n,其中n是数
  在重新presentation值位
  integer.41的特定大小)搜索
  ...结果
  41),这意味着无符号
  算术不溢出,因为
  结果,不能再由psented $ P $
  所产生的无符号整数类型
  降低模是第一位的
  大于最大值,该值
  可通过由此而来psented重新$ P $
  无符号整型。


块引用>

基本上是:

  C = 300%(的std :: numeric_limits< unsigned char型> :: MAX()+ 1);

二,通过%d个的printf 的格式字符串打印 unsigned char型变量。结果
这其中 YSTH 得到了它的权利;)有没有不确定的行为,因为从unsigned char型促销转换为int发生在的可变参数的情况下

注意:答案的第二部分的改写的什么都在the这个答案的评论,但它不是我的回答原来。

#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??

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.