On Mon, 27 Oct 2003 00:13:06 -0330, Neil Zanella wrote:
Unlike in pre-C99 versions of C where variables can only be defined at the
beginning of blocks, C99 allows variables to be defined in arbitrary
places inside blocks. However, gcc 3.2.2 seems to reveal that there
are still places where this is illegal. For instance, consider the
following code snippet.
You can't count on conformance of current versions of GCC
to the C99 standard. With that out of the way I'll continue.
int main(void) {
int i = 0;
switch (i) {
case 0:
char ch;
break;
}
}
Here the compiler complains with the error:
hello.c: In function `main':
hello.c:6: parse error before "char"
can anyone explain the reason for the compiler complaint?
The answer is in the C99 grammar. Declarations can appear at
any place within a block because of these productions:
A.2.3 Statements
(6.8.2) compound-statement: { block-item-list? }
(6.8.2) block-item-list: block-item
block-item-list block-item
(6.8.2) block-item: declaration
statement
But you can't put a declaration after a case construct because
of these productions:
A.2.3 Statements
(6.8) statement: labeled-statement
(6.8.1) labeled-statement: case constant-expression : statement
IOW, only a statement can follow a case.
-Sheldon