13

无限循环是否类似于for (;;);C 中的未定义行为?(它适用于 C++,但我不了解 C。)

4

2 回答 2

11

不,for (;;)语句的行为在 C 中已得到很好的定义。

N1570与官方 2011 ISO C 标准基本相同,在第 6.8.5 节第 6 段中说:

一个迭代语句,其控制表达式不是常量表达式,不执行输入/输出操作,不访问 volatile 对象,并且在其主体、控制表达式或(在for 语句的情况下)不执行同步或原子操作它的表达式 3可以被实现假定为终止。

有两个脚注:

一个省略的控制表达式被一个非零常量替换,这是一个常量表达式。

这旨在允许编译器转换,例如即使在无法证明终止时也可以删除空循环。

第一个脚注清楚地表明它for (;;)被视为具有恒定的控制表达式。

该规则的要点是在编译器无法证明循环终止时允许优化。但是如果控制表达式是常量,编译器可以简单地证明循环是否终止,因此不需要额外的权限。

于 2013-03-24T05:56:09.737 回答
0

The rationale for this question with relevance to C++ isn't relevant to C. Section 5.1.2.3p6 states the limits to optimisation, and one of them is:

At program termination, all data written into files shall be identical to the result that execution of the program according to the abstract semantics would have produced.

Now the question becomes "What data would execution according to the abstract semantics have produced?". Assuming a signal interrupts the loop, the program may very well terminate. The abstract semantics would have produced no output prior to that signal being raised, however. If anything, the compiler may optimise the puts("Hello"); away.

于 2013-03-24T06:33:48.260 回答