#include <iostream> using namespace std; int main() { int i = 1; int const j = 1; switch (-1) cout<<"switch(-1)\n" ; switch ( 0) cout<<"switch( 0)\n" ; switch ( 1) i : cout<<"switch( 1) i\n" ; switch ( 1) case 1 : cout<<"switch( 1) case 1\n"; switch ( 1) case j : cout<<"switch( 1) case j\n"; return 0; }I was reading the grammer for the switch statement in Stroustrup's C++ Programming Language, Third Edition, and I saw all of the above represented in the production rules. I thought the 'i:' fragment was very strange, until I realized this 'i' has nothing to do with the 'int i'. The 'i:' is just a statement label. There is no "case in front of it. The first 3 switch statements end up doing nothing. The last two switch statements print. For another example of a crazy switch statement, see Duff's Device: http://research.swtch.com/2008/01/on-duffs-device-and-coroutines.html Reference: The C++ Programming Language by Bjarne Stroustrup, Addison-Wesley, 1997, p. 803.
Friday, November 19, 2010
Switch Statements
The following program compiles:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment