问题描述
例如:
#include <stdio.h>
void why_cant_we_switch_him(void *ptr)
{
switch (ptr) {
case NULL:
printf("NULL!
");
break;
default:
printf("%p!
", ptr);
break;
}
}
int main(void)
{
void *foo = "toast";
why_cant_we_switch_him(foo);
return 0;
}
gcc test.c -o test
test.c: In function 'why_cant_we_switch_him':
test.c:5: error: switch quantity not an integer
test.c:6: error: pointers are not permitted as case values
只是好奇.这是技术限制吗?
Just curious. Is this a technical limitation?
人们似乎认为只有一个常量指针表达式.但这真的是真的吗?例如,这是 Objective-C 中的一个常见范例(除了 NSString
、id
和 nil
之外,它实际上只有 C,它们只是一个指针,所以它仍然是相关的——我只是想指出 是,事实上,它的一个常见用途,尽管这只是一个技术问题):
People seem to think there is only one constant pointer expression. Is that is really true, though? For instance, here is a common paradigm in Objective-C (it is really only C aside from NSString
, id
and nil
, which are merely a pointers, so it is still relevant — I just wanted to point out that there is, in fact, a common use for it, despite this being only a technical question):
#include <stdio.h>
#include <Foundation/Foundation.h>
static NSString * const kMyConstantObject = @"Foo";
void why_cant_we_switch_him(id ptr)
{
switch (ptr) {
case kMyConstantObject: // (Note that we are comparing pointers, not string values.)
printf("We found him!
");
break;
case nil:
printf("He appears to be nil (or NULL, whichever you prefer).
");
break;
default:
printf("%p!
", ptr);
break;
}
}
int main(void)
{
NSString *foo = @"toast";
why_cant_we_switch_him(foo);
foo = kMyConstantObject;
why_cant_we_switch_him(foo);
return 0;
}
gcc test.c -o test -framework Foundation
test.c: In function 'why_cant_we_switch_him':
test.c:5: error: switch quantity not an integer
test.c:6: error: pointers are not permitted as case values
原因似乎是 switch 只允许整数值(正如编译器警告所说).所以我想一个更好的问题是问为什么会这样?(虽然现在可能为时已晚.)
It appears that the reason is that switch only allows integral values (as the compiler warning said). So I suppose a better question would be to ask why this is the case? (though it is probably too late now.)
推荐答案
Switch 语句只对整数值进行操作.这就是错误消息是开关量不是整数"的原因.我不认为这是一个技术限制,因为它超出了语言语法.
Switch statements operate on integral values only. That's why the error message is "switch quantity not an integer." I don't think it's a technical limitation so much as it's outside the language syntax.
这篇关于为什么没有开关指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!