K
Keith Thompson
lovecreatesbeauty said:Richard said:There is simply no way that the compiler can know at compile time how many
elements the user will ask for at run time.
Is following the inconsistent between the standard and implementations?
#include <stdio.h>
int main(void)
{
int len = 10;
char a[len];
switch (sizeof a)
{
case 10:
printf("%s", "10 elements");
break;
default:
printf("<unknow>");
break;
}
fflush(stdout);
return 0;
}
$ gcc test.c
$ ./a.out
10 elements$
$
lovecreatesbeauty
/*quoting begins*/
6.6 Constant expressions
2 A constant expression can be evaluated during translation rather than
runtime, <snip>
6.8.4.2 The switch statement
3 The expression of each case label shall be an integer constant
expression <snip>
/*quoting ends*/
No, there's no inconsistency. The only thing that 6.8.4.2 applies to
in the program is the literal 10 in "case 10:"; that's clearly an
integer constant expression. The expression in parentheses following
the keyword "switch" doesn't need to be constant (the switch statement
wouldn't be very useful if it did).
switch(rand()) {
...
}