【问题标题】:If char is one byte how is this not undefined behavior如果 char 是一个字节,这不是未定义的行为
【发布时间】:2015-10-10 00:44:55
【问题描述】:

所以一个 int 是四个字节,我只是不明白 C 是如何知道在这种情况下使它工作的

随机函数来说明我的意思

char strl[20];
int c, i=0;
puts("Enter a string up to 19 characters");
while((i<20) && (c=getChar())!="\n")
    strl[i++]=c;

【问题讨论】:

  • C11 标准草案,6.5.16.1 Simple assignment, Section 2 In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.6.5.16 Assignment operators, Section 3 An assignment expression has the value of the left operand after the assignment[...]
  • 啊,复制粘贴第二个引用的错误句子:[...]The type of an assignment expression is the type the left operand would have after lvalue conversion.
  • 我认为如果它在读取换行符之前到达 EOF 是未定义的,因为 EOF 不是有效的char 值。
  • @EOF 给定你的句柄,你能确认一下吗?
  • EOF 是一个宏,在 *NIX 世界中的值为 -1

标签: c char int undefined-behavior


【解决方案1】:

C 不是强类型语言,像这样的隐式转换很常见。

C11 draft standard 6.5.16.1 的这个例子和你的非常相似:

int f(void);
char c;
/* ... */
if ((c = f()) == -1)
       /* ... */

函数返回的 int 值在存储时可能会被截断 char,然后在 比较。

所以这种行为是明确定义的。

编辑:我意识到上面可能不是最好的例子,因为从intchar 的转换将由实现定义(如果char 默认为unsignedsigned)。但是,它仍然表明这是 已定义 行为,而不是未定义。

【讨论】:

  • 我相信这也是在 89 中定义的,K&R ANCI C 提到也这么说。
  • @GRC 我敢肯定。我只是想引用最新的标准。
  • @GRC 它基本上永远是 C 的一部分,因为它在 PDP11 上运行。
  • 我相信你引用的例子是为了说明不正确的代码。最后一句为“因此,为了完全可移植,变量c 应声明为int。”
  • @rici 你是对的。它不是可移植代码,您可能称之为格式错误。但它仍然表明这是已定义的行为,而不是问题中的未定义行为。我将使用该免责声明编辑答案。
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
相关资源
最近更新 更多