Srini
Srini

Reputation: 487

why c for loop condition accepts initialization

Yesterday I have attended an interview, there I saw a weird program snippets.

By initial glance I decide that Snippet has compilation error in it. But when came home and tried manually in C compiler I found I was totally wrong

See interview code

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

Output:

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

output in C++ is similar to C

But,

when we run this code in java compiler

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

}

similarly I tried in PHP ,same problem arise as in java. Why C and C++ allow this kind of weird condition statement inside "for loop". what is reason behind it

Upvotes: 7

Views: 645

Answers (6)

log0
log0

Reputation: 10937

i=5 evaluates to 5 (int j=i=5; is valid and j == 5). 5 is a 'true' value according to C and C++. Java and Php expect a Boolean as second parameter of a for loop. C and C++ accept integers.

Upvotes: 0

nagendra547
nagendra547

Reputation: 6310

In java, for FOR loop

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

The highlighted code(middle condition of the for loop) is expecting a boolean type. You cannot give a expression which is not returning as boolean.

Java is robust language and every thing is strongly typed. In C/C++ assigning i=5 is fine as this expression get converted to bool as true, Java compiler will throw you error cannot convert from int to boolean

Upvotes: 1

Nergal
Nergal

Reputation: 369

well, let's break down what the code is doing.

you have:

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

in C, for(int i=0;i=5;i=5) each part of the for-loop is an expression. Please remember that for-loops are syntactic sugar for while-loops.

it would likely be translated down and be the same as...

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

The reason why Java whines about it is because Java has stronger typing than C and C++. In Java, the middle expression is expected to be a strictly bool value/result for it to be considered valid Java.

In C(++) boolean values are nothing but int values (true == 1 and false == 0). Assignments are considered an expression which evaluates to true if the value you give an identifier is above or less than 0.

Let's use this in another scenario!

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

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201487

false (in C) is 0. In C, everything that isn't 0 is true. Java doesn't work that way (Java is strongly typed, and won't allow an int to be implicitly converted to a boolean). So, the equivalent Java, would be something like

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

Which also produces an infinite loop printing helloworld.

Upvotes: 6

Kijewski
Kijewski

Reputation: 26043

Because assignments are expressions in C, not statements. That's different for different languages ...

Nb. always read the warnings of your compiler, and use -Wall -Wextra -Werror -pedantic -pedantic-errors to avoid such typos. Your void main() would not have passed either if you read the warnings.

As Ray Toal pointed out in Java assignments are expressions, too, but integers are not automatically casted to booleans.

Upvotes: 4

Ray Toal
Ray Toal

Reputation: 88428

In both C and Java, the second component of the for loop is an expression, and assignments are expressions. This is why you can have (syntactically speaking) the expression

i = 5

as the loop condition in a for-loop in both languages.

However, Java, unlike 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.

In Java, the type of the expression

i = 5

is int, not boolean, so the Java compiler gives the error.

C does not have this restriction, as it tends to be a lot more permissive with types, with integers and booleans being more or less "the same thing." Details are a little technical, perhaps, but the integer 5 is implicitly coerced to truthiness, so you see an infinite loop.

Upvotes: 9

Related Questions