加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

我什么时候可以逃脱未通过签名声明int?

发布时间:2020-12-16 09:50:28 所属栏目:百科 来源:网络整理
导读:在C中,应该使用关键字signed来声明像-1这样的有符号整数,如下所示: signed int i = -1; 但是,我试过这个: signed int i = -2;unsigned int i = -2;int i = -2; 并且所有3个案例用printf打印出-2(“%d”,i);.为什么? 解决方法 由于您确认使用以下方式打印
在C中,应该使用关键字signed来声明像-1这样的有符号整数,如下所示:

signed int i = -1;

但是,我试过这个:

signed int i = -2;
unsigned int i = -2;
int i = -2;

并且所有3个案例用printf打印出-2(“%d”,i);.为什么?

解决方法

由于您确认使用以下方式打印:

printf("%d",i);

在未签名的情况下,这是undefined behavior.这将在draft C99 standard第7.19.6.1节中介绍fprintf函数,该函数还包含格式说明符的printf,它在第9段中说明:

If a conversion specification is invalid,the behavior is undefined.248)[…]

3.4.3节中定义的标准未定义行为如下:

behavior,upon use of a nonportable or erroneous program construct or of erroneous data,
for which this International Standard imposes no requirements

并进一步说明:

Possible undefined behavior ranges from ignoring the situation completely with unpredictable results,to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message),to terminating a translation or execution (with the issuance of a diagnostic message).

最后,我们可以看到int与signed int相同.我们可以通过转到6.7.2类型说明符来看到这一点,在第2段中它将int分组如下:

int,signed,or signed int

后来在第5段中说:

Each of the comma-separated sets designates the same type,except that for bit-field[…]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读