昨天我参加了一次采访,在那里我看到了一个奇怪的节目片段.
初步一瞥我决定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");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
helloworld
helloworld
helloworld
helloworld
helloworld
helloworld
.
.
.
.(goes on and on)
Run Code Online (Sandbox Code Playgroud)
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
同样我在PHP中试过,同样的问题出现在java中.为什么C和C++在"for循环"中允许这种奇怪的条件语句.它背后的原因是什么
在C和Java中,for循环的第二个组件是表达式,赋值是表达式.这就是为什么你可以(在语法上说)表达式
i = 5
Run Code Online (Sandbox Code Playgroud)
作为两种语言中for循环的循环条件.
但是,与C不同,Java将以下行添加到for循环的静态语义定义中.
Expression必须具有boolean或Boolean类型,否则会发生编译时错误.
在Java中,表达式的类型
i = 5
Run Code Online (Sandbox Code Playgroud)
是int,不是boolean,所以Java编译器给出了错误.
C没有这个限制,因为它往往对类型更加宽容,整数和布尔值或多或少"相同".或许,细节有点技术性,但整数5被隐含地强制为真,所以你看到一个无限循环.
false(在C中)是0.在C中,一切都不0是true.Java不能以这种方式工作(Java是强类型的,不允许int将其隐式转换为a boolean).所以,等效的Java,就像是
public static void main(String args[]) {
for (int i = 0; (i = 5) != 0; i = 5)
{
System.out.println("helloworld");
}
}
Run Code Online (Sandbox Code Playgroud)
这也产生了无限循环打印helloworld.
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |