I've been reading some code and saw a for loop with no statements, and I tryed to search what it meant and found nothing (probably because if I type something like "What is for(;;)" in google it just reads as if it was "What is for()"). I don't know if it's just a way to like disable a loop and make it not run (cause I tested it once and the code inside de loop didn't run), though I would think people would just comment or erase the loop, and I'm just curious
CodePudding user response:
It's quite the opposite of not running. It's an infinite loop.
for(;;){
console.log("test")
}
Open an new tab and you press F12
and then enter the code above in the developer console you will see that test
gets printed quite often and your browser/ tab will get unresponsive quickly and your PC/ laptop might get louder as the cooler speeds up because the computer is busy looping.
So better quickly kill the tab where you're running it or if you run it in Node kill the process with Ctrl C
.
The code above is equivalent to:
while(true){
console.log("test")
}
The above is JavaScript, but that would also hold true for Java, C, C , C#. Due to for(;;)
being incorrect syntax for these languages it will not do anything in Kotlin, GoLang, Python, Rust, Swift or Groovy (and probably many others).
CodePudding user response:
A for
loop looks like this:
for (init_statement; condition; iteration_expression) statement
This is equivalent to:
{
init_statement ;
while ( condition ) {
statement
iteration_expression ;
}
}
An omitted condition
is equivalent to true
. Omitted init_statement
or iteration_expression
is like an empty statement or expression (does nothing).
So, for(;;) statement
is equivalent to:
{
/* no init_statement */
while ( true ) {
statement
/* no iteration expression */
}
}