Consider the following program:
#include <stdio.h> void f(int i) { switch(i) { case 1: printf("case 1\n"); break; default: printf("default\n"); break; case 2: printf("case 2\n"); break; } } int main(int argc, char *argv[]) { f(2); return 0; }
What will be the output?
Intuitively because the cases might be evaluated in the order that they are declared to make 'fall through' possible from one case to the next one by omitting the break statement, the default case might be executed when i value is 2. I have checked my C++ reference book and my C reference book. The C++ one is silent one this issue but I have found this statement from 'The C programming language' book on page 58:
The case labeled default is executed if none of the other cases are satisfied....Cases and the default clause can occur in any order.
I still had doubt so I have compiled the sample program with Microsoft Visual C++.NET 2003 and with gcc version 3.4.4. Both compilers are compliant with what is specified in 'The C programming language' book and the case 2 is executed. Could it be possible that a compiler with a naive implementation create code that behaves as I intuitively reasoned? Maybe so for staying on the safe side and to make the code unambiguous for the maintainers, a good guideline is to always place the default clause at the end of the switch block.
No Comments/Pingbacks for this post yet...
Comments are closed for this post.
I want you to find in this blog informations about C++ programming that I had a hard time to find in the first place on the web.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
<< < | > >> | |||||
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 | 31 |