昨天我参加了一个面试,看到了一个奇怪的程序片段。
乍一看,我认为 Snippet 中存在编译错误。 但是当回到家并在 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 循环”中使用这种奇怪的条件语句。 背后的原因是什么
最佳答案
在 C 和 Java 中,for 循环的第二个组成部分是表达式,赋值是表达式。这就是为什么您可以(从句法上讲)表达式
i = 5
作为两种语言的 for 循环中的循环条件。
但是,Java 与 C 不同,adds the following line to the static semantic definition of the for-loop .
The Expression must have type boolean or Boolean, or a compile-time error occurs.
在Java中,表达式的类型
i = 5
是int
,不是boolean
,所以Java编译器报错。
C 没有这个限制,因为它往往对类型更宽容,整数和 bool 值或多或少是“同一件事”。细节可能有点技术性,但整数 5 被隐式强制为真,因此您会看到一个无限循环。
关于c - 为什么c for循环条件接受初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46160583/