假设我在一个头文件中定义了一个常量
#define THIS_CONST 'A'
我想将这个常量写入流中。我做了如下操作:
char c = THIS_CONST;
write(fd, &c, sizeof(c))
然而,我想做的是为了简洁和清晰:
write(fd, &THIS_CONST, sizeof(char)); // error
// lvalue required as unary ‘&’ operand
有没有人知道获取字面量指针的宏/其他技巧?我想要一个可以像这样使用的东西:
write(fd, PTR_TO(THIS_CONST), sizeof(char))
注意:我意识到我可以将常量声明为静态常量变量,但这样我无法在 switch/case 语句中使用它们。例如:static const char THIS_CONST = 'A'
...
switch(c) {
case THIS_CONST: // error - case label does not reduce to an integer constant
...
}
有没有一种方法可以在case标签中使用const变量?