Confusing for... while loop syntax in C - 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.

Related

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++;
}

I have trouble understanding about blocks of for loop and if statement

In C Primer Plus, the author says that
A C99 feature, mentioned earlier, is that statements that are part of
a loop or if statement qualify as a block even if braces (that is, { }
) aren’t used. More completely, an entire loop is a sub-block to the
block containing it, and the loop body is a sub-block to the entire
loop block.
I guess the loop body means the printf(...) statement in the example below. But what do these these two bold words mean? : ".. an entire loop is a sub-block to the block containing it,..." It would be nice if you could explain it using the example below!
for(int n =1;n<3;n++)
printf("%d \n",n);
It is phrased a bit badly, but it's quite simple:
for(int n =1;n<3;n++) // <-- loop
printf("%d \n",n); // <-- block
The loop body is as you said the printf() in this case, and in general, trying to keep my answer as minimum as possible, this is the format:
for(...; ....;)
body_of_loop
The sub comes into play when you have nested loops, or if statements. For example, a double for loop:
1. for(int i = 0; i < 10; ++i)
2. for(int j = 0; j < 10; ++j)
3. printf("hi\n");
More completely, an entire loop is a sub-block to the block containing it, and the loop body is a sub-block to the entire loop block.
So, line 2 is an entire loop and it's a sub-block to the block that it is part of. The block of the exterior for loop is lines 2 and 3.
If you have a code block, for example:
while(1) <-- code block (contains if [that contains printf])
if(2) <-- sub block (contains printf)
printf("3"); <--- part of if block
the printf is considered to be a part of the if block, and the if block itself (now containing the printf as well) is considered a part of the bigger while block. This could go on and on...
while(1)
while(2)
if(3)
for(;;)
i++;
Each of the 3 mid-lines here is a sub block that contains following lines
The C11 standard says, in §6.8.5 Iteration statements
¶5 An iteration statement is a block whose scope is a strict subset of the scope of its
enclosing block. The loop body is also a block whose scope is a strict subset of the scope
of the iteration statement.
I think this is what the statement you quote is attempting to paraphrase.
What this is driving at, somewhat opaquely (welcome to the world of reading standards), is that an iteration statement (while loop, do … while loop or for loop) is treated as a block. This primarily affects the for loop with variable declarations.
Consider:
for (int i = 0; i < max; i++)
printf(" %d", i);
putchar('\n');
The wording means that the code functions as if you had:
{
for (int i = 0; i < max; i++)
{
printf(" %d", i);
}
}
putchar('\n');
This particularly limits the scope of i to the for loop; it is not accessible outside the loop. The loop body being a block whose scope is a strict subset of the iteration statement isn't a big surprise. The surrounding block is less obvious and could be a surprise.

Declaration difference?

What is the difference when we declare variable before using in loop and when define variable in loop.
I am talking about this situation
int i;
for(i=0; i<100; i++);
and
for(int i=0; i<100; i++);
In the former case, you can access i outside the for-loop. This can be advantageous if you have a conditional break in your loop, for example:
int i = 0;
for (i = 0; i < 100; i++) {
if (someUnexpectedConditionHappens()) {
break;
}
// do something
}
printf("The loop has been executed %d times", i);
In the first case it is supposed that variable i will be used also after the loop as for example
int i;
for(i=0; i<100; i++);
printf( "i = %d\n", i );
Nevertheless it would be much better to write the following way
int i = 0;
for( ; i<100; i++);
printf( "i = %d\n", i );
In this case we will get a valid readable code without a need to bother what is done within the loop as for example
int i = 0;
/* some loop used i */
printf( "i = %d\n", i );
That is even if the variable will not be changed (assigned) in the loop or in some other code instead of the loop (usually each code has a tendency to be changed) nevertheless we will get a valid result.
In the second case it is supposed that variable i will be used only within the loop
for(int i=0; i<100; i++);
We need not its value outside the loop. So in this case the life of the variable is limited by the body of the loop. Outside the loop it will be invisible and not alive.
It's the "scope". In the second case, you can only use the variable within the for loop. In the first case - in the entire containing block.
In the first case, i can be accessed outside the loop within the current block. In C89, you cannot declare variables in the loop so you'll have to stick to this method.
In the second case, i cannot be accessed outside the loop. Declaring variables in the loop is a C99 feature.
When you do it before the loop, the variable is then available outside the loop as well.
Whereas when you do it inside it, it is a local variable that can only be used inside the loop.
Also, you can declare a variable inside a loop when using C99 standard. But it does not work for example for C90. So be careful with that.
In the first case, i is accessible outside the for loop.
In the second case, the scope of i is restricted to the for loop body.
Arguably the second case gives you better program stability since the use of i outside the for loop is often unintentional.

Placing Infinite condition in 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*/){}

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.

Resources