for(;0;) --> HELP!!

Hi, i am Paras, class XI.
I just started learning c++.

Yesterday, i was using c++ and found that my for loop was behaving like an exit controlled loop.
I entered the following code:-

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n=1;
for(;0;)
cout<<n;
getch();
}

As I have learned that if the condition is false, statement should not be executed even once.
But when I compiled it, it gave me a warning of unreachable code - cout<<n;
and after ignoring the warning i executed the program, and found that the statement was executed once. I am unable to understand why was it executed.

I await your replies.
Thanks in advance.
Last edited on
I think you are mistaken. Nothing will be displayed on the screen.
No. Try it. I got the following output :-
1
Last edited on
Why do you want such a loop? Why not have an ordinary for loop?
nothing will be displayed unless you typed
for(;0;);
@Moooce

That's exactly right. My compiler (gcc 4.7.1) complains about null statement for loops, because they can be optimised to whatever the conditional evaluates to at the end of the loop.
By the way, you have main()'s return type set to void,

and <iostream.h> is deprecated.
Last edited on
closed account (zb0S216C)
Nothing happens with my compiler, as expected. The fact is, that loop will never execute under any circumstance, and therefore, will be removed, along with any statements that are associated with it.

Either your object files are out-of-date, or, your compiler was unable to optimise the loop away, and was forced to execute the loop at least once. Or, maybe, your compiler is old, and non-compliant with the standard, which could mean the compiler tests the condition of the loop after at least 1 iteration.

Wazzak
Last edited on
can you tell us what is your compiler?


because they can be optimised to whatever the conditional evaluates to at the end of the loop.

i don't get it... what do you mean?
Last edited on
1
2
3
int a;
for(a=0;a<10;a++)
            ; //null statement 


is exactly the same as a=10; so that is why my compiler issues an error.

I still wonder why people ask such pedantic questions (the OP's one I mean), with code that is pointless. There has been 1 reply from the OP at the start - is he trolling?
Topic archived. No new replies allowed.