此源代码在 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
!
最后,一个标准参考:
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屋!