Disclaimer: I know it is obscure, and I would not program like that. I am aware of the preferred do-while
statement, rather than that, the question is more about validity of a specific language construct.
Is goto
always supposed to omit conditional expression of the for
loop? From what I observed it skips both the first (i.e. initializing) and second expressions. Will this always happen this way or is this behavior purely compiler dependent?
#include <stdio.h>
int main(void)
{
int m = 5;
goto BODY;
for (m = 0; m < 5; m++)
BODY: puts("Message"); // prints "Message" once
printf("m = %d\n", m); // prints m = 6
return 0;
}
Although the goto statement can be used to create loops with finite repetition times, use of other loop structures such as for, while, and do while is recommended. The use of the goto statement requires a label to be defined in the program.
Statement 1: Goto statement allows an unconditional transfer of control.
In fact, IDL's own documentation advises against it. Actually, it doesn't advise against it; it outright states that using it is bad programming: "The GOTO statement is generally considered to be a poor programming practice that leads to unwieldy programs. Its use should be avoided."
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.
Yes, you're jumping over both m = 0
and m < 5
, and this is as it should be.
for (A; B; C)
D;
is equivalent to
{
A;
loop:
if (B)
{
D;
C;
goto loop;
}
}
There is no way to transfer control to a point between A
and B
.
The semantics of your loop are exactly like this "pure goto" version:
int m = 5;
goto BODY;
m = 0;
loop:
if (m < 5)
{
BODY: puts("Message"); // prints "Message" once
m++;
goto loop;
}
printf("m = %d\n", m); // prints m = 6
Does goto is always supposed to omit conditional expression of the for loop?
Yes. A goto jump is always an unconditional jump and the execution will carry from the label from there.
From C11 draft, § 6.8.6.1 The goto statement:
A goto statement causes an unconditional jump to the statement prefixed by the named label in the enclosing function.
With the only exception being:
The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.
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