4 ms·
I don't understand the example. While(false) means that the loop will not be executed again, which is the opposite of the example with goto.
by goto11 8y ago
I don't understand the example. While(false) means that the loop will not be executed again, which is the opposite of the example with goto.
- n4r9 8y agoRight, exactly. I assumed the parent comment was doing a single iteration of the loop. Maybe I interpreted wrongly.
- int_19h 8y agoA do-loop will always execute the body before checking the condition. So yes, it always executes a single iteration, making it just a block, not really a loop. The whole point of having "do .. while" is so that you can use "break" inside to go to the point immediately after the loop. Yes, with a single check, you might as well just do "if" instead. The actual code involved numerous such checks. Think of code that repeatedly calls various APIs that return error codes; if any call returns a non-success code, the code must immediately exit this block. You can just keep writing nested ifs, but then you start getting crazy nesting levels after a few calls, which makes code pretty hard to read. So, most people prefer to just jump out instead, resulting in a flat code on the success path, with all errors handled with jumps. In C or C-like C++ (sans exceptions), this idiom is extremely common, and usually it's done with "if .. goto error" or something similar, often wrapped in a macro.
- n4r9 8y agoI think I get it. Writing mostly in C# these days, my instinct when facing nested ifs is to break things down into functions, as you can then return from a function call in order to break out of that code block. Admittedly the problem then becomes naming the functions and potentially having to pass a lot of local state around. I guess this is easier to swallow in a class-based language like C# where you can simply wrap the variables into an object or make them fields of the method's class.