c - 为什么c for循环条件接受初始化

标签 c for-loop

昨天我参加了一个面试,看到了一个奇怪的程序片段。

乍一看,我认为 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/

相关文章:

c - 在C中执行以下操作的方法是什么?

c - 我想打印输入字符串中以空格分隔的单词

c - 在 C 中读取和打印字符串

python - 如何遍历列表中除最后一项之外的所有内容?

r - 迭代过滤器列表和所有可能的组合

java - 更新文本区域

javascript - For-Loop 调用时未运行

java - 如何按顺序打印两个相邻的增强型 for 循环

c - 搜索 -lMY_LIB 时跳过不兼容的 lib_share.so 找不到 -lMY_LIB

c++ - 我可以直接调用函数指针吗?