I came across this puzzle here. I can't figure out wh开发者_JAVA百科y NONE is not printed. Any ideas?
#include<stdio.h>
int main()
{
int a=10;
switch(a)
{
case '1':
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defa1ut:
printf("NONE\n");
}
return 0;
}
defa1ut:
is a syntactically valid label, e.g. for a goto
but not the default
of the switch statement.
If you compile with gcc with enough warnings it will point this out:
ajw@rapunzel:/tmp > gcc -Wall -Wextra test.c
test.c: In function ‘main’: test.c:13:15: warning: label ‘defa1ut’ defined but not used
It's a good argument for building with warnings cranked up high and aiming for 0 warnings in every build.
If defa1ut
is a typo for default
and the string "NONE" is printed:
This is because '1'
and 1
is different.
'1'
means the ASCII value of the character '1'
whose value in decimal is 49
. and 1
is an integer.
The first case will be true if the value of a
is 49
or '1'
, but as a=10
so it is neither equal to '1'
nor equals to '2'
and thus default
is executed (if it existed, and defa1ut
is not a typo).
If defa1ut
is not a typo for default
and simply nothing is printed:
In this case you have no default
instead which look like it is defa1ut
which will act as a normal label, so simply nothing will be printed.
default is spelled wrong. and so that case is never reached. http://codepad.org/gQPA6p4s
#include<stdio.h>
int main()
{
int a=10;
switch(a)
{
case '1':
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defalut:
printf("NONE\n");
mickey_mouse:
printf("No Mickey\n");
default :
printf("CORRECT DEFAULT\n");
}
return 0;
}
Since defa1ut is not keyword, it should be addressed with a case
statement.
Why do you think it should be printed?
defa1ut
is different from default
精彩评论