This question already has answers here:
Two semicolons inside a for-loop parentheses
(4 answers)
Endless loop in C/C++ [closed]
(12 answers)
Closed 4 years ago.
I was searching for an explanation for the "double semicolon" in the code:
for(;;){}
Original question.
I do not have enough reputation to even leave a comment so I need to create a new question.
My question is,
What does an "extra" semicolon means. Is this "double semicolon" or "extra semicolon" used for "something else"?
The question comes from a person with no knowledge of programing, just powered on my first arduino kit and feel like a child when LED blinked.
But it is the reality that the questions, like general occurence, are radiating the actual knowledge of the person asking the question.
And beyond "personal preference" in using while(1) or for(;;) is it helpful in using for(;;) where you do not have enough room for the code itself?
I have updated the question.
Thank you for the quick explanation. You opened my eyes with the idea of not using anything in for loop = ). From basic high school knowledge I am aware of for loop so thank you for that.
So for(;;) returns TRUE "by default"?
And my last line about the size of the code?
Or it is compiled and using for or while actually does not affect the compiled code size?
A for loop is often written
int i;
for (i = 0; i < 6; i++) {
...
}
Before the first semicolon, there is code that is run once, before the loop starts. By omitting this, you just have nothing happen before the loop starts.
Between the semicolons, there is the condition that is checked after every loop, and the for loop end if this evaluates to false. By omitting this, you have no check, and it always continues.
After the second semicolon is code that is run after every cycle, before that condition is evaluated. Omitting this just runs additional code at that time.
The semicolons are always there, there is nothing special about the face that they are adjacent. You could replace that with
for ( ; ; )
and have the same effect.
While for (;;) itself does not return true (It doesn't return anything), the second field in the parentheses of the for always causes the loop to continue if it is empty. There's no reason for this other than that someone thought it would be convenient. See https://stackoverflow.com/a/13147054/5567382. It states that an empty condition is always replaced by a non-zero constant, which is the case where the loop continues.
As for size and efficiency, it may vary depending on the compiler, but I don't see any reason that one would be more efficient than the other, though it's really up to the compiler. It could be that a compiler would allow the program to evaluate as non-zero a constant in the condition of a while loop, but recognise an empty for loop condition and skip comparison, though I would expect the compiler to optimize the while loop better. (A long way of saying that I don't know, but it depends on a lot.)
Related
I'm currently studying computer science in Germany but did work on several C/C++ opensource projects before.
Today we kind of started with C at school and my teacher said it would be a no go to modify a for loop variable inside the loop, which I absolutely agree with. However, I often use a for loop without the last incrementing part and then modify it only inside the loop, which he also did not like.
So basically it comes down to
for(int i=0; i<100;) {
[conditionally modify i]
}
vs
int i=0;
while(i<100) {
[conditionally modify i]
}
I know that they are essentially the same after compile, but I don't like using a while loop because:
It's common practice to limit variables to smallest possible scope
It can introduce bugs if you reuse i (which you have to because of larger scope)
You can not use a different type for i in a later loop without using a different name
Are there any style guides/common practices which one to choose ?
If you answer with "I like while/for more" at least provide a reason why you do so.
I did already search for similar questions, however, I could not find any real answer to this case.
Style guides differ between different people / teams.
The C standard describes the syntax of for like this:
for ( clause-1 ; expression-2 ; expression-3 ) statement
and it's common practice to use for as soon as you have a valid use for "clause-1", and the reason to do so is indeed because of the limited scope:
[...] If clause-1 is a
declaration, the scope of any identifiers it declares is the remainder of the declaration and
the entire loop, including the other two expressions; [...]
So, your argumentation is fine, and you could try to convince your teacher. But don't try too hard. After all, questions of style rarely have one definitive answer, and if your teacher insists on his rules, just follow them when coding for that class.
There are some common practices which programmers follow while taking the decision on which loop to use - for or while!
The for loop seems most appropriate when the number of iterations is known in advance. For example -
/*N - size of array*/
for (i = 0; i < N; i++) {
...
}
But, there could be many complex problems where the number of iterations depend upon a certain condition and can't be predicted beforehand, while loop is preferable in those situations.
For example -
while( fgets( buf, MAXBUF, stdin ) != NULL)
However, both for and while loops are entry controlled loops and are interchangeable. Its completely up to the programmer to take the decision on which one to use.
If you are modifying the loop counter inside the body, I would recommend not using a for loop because it is more likely to cause reader's confusion than the while loop.
You can work around the lack of scope limitation with an additional block:
{
int i = 0;
while (i < 100) {
[conditionally modify i]
}
}
for(int i=0; i<100;) {
[conditionally modify i]
}
Because this looks confusing, not standard way to write for loop. Also, conditionally modify i is dangerous, you don't want to do that. Someone reading your code would have problems understanding how you increment, why, when..etc. You want to keep your code clean and easy to understand.
I would personally never write for loop with conditionally modifying iterator. If you need it, you can use additional counter, or something like that. But you shouldn't control flow with conditioning iterator, some people even avoid break and continue.
This question already has answers here:
Is it a bad practice to use break in a for loop? [closed]
(19 answers)
Closed 5 years ago.
I have a fairly simple structure:
do i = 1,x
if (condition) then
do_stuff
exit
end if
end do
If the do-loop gets big enough, the exit statement wouldn't be good anymore (I look at it approx. like I look at go to statements).
I'm looking for a cleaner way to exit the loop when appropriate so that it is also more clear what is happening for somebody else looking over my code.
One thing I thought of that might clean up would be something along the lines of
lkeepgoing = .true.
iterator = 1
while (lkeepgoing) then
if (condition) then
do_stuff
lkeepgoing = .false.
end if
iterator = iterator+1
end while
While I think it clears up why I want to exit the loop without having to look through the whole loop, it looks overly complicated I think.
So the question: How do you exit do-loops when a condition is met in a clear, clean way that doesn't use spaghetti-code-prone statements?
There's nothing wrong with the way your first code snippet uses exit. A little jump such as that is hardly spaghetti code. And compared with your second snippet it's considerably clearer that you are making a disciplined early exit from a loop when a certain condition is met.
Bear in mind that exit is very confined in where it can jump to, while go to can be used to jump all over the place.
Don't adhere to one-size-fits-none rules such as never use goto too strictly, certainly not when they make code worse.
This question already has answers here:
"Backwards" Conditionals in C [duplicate]
(4 answers)
Closed 6 years ago.
Lately I've been noticing the style of some programmers who write "if" statements backwards. That is, in the test they put the constant value first and then the variable that they are testing second. So for example they write:
bar = foo();
if (MY_CONSTANT == bar) {
/* then do something */
}
To me, this makes code somewhat difficult to read. Since we are really talking about testing the value of the variable "bar" and not all variables that are equal to "MY_CONSTANT", I always put the variable first. Its sort of a unspoken grammar.
Anyhow, I see that some programmers ALWAYS do this in the opposite order. Further, I've only noticed this in the past few years. I've been programming in C for over 25 years and I've not seen this until, say, about the last 4 years or so. So my question is:
Is there a reason people are doing this and if so what is it? Is this a common standard in some languages, or projects, or is it taught in some universities? or is that just a few people trying to be different?
This is called "Yoda-Style" (or "Yoda conditions" or "Yoda notation") and should prevent you from accidentally writing
if (bar = MY_CONSTANT) {
/* then do something */
}
since
if (MY_CONSTANT = bar) {
/* then do something */
}
would trigger a compiler error.
The name is derived from the uncommon twisted sentence construction the Star Wars character Yoda is also using.
In my opinion using "Yoda-Style" makes understanding of code harder because it is against the normal sentence construction rules. Also code quality checker (or as mentioned in the comments maybe even the compiler itself) should complain about such assignments anyway, so that (imho) there is no good reason to obfuscate your code.
This is something of a best practice which someone thought best 15 years ago or so. Alleged benefit was that it would prevent someone from doing accidental assignments instead of comparison.
It was dubious back than, it is 100% moot nowadays since any compiler worth using will warn about assignment in branch operator, but hordes of lemmings still copy best practice without even thinking what it means or what it is for.
I have seen code (in C) which contains something similar to:
for(;;){
}
How would this work, and why is it used in any instance?
It is the idiomatic way to have an infinite loop.
In the C Programming Language book, by Kernighan & Ritchie book it was introduced in section 3.5:
for (;;) {
...
}
is an infinite loop, presumably to be broken by other means, such as a break or return.
is an infinite loop something like
while(true)
{}
This is equivalent to an infinite loop, as many other have explained. However, few of them explained why this executes as an infinite loop.
A for loop can be broken down into three parts:
for(initialization(s); condition(s); looping command(s))
None of these fields are actually required. Without a condition provided, there's nothing to stop the command from running. This is because the for loop looks for a false statement. Without conditions provided, nothing is false, therefore the loop runs indefinitely.
Therefore to cause a for loop to be infinite, all you need is to not provide a condition. This means that this is also a valid infinite loop:
for(int i = 0;; i++)
printf("Iteration: %i\n", i);
For readability, and to make sure that the second semi-colon isn't a typo, some programmers might put a space between them, or put true as the condition.
Honestly, I prefer while(true), as this is a clear infinite loop. Using while(1) works as well, but '1' is an integer, not a boolean. While it is equivalent to true, it does not always mean true.
Between these three types of infinite loops, for(;;) has the fewest characters (7). while(1) comes second at 8 characters, and while(true) at 11.
I suppose that certain programmers prefer a low byte count over a readable program, but I wouldn't recommend using for(;;). While equivalent, I believe that using while(true) is better practice.
A for loop needs three expressions, which are separated by semicolons, and are completely optional:
An initialization (e.g. int i=0)
A condition (e.g. i < 10)
An afterthought (e.g. i++)
In this case, the three expressions are empty, and thus there's no condition that will make the loop stop, thus creating an infinite loop, unless a flow control instruction like break (which will exit the loop) or return is used.
Its an infinite loop. Its equivalent to:
while (true) {
}
The C# compiler directly translates for (; ;) into the exact same construct as while (true).
Infinite loop
same as
while(true){}
the code for(;;){} or while(true){} or while(1){} all represent infinite loops.
An infinite loop is something to be expected in a software system that is expected to run and "unlimited" amount of time. Every OS has at least one - it's how a background task or idle task is implemented.
Real Time systems use infinite loops as well because the system has to handle events which are asynchronous;
Basically anything that runs software uses infinite loops in one way or another.
I don't know why no one answered why people do this instead of while(true): It's because while(true) will often generate a compilation warning that the condition of the loop is constant.
This kind of infinite loop can be used in microcontroleurs. In your main function, you initialize the basic functions of your microcontroleur, then put a while (1).
void MAIN(void)
{
Init_Device();
while(1);
}
The microcontroleur will then do nothing but wait for interrupts of internal or external devices (like a timer overflow, or UART data ready to be read), and react to these interrupts.
I'm using PC Lint for the first time. I was "linting" my code, when PC Lint warns me about my while(TRUE).
This is what it says:
716: while(1) ... -- A construct of the form while(1) ... was found.
Whereas this represents a constant in a context expecting a Boolean,
it may reflect a programming policy whereby infinite loops are
prefixed with this construct. Hence it is given a separate number and
has been placed in the informational category. The more conventional
form of infinite loop prefix is for(;;).
I didn't understand this statement. Can anyone help me to understand it?
The text says that although while(TRUE) (which gets preprocessed into while(1)) is a perfectly valid infinite loop, the more conventional form of writing an infinite loop is
for(;;)
{
...
}
because it doesn't use any values at all and therefore is less error-prone.
It says that the more conventional infinite loop is for(;;), which I'd say is an arguable assertion, and that it's categorized this construct as an "informational category" finding - I suspect that if you used the for(;;) instead it would go away. I've always written these as while(1) and never for(;;) myself. If it does what you expect, I'd ignore the findings of PC LINT on this one or switch it if you're worried about someone redefining TRUE because if someone redefined TRUE your loop wouldn't run at all.