根据#定义的数字定义不同长度的枚举

Define a different length enum based on #defined number

本文关键字:定义 枚举 数字 根据      更新时间:2023-10-16

假设我有

#define l 4

我想要一个看起来像下面的枚举

enum Biscuits{
b1, b2, b3, b4
}

换句话说,饼干的长度取决于l是什么。我能想到的唯一方法是创建另一个包含b1、b2、b3、b4的#定义变量,然后用它来定义饼干。还有别的办法吗?

保持简单(除非您有很多变化):

#if l == 1
enum Biscuits{ b1 };
#elif l == 2
enum Biscuits{ b1, b2 };
#elif ...
#endif

避免预处理器魔术可以提高可读性。

我不知道你希望你的代码有多灵活。我建议使用:

enum Biscuits{
#ifndef l
#error l is not defined
#else
#if (l >= 2 )
   b1, b2
#endif
#if (l >= 4 )
   , b3, b4
#endif
#if (l >= 6 )
   , b5, b6
#endif
#if (l >= 8 )
   , b7, b8
#endif
#endif
};