使用 C 语法在一行中重新定义宏常量的方法?

Way to redefine a macro constant in just one single line using C syntax?

我想在我的 C 源代码中的某个条件下重新定义宏常量的值。我无法使用条件预处理指令来定义 LEN_OSG,因为是否用另一个值重新定义它是在 运行 时决定的。

我已经拥有的是:

if(condition)                      // proof condition for replacing the value in LEN_OSG.
{
   if(LEN_OSG != CBS_LEN)          // check if LEN_OS already has the value in CBS_LEN.
   {
      #undef LEN_OSG               // undefine macro LEN_OSG by using `#undef` directive.
      #define LEN_OSG CBS_LEN      // recreate the macro LEN_OSG with new value.
   }
}

C 语法是否允许使用另一种方式来缩写它,而不是使用 #undef 指令,然后通过另一个 #define 指令(仅在一行中)用新值重新创建宏?


想要的解决方案应该是这样的:

if(LEN_OSG != CBS_LEN)          // check if LEN_OS already has the value in CBS_LEN.
{
   #redefine LEN_OSG CBS_LEN    // redefine LEN_OS with another value in one line. 
}

您正在尝试将运行时代码执行与预处理器指令混合,即在编译之前就已经生效的东西。
那行不通。

您的代码未按预期运行。 #define 是在编译时执行的,所以你必须使用编译时 #if 来配合它。否则总是执行。

另外,没有#redefine,所以需要两个命令。

如果您有运行时条件,请使用普通变量并在运行时更改其值。