Fingering->pointers
Sudheendra Hangal's randomly updated weblog

20041005 Tuesday October 05, 2004

Forgot a case ?

It was surprising to see that the following compiles without warning using both the Sun C compiler and gcc:

#include <stdio.h>
int main()
{
    enum {RED, GREEN} color = RED;
    int x = 0;
    switch (color)
    {
      RED: x = 1; break;
      GREEN: x = 2; break;
    }
    printf ("x = %d\n", x);
    return 0;
}

Missed the case keyword and it still compiles fine ?!
(You write this kind of code after staring at too much Verilog)

The semantics of such code appears to be that nothing inside the switch statement is executed. This caused some head-scratching in one of our programs recently. gcc -Wall does report it though; yet another reason to always run it with every compile.

Wonder why the C syntax explicitly permits this:

<selection-statement> ::= if ( <expression> ) <statement>
                        | if ( <expression> ) <statement> else <statement>
                        | switch ( <expression> ) <statement>

<statement> ::= <labeled-statement>
              | <expression-statement>
              | ...

<labeled-statement> ::= <identifier> : <statement>
                      | case <constant-expression> : <statement>
                      | default : <statement>

And as usual, the Java language does not allow you to write nonsense as easily as C:

<switch-statement> ::= switch ( <expression> ) <switch-block>

<switch-block> ::= { {<switch-block-statement-group>}* {<switch-label>}* }

<switch-block-statement-group> ::= {<switch-label>}+ {<block-statement>}+

<switch-label> ::= case <constant-expression> :
                 | default :

(2004-10-05 23:59:48.0) Permalink Comments [1]

Comments:

I agree that this code compiles without any warning in Sun C compiler. However, when I compiled this code in gcc without using -Wall, I did get the following warning:

<code> bash-2.03$ gcc no_warning_without_case.c
no_warning_without_case.c: In function `main':
no_warning_without_case.c:11: warning: unreachable code at beginning of switch statement
bash-2.03$ </code>

It compiles fine if I add the case statement.

Posted by Sharath Ramanathan on December 02, 2004 at 10:06 PM PST #

Post a Comment:

Comments are closed for this entry.

archives
links