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.
Related
I am doing Cs50 Harvard University online and I'm on week 3 but while watching the video I noticed that I iterations and loops seem the same, as they repeat things over and over. But there must be a difference or else they wouldn't have two names for the same thing. No matter how many times I re-watch the video I can't find a difference. Please help me understand.
"Loop" refers to language constructs that are used to repeatedly execute some code. (for loops, while loops, etc.)
"Loop" can also refer to code being executed repeatedly. (e.g. "It's stuck in a loop.")
Iterating is the process of doing something repeatedly. (e.g. "This loop iterates over the elements of the array.")
An iteration is a single pass of a loop. (e.g. "In the first iteration of that for loop, i will be 0.")
Usually "loop" refers to the code and "iteration" refers to the conceptual process of repeating some steps. In this case, they are more or less the same. Additionally, you could use "iteration" to refer to a single repetition within a loop which gives it a different meaning.
A case example for the first usage of "iteration" would be:
You can print a linked list either by using iteration or recursion. If you use iteration, simply create a while-loop that propagates a "current" node through the list and stops when it becomes NULL.
And an example refering to specific repetitions:
The following loop outputs numbers 1 to 10 in reverse order. At the k-th iteration, 10-k+1 is printed:
for (i=10; i>=1; i--){
printf("%d\n", i);
}
That's how I would define it:
"Loop" - A control flow statement that iterates the code in the loop's body dependent upon a provided loop condition. It is a language construct and in C we have three kinds of these constructs: for, while and do-while.
"Iteration" - One specific walkthrough of the code inside of the loop's body after the first walkthrough. In other words, a single repetition of the execution of the loop body's code.
When doing looping/iterating (as verb they can be seen equal indeed), you repeat over the code in the loop's body. Every single repetition is an iteration.
A loop's purpose is the capability to do iterations. Without being able to do iterations the loop construct is useless.
So, both terms are closely related, but not the same.
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.)
loop
if rising_edge (CLOCK) then
fcounter := fcounter+1;
end if;
A<=fcounter(6); --fa=fclock/2^6
if rising_edge (A) then
counter_A:= counter_A+1;
end if;
CIKIS<=A; --40 consecutive "1" consignment to DIN for STARTUP RESET
exit when counter_A=101000; --40
end loop;
ISE gives "ERROR:Xst:1312 - Loop has iterated 64 times. Use "set -loop_iteration_limit XX" to iterate more." What does that mean and what should i do to get rid of it?
Unbounded loops are not generally synthesizable outside of generating constants. The error is telling you that the loop has iterated beyond the preset limit that guards against infinite loops. Increasing the limit will not fix anything because what you have described doesn't map naturally to hardware with the current crop of synthesis tools.
You need to restructure your logic to inhibit that block of code with an enable that is deactivated when the counter reaches its terminal value rather than use a loop.
Synthesizable constructs can't have compile time unbounded loops like this, they are only to be used in testbench code. The reason is that when they expand into hardware, something like this would require infinite resources (which you don't have). You seem to be trying to write this like a piece of software. When using a HDL, you need to be thinking of how it translates into hardware (assuming you plan to synthesize). Instead you might look at using a process where all activity happens inside an "if rising_edge(clock)", and use signals to explicitly use flip flops as opposed to variables which could go either way. It isn't entirely clear to me if you're trying to count when your fcounter rolls over 40 times (what you currently do) or when your fcounter exceeds 0111111 for 40 clock cycles, but you can use a signal indicating the state for either case instead of an exit statement, and an if/elsif statement on that signal to do something else when you don't want to have process counting. Sorry for the poor formatting, short on time.
I am asking this question only for the sake of knowledge(because i think it has nothing to do with beginner like me).
I read that C-programmers prefer
for(; ;) {....}
over
while(1) {....}
for infinite loop for reasons of efficiency. Is it true that one form of loop is more efficient than the other, or is it simply a matter of style?
Both constructs are equivalent in behavior.
Regarding preferences:
The C Programming Language, Kernighan & Ritchie,
uses the form
for (;;)
for an infinite loop.
The Practice of Programming, Kernighan & Pike,
also prefers
for (;;)
"For a infinite loop, we prefer for(;;) but while(1) is also popular. Don't use anything other than these forms."
PC-Lint
also prefers
for (;;):
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(;;)
One of the rationale (maybe not the most important, I don't know) that historically for (;;) was preferred over while (1) is that some old compilers would generate a test for the while (1) construct.
Another reasons are: for(;;) is the shortest form (in number of characters) and also for(;;) does not contain any magic number (as pointed out by #KerrekSB in OP question comments).
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.