7

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

Srini
  • 477
  • 1
  • 11
  • 25
  • 7
    **Why** did you think it should be a compilation error in C? It is not possible to properly address the root of your confusuion without knowing where that root is. Why do you think the condition statement is "wrong"? What's wrong with it? – AnT Sep 11 '17 at 16:54
  • 4
    C and Java are different languages with different rules. In C, the test expression in a `for` statement just has to be an integral type, which `i=5` is. In Java, the test expression must be a Boolean type, which `i=5` is *not*. The C code isn't "wrong" in a semantic sense, although it isn't terribly clear; it could either be an obfuscated equivalent of `for(;;)`, or it could represent a common typo (using `=` when you meant `==`). – John Bode Sep 11 '17 at 17:25
  • 2
    What did you say about `void main()` to the interviewer? – Weather Vane Sep 11 '17 at 17:32
  • @AnT I am a beginner sorry for my ignorance – Srini Sep 12 '17 at 04:14
  • @WeatherVane what that mean – Srini Sep 12 '17 at 04:14
  • @JohnBode thank you sir,Now I understood – Srini Sep 12 '17 at 04:15

6 Answers6

9

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.

Ray Toal
  • 79,229
  • 13
  • 156
  • 215
6

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.

Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
4

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.

kay
  • 23,543
  • 10
  • 89
  • 128
1

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

nagendra547
  • 3,469
  • 21
  • 33
0

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.

log0
  • 9,642
  • 2
  • 23
  • 59
0

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");
}
Nergal
  • 310
  • 3
  • 13