可以有人解释这个短段的C ++代码,我不能做头或尾的它 [英] can someone explain this short segment of C++ code, I can't make heads or tails of it
问题描述
#include <opcodes.h>
const char *getOpcodeName(
uint8_t op
)
{
#define OPCODE(x, y) if((0x##y)==op) return "OP_" #x;
OPCODES
#undef OPCODE
return "OP_UNKNOWN";
}
链接到此处的代码: https://github.com/znort987/blockparser/blob/master/opcodes.cpp
这是指向包含的 opcodes.h的链接
我知道这只是一个奇怪的格式化函数,但是,我想知道什么是 *
在函数名的开头表示。我假设它与指针有关系。
I understand this is just a strangely formatted function, however, I am wondering what exactly the *
at the beginning of the function name means. I assume it has something to do with pointers?
此外, #undef
和 #define
语句有效吗?在任一个之后没有分号,其中一个似乎被定义为一行函数。 (0x ## y)
是什么意思? 返回OP_#x
是什么意思?我从来没有遇到过这样的语法。
Also, how are the #undef
and #define
statements valid? There's no semicolon after either one, and one of them seems to be defined as a one-line function. What does (0x##y)
mean? What does return "OP_" #x
mean? I haven't ever come across syntax like this before.
我想更加认真地进入C ++,但是看代码来说明是什么发生了很困难。我如何最有效地学习语法和规则?
I want to get into C++ more seriously, but it's very hard when looking at code to tell what exactly is going on. How can I learn the syntax and rules most effectively?
推荐答案
通过 C ++预处理器,例如使用 g ++ -Wall -C -E opcodes.cpp> opcodes.i
然后查看生成的 opcodes.i
Run your code thru a C++ preprocessor, e.g. using g++ -Wall -C -E opcodes.cpp > opcodes.i
then look inside the generated opcodes.i
#define
不是语句,而是预处理器指令
宏 OPCODES
被扩展为一些大块,主要包含 OPCODE NOP,61)
,其将扩展为类似于
The macro OPCODES
gets expanded to some big chunk, notably containing OPCODE( NOP, 61)
which would get expanded to something like
if ((0x61)==op) return "OP_" "NOP";
两个字符串字符串连接成一个OP_NOP
这里。
The two string literals are concatenated into one, "OP_NOP"
here.
GCC有一个很好的文档 cpp预处理器。了解字符串(单个#
像 OPCODE
宏的结尾 #x;
)和 concatenation (双重 ##
如<$ c OPCODE
宏的$ c>(0x ## y))。
GCC has a good documentation on its cpp preprocessor. Read about stringification (with the single #
like the ending #x;
of the OPCODE
macro) and about concatenation (with a double ##
like (0x##y)
of the OPCODE
macro).
这篇关于可以有人解释这个短段的C ++代码,我不能做头或尾的它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!