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

时间:2017-09-11 16:44:28

标签: c for-loop

昨天我参加了一次采访,在那里我看到了一个奇怪的节目片段。

初步一瞥我决定Snippet中有编译错误。 但当回到家并在C编译器中手动尝试时,我发现我完全错了

查看访谈代码

 helloworld
 helloworld
 helloworld
 helloworld
 helloworld
 helloworld
 .
 .
 .
 .(goes on and on)

输出:

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");
    }
}

}

C ++中的输出类似于C

但是,

当我们在java编译器中运行此代码时

name: "conv1/truncated_normal"
op: "Add"
input: "conv1/truncated_normal/mul"
input: "conv1/truncated_normal/mean"
attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}

同样我在PHP中尝试过,同样的问题出现在java中。 为什么C和C ++在“for循环”中允许这种奇怪的条件语句。 它背后的原因是什么

6 个答案:

答案 0 :(得分:9)

在C和Java中,for循环的第二个组件是表达式,赋值是表达式。这就是为什么你可以(语法上)说出表达式

i = 5

作为两种语言中for循环的循环条件。

然而,Java与C不同,adds the following line to the static semantic definition of the for-loop

  

Expression必须具有boolean或Boolean类型,否则会发生编译时错误。

在Java中,表达式的类型

i = 5

int,而不是boolean,因此Java编译器会给出错误。

C没有这个限制,因为它往往对类型更加宽容,整数和布尔值或多或少都是相同的。"或许,细节有点技术性,但是整数5被隐含地强制为真,所以你看到一个无限循环。

答案 1 :(得分:5)

false(在C中)是0。在C中,不是0的所有内容都是true。 Java不是那样工作的(Java是强类型的,不允许int隐式转换为boolean)。所以,等效的Java,就像

public static void main(String args[]) {
    for (int i = 0; (i = 5) != 0; i = 5)
    {
        System.out.println("helloworld");
    }
}

这也产生了无限循环打印helloworld。

答案 2 :(得分:4)

因为赋值是C中的表达式,而不是语句。这对于不同的语言来说是不同的......

的Nb。始终阅读编译器的警告,并使用-Wall -Wextra -Werror -pedantic -pedantic-errors来避免这种拼写错误。如果您阅读警告,则void main()也不会通过。

正如Ray Toal在Java中指出的那样,赋值也是表达式,但整数不会自动转换为布尔值。

答案 3 :(得分:1)

在java中,FOR FOR循环

for(int i = 0; i = 5 ; i = 5)

  

突出显示的代码(for循环的中间条件)期待a   布尔类型。你不能给出一个没有返回的表达式   布尔值。

Java是强大的语言,每一件事都是强类型的。在C / C ++中分配i = 5很好,因为这个表达式转换为bool为true,Java编译器会抛出错误无法从int转换为boolean

答案 4 :(得分:0)

i=5评估为5(int j=i=5;有效且j == 5)。 5是根据C和C ++的“真实”值。 Java和Php期望布尔值作为for循环的第二个参数。 C和C ++接受整数。

答案 5 :(得分:0)

好吧,让我们分解一下代码的作用。

你有:

for(int i=0;i=5;i=5)// here condition and increment are assigned wrongly and where I thought it is compilation during interview
{
    printf("helloworld \n");
}

在C中,表示(int i = 0; i = 5; i = 5) for循环的每个部分都是一个表达式。 请记住,for循环是while循环的语法糖。

它可能会被翻译下来并与......相同。

int i=0;
while( i=5 ) {
    printf("helloworld \n");
    i=5;
}

Java抱怨它的原因是因为Java比C和C ++具有更强的类型。在Java中,中间表达式应该是严格的bool值/结果,以使其被视为有效的Java。

在C(++)中,布尔值只是int值(true == 1和false == 0)。 如果赋予标识符的值大于或小于0,则赋值被视为表达式,其值为true。

让我们在另一种场景中使用它!

int main()
{
    int i;
    if( i = -1, i=5 )   // this would run
        printf("Hello World\n");
}