static unsigned long k=-1;

bestoak 2009-07-12 07:44:27
请问既然定义了是无符号,为什么k还可以等于-1呢?
...全文
91 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
飞天御剑流 2009-07-13
  • 打赏
  • 举报
回复
[Quote=引用楼主 bestoak 的帖子:]
请问既然定义了是无符号,为什么k还可以等于-1呢?
[/Quote]

这不是k等于-1,标准规定,进行整形转换的时候,如果新值是无符号类型,当旧值不在新值的表示范围内时,会将旧值加上新值无符号类型的最大值再加一,再

赋予新值,标准摘录如下:


6.2.1.2 Signed and unsigned integers

When a value with integral type is converted to another integral type, if the value can be
represented by the new type, its value is unchanged.

When a signed integer is converted to an unsigned integer with equal or greater size, if the
value of the signed integer is nonnegative. its value is unchanged. Otherwise: if the unsigned
integer has greater size, the signed integer is first promoted to the signed integer corresponding to
the unsigned integer: the value is converted to unsigned by adding to it one greater than the
largest number that can be represented in the unsigned integer type ”
风老二 2009-07-12
  • 打赏
  • 举报
回复
[Quote=引用楼主 bestoak 的帖子:]
请问既然定义了是无符号,为什么k还可以等于-1呢?
[/Quote]

可以理解为int与uint都在一个容器里,只不过解析方法不同
haierpro 2009-07-12
  • 打赏
  • 举报
回复
同意二楼的说法,应该是自动类型转换,就像int a = 'c';
AlwaysSLH 2009-07-12
  • 打赏
  • 举报
回复
学习一下:原码、反码、补码,以及数在计算机中的表示
happypeter2008 2009-07-12
  • 打赏
  • 举报
回复
有点玄乎
东大坡居士 2009-07-12
  • 打赏
  • 举报
回复
无所谓符号了~~~~
lemirymoo 2009-07-12
  • 打赏
  • 举报
回复
看淡一些吧,其实无所谓符号,也无所谓数值,用的时候你怎么去用它就是什么。

printf("1.k=%d",k);
printf("2.k=%u",k);

k = 1145258561;

printf("3.k=%s",&k);

ljhhh0123 2009-07-12
  • 打赏
  • 举报
回复
假如unsigned long 是32位长度,-1就是0xffffffff,这两个表示方法没什么区别.
把这个值传过去,编译器假设你知道自己在做什么.
Walf_ghoul 2009-07-12
  • 打赏
  • 举报
回复
无符号不是所看见的,关键得理解里面的二进制存储。。
blh 2009-07-12
  • 打赏
  • 举报
回复
[Quote=引用楼主 bestoak 的帖子:]
请问既然定义了是无符号,为什么k还可以等于-1呢?
[/Quote]

自动类型转换

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧