when should I use do-while, while, for or even goto?
I've been coding in C++ for a while; unfortunately, till this very moment I am still clueless about the differences between all the types of loops.
All I've been told is that don't use goto. (but, to be honest, I have no idea why shouldn't I use this one)
I am also aware of the fact that 'while' loop tests its condition before execution of the contents of the loop begins; the 'do' loop tests it condition after it's been executed at least once.
I heard that sometimes you should use a certain type of loops to optimize the program, but, again, I have no idea when and why.
I would really appreciate if somebody could explain the differences to me. :confused:
Regards, :wave:
Richard
Re: when should I use do-while, while, for or even goto?
Quote:
Originally posted by Vietpub
All I've been told is that don't use goto. (but, to be honest, I have no idea why shouldn't I use this one)
Any program can be written without gotos using a few selected control structures. This is the central dogma of structured programming and the foundation of most popular high-level languages today.
Structured programming demands that you give up your freedom to jump back and forth all over the program and instead restrict yourself to just a few imposed movements like if-then-else and while-do etcetera. The advantage is that the complexity of the program is reduced. It becomes easier to write, read, debug and maintain, in short, it becomes simpler.
Structured programming was very controversial at first. Some felt restrained and said I'd go mad with this strait-jacket. Some saw the benefits and said I would rather kill myself than ever use a goto again. This happened in the 70's and among surviving programmers there's often a very strong sentiment to NEVER EVER USE GOTO.
But things have relaxed and the goto is basically back (if it ever left). I'm thinking of the break statement many languages allow to exit out of loops. The reason why this form of goto is less malign is that it's local. It's confined to a very limited section of code. It still increases structural complexity, BUT it at the same time reduces logical complexity. In plain words you make the loop exit criterium simpler but you trade it for an extra exit jump. I personally prefer a more complex loop structure over a gigant logical exit expression with lots of and's and or's.
In C++ you can just break out of the enclosing loop. You can't break straight out of nested loops. This is one situation when I think a well placed goto is motivated. If you jump out of the innermost loop to the exit point of the outermost loop you remove lots of loop exit checks. This would make your program simpler and that's the ultimate goal of structured programming so that should be allowed I think.
So in my view break, continue and well-placed locally confined gotos are okay even if structured programming affectionados will think otherwise I'm sure. :)