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
Here, initialization sets the loop control variable to an initial value. Condition is an expression that is tested each time the loop repeats. As long as condition is true, the loop keeps running.
Answer. In Python, a for loop variable does not have to be initialized beforehand.
No, you can only have one initializing statement.
In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With