签署无符号的转换 [英] signed to unsigned conversions

查看:98
本文介绍了签署无符号的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  谜语(C语言)

看到这个code

  #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) 

  int array[] = {23,34,12,17,204,99,16}; 

  int main() 

  { 

      int d; 

      for(d=-1;d <= TOTAL_ELEMENTS-2;d++) 
          printf("%d\n",array[d+1]); 

      return 0;

  } 

现在这个循环将无法运行。
的sizeof()会这么TOTAL_ELEMENTS有一个无符号值返回一个无符号值。
现在,来到for循环,请告诉我,如果单目运算符 - 适用于有符号整数2或隐式转换发生到签名,然后将 - 运营商的作品。

now this loop won't run. sizeof() would return an unsigned value so TOTAL_ELEMENTS has an unsigned value. now , coming to the for loop, please tell me if the unary operator '-' works on signed int 2 or an implicit conversion takes place into unsigned and then the '-' operator works.

推荐答案

在您的例子的 D 转换为在比较的的 unsigned int类型的。但是-1不能重新psented为的 unsigned int类型的价值$ P $,所以它转换为UINT_ MAX。为了避免这种情况,你可以比较的右侧转换为签署的 INT 的由prepending的(INT)

In your example d is converted to an unsigned int in the comparison. But -1 cannot be represented as an unsigned int value, so it is is converted to UINT_ MAX. To avoid this behaviour you can convert the right side of the comparison to an signed int by prepending (int).

请参阅Understand整数转换规则,获取有关使用C整数转换的详细信息。

See Understand integer conversion rules for details on integer conversion in C.

这篇关于签署无符号的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆