The while-while loop
One of the first constructs learned in c is the while loop, with the do-while loop following shortly thereafter. Today, while inspecting some code (whose location I will keep anonymous to protect the guilty), I ran into the wicked uncle of these innocent statements:
The while-while loop
I kid you not. At first I thought, well that's not even legal c; how is this even getting through the compiler? So I isolated it to ensure I wasn't tricked by some conditional compilation, and sure enough, GCC is perfectly fine with it:
So I played with it a bit, to see which condition is actually the one controlling the loop:
It appears to ignore the second condition here.
And then the behaviour in the examples then becomes obvious.
For now I can think of no reasonable reason to format code to look like this naughty while-while loop, and yet the language happily lets you shoot yourself in the foot with it. Beware!
So I played with it a bit, to see which condition is actually the one controlling the loop:
Let the first condition run to 20:
Let the second condition run to 20:
Time limit exceeded???Aha!
Then it occured to me what is happening. These are two entirely independent while loops. Written more clearly, they could look like this:And then the behaviour in the examples then becomes obvious.
For now I can think of no reasonable reason to format code to look like this naughty while-while loop, and yet the language happily lets you shoot yourself in the foot with it. Beware!
Comments
Post a Comment