我什么时候可以用未签署声明INT脱身? [英] When can I get away with not declaring int with signed?

查看:212
本文介绍了我什么时候可以用未签署声明INT脱身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,有符号整数像-1理应应该用关键字来声明签署,就像这样:

In C, signed integers like -1 are supposedly supposed to be declared with the keyword signed, like so:

signed int i = -1;

不过,我想这样的:

However, I tried this:

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

和三种情况下打印出-2与的printf(%d个,我); 。为什么呢?

and all 3 cases print out -2 with printf("%d", i);. Why?

推荐答案

由于您确认您使用的是打印:

Since you confirmed you are printing using:

printf("%d", i);

这是的无符号情况下未定义行为。这是包括在草案C99标准部分 7.19.6.1 fprintf函数的又包括的printf 的格式说明,它说在段落的 9 的:

this is undefined behavior in the unsigned case. This is covered in the draft C99 standard section 7.19.6.1 The fprintf function which also covers printf for format specifiers, it says in paragraph 9:

如果一个转换说明是无效的,其行为是不确定的。 248) [...]

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

在节中定义的标准 3.4.3 未定义行为的是:

The standard defined in section 3.4.3 undefined behavior as:

行为,或者在错误数据的使用不可移植的或错误的程序构造,
  对于这本国际标准并没有规定要求

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

和进一步指出:

可能的不确定的行为从与联合国predictable结果完全无视的情况下,在环境的记录方式的特点翻译或程序执行过程中的行为(有或没有发行的诊断消息)的范围,以终止翻译或执行(并出具诊断消息)。

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 的是一样的符号int 的。我们可以通过将部分 6.7.2 类型说明符的,在第的 2 的IT小组的 INT看到这的如下:

Finally, we can see that int is the same as signed int. We can see this by going to section 6.7.2 Type specifiers, in paragraph 2 it groups int as follows:

INT,签名,或签署INT

int, signed, or signed int

和段落后面说的 5 的说道:

and later on says in paragraph 5 says:

每个逗号分隔的集指定的相同类型,但对于位字段[...]

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

这篇关于我什么时候可以用未签署声明INT脱身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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