
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
|