需要帮助理解这种在C环code [英] Need help understanding this for loop code in C
问题描述
考虑以下code在C:
Consider the following code in C:
void main()
{
int a=0;
for(printf("\nA"); a; printf("\nB"));
printf("\nC");
printf("\nD");
}
当我使用TURB C ++ 3.0版本和gcc-4.3.4,我得到以下为两种情况下输出编译:
When I compile it using Turb C++ version 3.0 and gcc-4.3.4, I get the following as the output in BOTH the cases :
A
C
D
不过,如果我编译以下code:
However, if I compile the following code:
void main()
{
for(printf("\nA"); 0; printf("\nB"));
printf("\nC");
printf("\nD");
}
由GCC-4.3.4的输出是一样的,在previous案件,但涡轮C ++ 3.0生成以下的输出:
The output by gcc-4.3.4 is the same as in the previous case but turbo c++ 3.0 produces the following output :
A
B
C
D
首先,我不知道这里发生了什么!另外,怎么来用gcc编译器的输出是相同的两个在codeS,但TURBOC ++ 3.0编译器的情况下,输出不同呢?是否有人可以提供一些线索?
First of all, I have no idea what's happening here! Plus, how come the output by the gcc compiler is the same for both the codes but in the case of turboc++ 3.0 compiler, the output is different? Can someone please shed some light?
编辑:
其实有人问一家IT公司的采访这个问题时,他没有给出答案,面试官作了这样的解释。但我觉得这是愚蠢的。你怎么能要求别人用错误,仿佛它是由语言设施提供?对于它被称为工厂和技术,我们是否传递0作为第二恩pression文字或一个变量,其值为0,结局应该是一样的。
Actually someone was asked this question in an interview for an IT company and when he failed to give the answer, the interviewer gave this explanation. But I find this to be stupid. How can you ask someone to use a "bug" as if it's a "facility" provided by the language? For it to be called a "facility" and "technique", whether we pass 0 as a literal in the second expression or a variable whose value is 0, the outcome should have been the same.
我错了总结面试官是非常愚蠢的问这样的问题,它显示了他的无能?
Am I wrong concluding that the interviewer was very dumb to ask a question like that and that it shows his incompetence?
推荐答案
在TCC输出第二个例子是错误的。
The TCC output for the 2nd example is wrong.
从C99标准:
语句
的( 第1 的 前pression-2 的 的前pression-3 的) 语句的
行为如下:这位前pression的前pression-2 的是控制
这是循环体的每次执行之前评估前pression。
这位前pression的前pression-3 的评价为无效前pression后
循环体的每次执行。 [...] 的
behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. [...]
显然,没有迭代这里,所以前pression -3- 的不应该被执行。
Obviously, there are no iterations here, so expression-3 should never be executed.
类似地,在C90标准(或至少在一个草案,我发现的),它说:
Similarly, in the C90 standard (or at least in a draft that I found), it says:
除了continue语句的循环体的行为时,
声明
Except for the behavior of a continue statement in the loop body, the statement
for ( expression-1 ; expression-2 ; expression-3 ) statement
和语句序列
expression-1 ;
while ( expression-2) {
statement
expression-3 ;
}
是等效的。
are equivalent.
这篇关于需要帮助理解这种在C环code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!