当定义将某些内容设置为整数时是否需要括号?

问题描述 投票:0回答:1

在 C 中,众所周知

#define
宏应该使用括号。参见例如C 宏和括号中参数的使用

但是,在嵌入式代码中,我经常看到它甚至与整数一起使用。例如:

#define OFFSET (0x100)

当宏只是一个常量整数时,括号的意义是什么?他们可以在什么情况下发挥作用?

c macros embedded c-preprocessor
1个回答
0
投票

What is the point of the parens when the macro is simply a constant integer?

我认为这是为了清晰起见,当包含括号时,它使代码更加明确并且更容易为其他开发人员理解。

此外,这还取决于开发者所熟悉的编码风格。

在宏中使用括号是一个很好的选择,即使在定义常量整数值时也是如此。

这种做法可以帮助您防止微妙的问题和/或使您的代码更易于维护/可读

细微的问题例如:

  • 避免意外的副作用
  • 运算符优先级
  • 类型安全
  • ...
© www.soinside.com 2019 - 2024. All rights reserved.