本文介绍了混合符号的整数运算取决于大小可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

功能 G1() G2()具有相同的逻辑,但输入的类型有不同的尺寸。为什么他们返回不同的结果负数额?

Functions g1() and g2() have identical logic, but the input types have different sizes. Why do they return different results for negative sums?

/*BINFMTCXX: -Wall -Werror -Wextra -std=c++11
*/

#include <stdio.h>
#include <stdint.h>

char g1( int32_t a, uint32_t b ) { return a+b<9; } // fails when a+b is negative
char g2( int16_t a, uint16_t b ) { return a+b<9; } // works if no overflow

int main()
   {

   for ( int a=-2, b=0; a<=2; a++ )
      {
      fprintf(stderr,"a=%+d, b=%d, g1=%+d, g2=%+d %s\n", a, b, g1(a,b), g2(a,b), g1(a,b)==g2(a,b)?"":"!" );
      }

   return 0;
   }

当我运行它,它表明 G1()时失败 A + B 是否定的:

When I run it, it shows that g1() fails when a+b is negative:

$ ./mixed_sign_math_per_size.cpp
a=-2, b=0, g1=+0, g2=+1 !
a=-1, b=0, g1=+0, g2=+1 !
a=+0, b=0, g1=+1, g2=+1 
a=+1, b=0, g1=+1, g2=+1 
a=+2, b=0, g1=+1, g2=+1 

的结果是在C和C ++相同的

The results are the same in C and C++.

推荐答案

由于的,无论是 A b G2 的身体都提升到 INT ,这就是为什么该功能很完善。

As a result of the usual arithmetic conversions, both a and b in g2's body are promoted to int, which is why that function works perfectly well.

有关 G1 ,因为( U int32_t 没有等级小于 INT ,无促销发生,并且非常最后一颗子弹点(11.5.5)适用。这两个操作数转换为无符号的类型,其中 - 在 A 的情况下 - 会导致下溢,生产比9。因此, G1更大的值返回 1 真正)。

For g1, because (u)int32_t does not have a rank less than that of int, no promotion occurs, and the very last bullet point (11.5.5) applies. Both operands are converted to the unsigned type, which - in a's case - causes an underflow, producing a value much greater than 9. Hence g1 returned 1 (true).

这篇关于混合符号的整数运算取决于大小可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 11:11