此源代码在C中打开字符串.它是如何做到的? [英] This source code is switching on a string in C. How does it do that?
问题描述
我正在阅读一些仿真器代码,并且已经发现了一些真正奇怪的东西:
I'm reading through some emulator code and I've countered something truly odd:
switch (reg){
case 'eax':
/* and so on*/
}
这怎么可能?我以为您只能在整数类型上使用switch
.发生了一些大骗局吗?
How is this possible? I thought you could only switch
on integral types. Is there some macro trickery going on?
推荐答案
(除非您粘贴更多的代码,否则您只能回答宏骗术"部分.但是这里没有太多要处理的宏-正式而言,您可以不允许重新定义关键字;这样做的行为是不确定的.)
(Only you can answer the "macro trickery" part - unless you paste up more code. But there's not much here for macros to work on - formally you are not allowed to redefine keywords; the behaviour on doing that is undefined.)
为了实现程序的可读性,机智的开发人员正在利用实现定义的行为. 'eax'
是不是字符串,而是多字符常量.请非常仔细地注意eax
周围的单引号字符.在您的情况下,很可能会给您提供int
,该字符对于该字符组合是唯一的. (通常每个字符在32位int
中占据8位).大家都知道您可以在int
上使用switch
!
In order to achieve program readability, the witty developer is exploiting implementation defined behaviour. 'eax'
is not a string, but a multi-character constant. Note very carefully the single quotation characters around eax
. Most likely it is giving you an int
in your case that's unique to that combination of characters. (Quite often each character occupies 8 bits in a 32 bit int
). And everyone knows you can switch
on an int
!
最后,一个标准参考文献:
Finally, a standard reference:
C99标准说:
6.4.4.4p10:包含多个字符(例如'ab')或包含一个字符或 不映射到单字节执行的转义序列 字符,是实现定义的."
6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."
这篇关于此源代码在C中打开字符串.它是如何做到的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!