昨天我参加了一次面试,在那里我看到了一些奇怪的程序片段。
初步看来,我认为这个片段有编译错误。但是当我回家后手动在C编译器中尝试时,发现我完全错了。
看看面试代码:
#include<stdio.h>
void main()
{
for(int i=0;i=5;i=5)// here condition and increment are assigned
//wrongly and where I thought it is compilation
//error during interview which isn't wrong
{
printf("helloworld \n");
}
}
输出:
helloworld
helloworld
helloworld
helloworld
helloworld
helloworld
.
.
.
.(goes on and on)
C++中的输出类似于C语言。
但是,当我们在Java编译器中运行此代码时,
public class Forhottest {
public static void main(String args[])
{
for(int i=0;i=5;i=5)// here it throws compilation error
{
System.out.println("helloworld");
}
}
}
同样,我在PHP中尝试过,与Java中一样出现了同样的问题。 为什么C和C ++允许在“for循环”内部使用这种奇怪的条件语句? 这背后的原因是什么?
for
循环语句中的测试表达式只需要是整数类型,而i=5
就是一个整数类型。而在Java中,测试表达式必须是布尔类型,而i=5
则不是。从语义上讲,C代码并没有错误,尽管它不太清晰;它既可以是等同于模糊的for(;;)
,也可以代表常见的打字错误(使用=
时应该使用==
)。 - John Bodevoid main()
的问题? - Weather Vane