C mini-contest

Go guess, what's behaviour of this code:
int foo() {
  while (0) while (1) while (2) ;
}
and this
int foo() {
  while (2) while (1) while (0) ;
}

Both are valid C constructs, of course.

PS: Question itself is rather trivial, but at least to me it demonstrates important aspects of how dangerous implicit boundaries of C statements could be.

PPS: actually code which inspired me on this example was this comparison:

 while (1) {  } while (0); 
 do {  } while (0);
which looking structurally same in fact are parsed completely differently
Comments:

The first program exits immediately after the first while (0) statement, while the second one goes on an infinite loop over the second while (1) statement.

Posted by Gopal Venkatesan on July 03, 2007 at 10:08 AM MSD #

as an aside, none of the programs actually return an int... that's very poor practice.

Posted by Michael van der Westhuizen on July 03, 2007 at 10:56 AM MSD #

first foo() won't execute any while loop. whereas second foo() will execute infinite while loop over while(1).

Posted by Ashish Shukla on July 03, 2007 at 12:33 PM MSD #

Yeah, your answers are correct. Generally with curly brackets put correctly this code become obvious, but wanted to share this code example.

Posted by nike on July 03, 2007 at 05:53 PM MSD #

I \*always\* put braces round any compound statement in C/C++/Java, even a single statement, to avoid this kind of horror: a lesson I learned 20+ years ago when I accidentally inserted a bare ; after a while(expr) and spent a whole week trying to find the problem...

Rgds

Damon

Posted by Damon Hart-Davis on July 03, 2007 at 07:38 PM MSD #

Ditto about the always adding braces for even single-line statements. When I mentor people for software coding, I tell them to code as if they were debugging it at 2am - they certainly will be one day.

Posted by Jeff Bailey on July 07, 2007 at 03:57 PM MSD #

Post a Comment:
  • HTML Syntax: NOT allowed
About

nike

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today