Java: for(;;) vs. while(true)

Semantically, they’re completely equivalent. It’s a matter of taste, but I think while(true) looks cleaner, and is easier to read and understand at first glance. In Java neither of them causes compiler warnings. At the bytecode level, it might depend on the compiler and the level of optimizations, but in principle the code emitted should … Read more

Java How can I break a while loop under a switch statement?

You can label your while loop, and break the labeled loop, which should be like this: loop: while(sc.hasNextInt()){ typing = sc.nextInt(); switch(typing){ case 0: break loop; case 1: System.out.println(“You choosed 1”); break; case 2: System.out.println(“You choosed 2”); break; default: System.out.println(“No such choice”); } } And the label can be any word you want, for example … Read more

How to write a while loop with the C preprocessor?

If you want to implement a while loop, you will need to use recursion in the preprocessor. The easiest way to do recursion is to use a deferred expression. A deferred expression is an expression that requires more scans to fully expand: #define EMPTY() #define DEFER(id) id EMPTY() #define OBSTRUCT(id) id DEFER(EMPTY)() #define EXPAND(…) __VA_ARGS__ … Read more

Continue in nested while loops

UPDATE: This question was inspiration for my article on this subject. Thanks for the great question! “continue” and “break” are nothing more than a pleasant syntax for a “goto”. Apparently by giving them cute names and restricting their usages to particular control structures, they no longer draw the ire of the “all gotos are all … Read more

Why piping input to “read” only works when fed into “while read …” construct? [duplicate]

How to do a loop against stdin and get result stored in a variable Under bash (and other shell also), when you pipe something to another command via |, you will implicitly create a fork, a subshell that is a child of current session. The subshell can’t affect current session’s environment. So this: TOTAL=0 printf … Read more