Bifalgorithm post · Computer science one · While Loops

Why should you avoid a semicolon after a while-loop condition?

Why should you avoid a semicolon after a while-loop condition? (Computer science one · While Loops) — "Consider the following:\n\n1 while(i <= 10);\n\n2 {\n\n3…

Ideas in this flowchart

  • Ein Semikolon nach einer while-Bedingung kann eine Endlosschleife verursachen.
  • Die while-Bedingung bindet die nächste ausführbare Anweisung oder den nächsten Codeblock.
  • Durch das Semikolon wird eine leere Anweisung an die while-Schleife gebunden.
  • Der nachfolgende Codeblock gehört dadurch nicht zur while-Schleife.
  • Die Situation entspricht im Wesentlichen einer while-Schleife mit leerem Rumpf.
  • Die Schleife erhöht die Zählervariable i nicht.
  • Die Bedingung i <= 10 bleibt wahr und die Berechnung läuft unendlich weiter.
  • Der Code ist gültiges Java und kann kompiliert und ausgeführt werden.
  • Einige Compiler warnen vor dem Problem, andere nicht.
  • Das Problem lässt sich durch eine korrekte Syntax vermeiden.
Feed/

Why should you avoid a semicolon after a while-loop condition?

No cover

Channel

Computer science one

1 page

"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 will warn you about this, others will not. It is valid Java and it will compile and run, but obviously won’t work as intended. Avoid this problem by using proper syntax."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.