Home
Fractals
Tutorials
Books
My blog
My LinkedIn Profile

BOOKS i'm reading

Napoleon Hill Keys to Success: The 17 Principles of Personal Achievement, Napoleon Hill, ISBN: 978-0452272811
The 4-Hour Workweek: Escape 9-5, Live Anywhere, and Join the New Rich (Expanded and Updated), Timothy Ferriss, ISBN: 978-0307465351
The Fountainhead, Ayn Rand, ISBN: 0452273331
Web Hosting Canada

mailto:olivier@olivierlanglois.net

switch/case peculiarity: Place the default clause at the end of the switch block to avoid interpretation ambiguity

06/19/07

Permalink 09:33:15 pm, by lano1106, 240 words, 5040 views   English (CA)
Categories: C++

switch/case peculiarity: Place the default clause at the end of the switch block to avoid interpretation ambiguity

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.

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Comments are closed for this post.

Olivier Langlois's blog

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.

April 2024
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        

Search

Custom Search

Misc

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 5

powered by
b2evolution