Concept
Why should you avoid a semicolon after a while condition?
ComputerScienceOne / While Loops
"Consider the following:\n\n1 while(i <= 10);\n\n2 {\n\n3 //perform some action\n\n4 i++; //iteration\n\n5 }\n\nA similar problem occurs: the while keyword and continuation condition bind to the next executable statement or code block. As a consequence of the semicolon, the executable statement that gets bound to the while loop is empty. What happens is even worse: the program will enter an infinite loop. To see this, the code is essentially equivalent to the following:\n\n1 while(i <= 10) {\n\n2 }\n\n3 {\n\n4 //perform some action\n\n5 i++; //iteration\n\n6 }\n\nIn the while loop, we never increment the counter variable i, the loop does nothing, and so the computation will continue on forever! Some compilers may warn you about this, others will not. It is valid C and it will compile and run, but obviously won’t work as intended. Avoid this problem by using proper syntax and good style."
Related Ideas
- Why should you avoid a semicolon after a while-loop condition?ComputerScienceOne · While Loops
- Why should a while-loop condition not end with a semicolon in PHP?ComputerScienceOne · While Loops
- What happens when a while loop never increments its counter?ComputerScienceOne · For Loops
- Why can an extra semicolon make an if statement behave incorrectly?ComputerScienceOne · Computing a Logarithm
- How is a basic while loop structured in Java?ComputerScienceOne · While Loops
- How are while loops structured and styled in PHP?ComputerScienceOne · While Loops
- How are if, if-else, and if-else-if statements written in C?ComputerScienceOne · If, If-Else, If-Else-If Statements
- How does a do-while loop differ from a while loop in C?ComputerScienceOne · Do-While Loops