Placing Infinite condition in c - c

I am running a C program with an infinite for loop:
for(;;)
{
//Statement
}
Why is it running an infinite number times, even though we have not specified the loop's initialization, condition and incrementation?
What do the "blank" values mean?

Here's the basic syntax of a for loop.
for(clause-1; expression-2; expression-3) statement;
According to The C Programming Language by K&R, both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a non-zero constant. And as we know, any non-zero value means "true" in C.
P.S.: Though the K&R book is quite outdated, it's considered as the Bible of C by many.

The loop only breaks when the condition is false. Since there is no condition, nothing can be false, and the loop doesn't break.

the for(;;) statement is the same as the while. If you "convert" the for(;;) it will be something like this:
for(i = 0; i < n; i++)
{
//Do stuff
}
to this
i = 0;
while( i < n )
{
//Do stuff
i++;
}
So if the middle statement has nothing in it, it will run forever
EDIT:
In the third part of the loop you can do anything. You could even to this:
for(i = 0; i < n; i++, /*Do stuff*/){}

Related

Confusing for... while loop syntax in C

I accidentally noticed that the following snipped of code compiles under GCC:
void myFunction(void) {
int i, y = 0;
for (i = 0; i < 10; i++)
y++;
while (y);
}
I've never encountered such a piece of code before and wasn't able to find any information about such a construct after doing some searching around. It leads me to wonder what the purpose of such a construct is and what it is meant to do?
There is no such thing as a for ... while loop.
What you see are two independent loops.
First, there is a for loop. The only instruction in the body of that loop is y++;.
Then you see anoter loop: while(y) ;. That is not related at all to the for loop. The body only consists of an empty instruction ;. As y never changes in the body, that will be an infinite loop.

Iterative Statements

So, I have been studying iterative statements for a report. While I was reading, I came across the developmental history of definite iteration and eventually learn the for loop. We know that the syntax for the for loop in C,C++, and java is
for (expression1; expression2; expression3)
statement
And it says here that we can omit any of the expression and that it is legal to have a for loop that look like this
for (;;)
My question is how does that work? I cant find any more resources for this one.
A for loop declared as:
for (init-statement; condition; iteration-expression) body;
Is equivalent to:
init-statement;
while (condition) {
body;
iteration-expression;
}
It's easy to see how init-statement or iteration-expression could be omitted. If the condition is omitted, it is assumed to be true.
A reasonable resource that explains this is the Explanation section of the for loop documentation at cppreference.com.
Basically, for (;;) is legal, but you will need to put something inside the body of that for loop, otherwise the loop will never stop.
int counter = 0;
int limit = 5;
for (;;) {
if (counter > limit) break;
counter++;
}

Can an empty for-loop be "correct"?

I have a doubt about the for loop of the following code in C:
main()
{
int i=1;
for(;;)
{
printf("%d",i++);
if(i>10)
break;
}
}
I saw this code in a question paper. I thought that the for loop won't work because it has no condition in it. But the answer says that the code has no error. Is it true ? If true, how ?
The regular for loop has three parts:
Initialization
Condition
Increment
Usually they are written like this:
for (initialization; condition; increment) { statements }
But all three parts are optional. In your case, all parts are indeed missing from the for loop, but are present elsewhere:
The initialization is int i=1
The condition is if (i>10) break
The increment is i++
The above code can be equivalently written as:
for (int i=1; i <= 10; i++) {
printf("%d", i);
}
So all the parts necessary for a for loop are present, except they are not inside the actual for construct. The loop would work, it's just not a very readable way to write it.
The for (;;) loop is an infinite loop, though in this case the body of the loop takes actions that ensure that it does not run forever. Each component of the control is optional. A missing condition is equivalent to 1 or true.
The loop would be more clearly written as:
for (int i = 1; i < 11; i++)
printf("%d", i);
We can still debate whether the output is sensible:
12345678910
could be produced more easily with:
puts("12345678910");
and you get a newline at the end. But these are meta-issues. As written, the loop 'works'. It is syntactically correct. It also terminates.
You are not specifying any parameters or conditions in your for loop, therefore, it would be an endless loop. Since there is a break condition based on another external variable, it would not be infinite.
This should be re-written as:
for (int i = 1; i <= 10; i++)
printf("%d",i++);
It's an infinite loop. When there is not a condition in for and we use ;; the statements in the body of for will be executed infinitely. However because there is a break statement inside it's body, if the variable i will be greater than 10, the execution will be stopped.
As it is stated in MSDN:
The statement for(;;) is the customary way to produce an infinite loop which can only be exited with a break, goto, or return statement.
For further documentation, please look here.
Even if a for loop is not having any condition in it, the needed conditions are specified inside the for loop.
The printf statement has i++ which keeps on increasing the value of i and next we have if statement which will check if value of i is less than 10. Once i is greater than 10 it will break the loop.

Bound by confusion, needs clear explanation of post increment

guys i'm new at programming and i was surprised by the result of post increment value, now i'm bound by confusion after i found out and executed the code below, if for loop says
1. initialize
2. check for condition if false terminate
3. incrementation.
where does i++ happens? where does i value is equal to 1?
int main()
{
int i, j;
for (int i =0; i<1; i++)
{
printf("Value of 'i' in inner loo[ is %d \n", i);
j=i;
printf("Value of 'i' in outter loop is %d \n", j);
// the value of j=i is equals to 0, why variable i didn't increment here?
}
//note if i increments after the statement inside for loop runs, then why j=i is equals to 4226400? isn't spose to be 1 already? bcause the inside statements were done, then the incrementation process? where does i increments and become equals 1?
//if we have j=; and print j here
//j=i; //the ouput of j in console is 4226400
//when does i++ executes? or when does it becomes to i=1?
return 0;
}
if Post increment uses the value and add 1? i'm lost... Please explain... thank you very much.
I'm not really sure what you're asking, but sometimes it's easier for beginners to understand if rewritten as a while loop:
int i = 0;
while (i < 1)
{
...
i++; // equivalent to "i = i + 1", in this case.
}
Your loop declares new variable i and it shadows the i declared earlier in main(). So if you assign i to j outside of the loop, you are invoking undefined behaviour because i is not initialised in that context.
Prior to the first iteration, i is initialised to 0. This is the "initialize" phase, as you called it.
The loop condition is then evaluated. The loop continues on a true value.
The loop body is then executed. If there's a continue; statement, that will cause execution to jump to the end of the loop, just before the }.
The increment operator is then evaluated for it's side-effects.
Hence, it is after the first iteration that i changes to 1. i keeps the value 1 for the entirety of the second iteration.
It looks like you have a clash of variable names: i is declared before the loop, and also inside the loop.
The i that is declared in the for statement is the only one that will ever be 1. It will be one just after the body of the loop is executed.
Try setting a breakpoint and using the debugger to step through the loop whilst you watch the value of the variable (here's a video of what I mean by stepping with the debugger).
To remove the ambiguitity of having two variables called i you could change the for loop to:
for (i = 0; i < 1; i++) // remove the `int`
this will ensure that there is only one i in your code.
A comment on #CarlNorum's answer which wouldn't look good as a comment:
The C Standard defines
for ( A; B; C ) STATEMENT
as meaning almost the same thing as
{
A;
while (B) {
STATEMENT
C;
}
}
(where a {} block containing any number of statements is itself a kind of statement). But a continue; statement within the for loop will jump to just before the next statement C;, not to the next test of expression B.
for (i=0; i<x; i++)
Is equivalent to
i=0;
while(i<x) {
// body
i = i + 1;
}

for(i=0;0;i ) in c executes exactly one time why?

for(i=0; 0; i)
{
//statement
}
Why the statement executes only one time ? Either it does not execute the statement or the statement should go into an infinite loop. but the statement executes just one time. Can you please help me.
Make sure you don't have a semi-colon after the for loop otherwise the compiler will take the semi-colon to be the end of the loop and anything in the following braces will be executed once.
for(i=0; 0; i); // end of loop
{
// do something once
}
You don't have a semicolon in your example but I've seen people do this often in programming courses and the fact it runs once is a symptom of this mistake. Just a suggestion.
Actually, that line will not execute the statement. I would look at your program again to see if some other output / statements have been misidentified as the output of the statement in the block
#include <stdio.h>
int main(int argc, char** argv)
{
int i;
for (i = 0; 0; i) {
printf("i is %d\n", i);
}
return 0;
}
when ran yields no output.
Another possibility is that your source code is now out-of-sync with your binaries, something that happens occasionally with hand rolled C build systems. Try removing your .o object files, your generated binaries, and recompiling from scratch. If the execution disappears, perhaps you need to look at how you achieve your build a bit more carefully.
This is quote from the C99 standard about the for loop:
6.8.5.3 The for statement 1 The statement
for ( clause-1 ; expression-2 ; expression-3 )
statement behaves as follows: The expression expression-2 is the
controlling expression that is evaluated before each execution of the
loop body. The expression expression-3 is evaluated as a void
expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any variables it declares is the remainder
of the declaration and the entire loop, including the other two
expressions; it is reached in the order of execution before the first
evaluation of the controlling expression. If clause-1 is an
expression, it is evaluated as a void expression before the first
evaluation of the controlling expression.134)
Since the condition is false, it shouldn't execute it even once. So it's clearly a bug in the compiler you use.
Try
for (i = 0; i < 10; i++)
then lookup the for loop on google.
There are three parts to a for loop
initialization ; loop end condition ; increment.
why your code says, is probably not what you mean.
This loop will not execute even one time because the terminating condition is 0 ie false
for(i=0; 0; i)
{
printf("%d",&i)
}
Does not print any thing.

Resources