15

可能是一个幼稚的问题——我在 20 年前就开始编程,从那以后就很少编码了。从那以后,我对这些作品的记忆力C preprocessor大大萎缩了……

我正在编写一个非常简单的C程序,并且我正在尝试声明一些静态全局数组,但是它们的大小arrays将取决于(以非平凡的方式)一个MODE变量。类似于下面的简化示例。

两个要点:我知道我可以arrays根据 any 所需的最大尺寸来调整尺寸MODE,但我不想这样做,因为(与下面的简化示例不同)有时这些尺寸中的一小部分会非常大,而其他的很小。

另外,我想使用静态定义的全局数组——而不是在运行时动态分配它们。我希望编译器在编译时具有大小。

//** Simplified example of what I'd like to do **//    
#define SIZE_LIST_1[5] = {2, 7, 23, 33, 12, 76}  // I don't think this is valid syntax 
#define SIZE_LIST_2[5] = {11, 65, 222, 112, 444}

#define MODE 4
#define S1 SIZE_LIST_1[MODE]
#define S2 SIZE_LIST_2[MODE] 

int a[S1], b[S2];
4

4 回答 4

15

您需要先定义一堆帮助宏,然后才能以简单的方式执行此操作:

#define CONCAT(A,B)         A ## B
#define EXPAND_CONCAT(A,B)  CONCAT(A, B)

#define ARGN(N, LIST)       EXPAND_CONCAT(ARG_, N) LIST
#define ARG_0(A0, ...)      A0
#define ARG_1(A0, A1, ...)  A1
#define ARG_2(A0, A1, A2, ...)      A2
#define ARG_3(A0, A1, A2, A3, ...)  A3
#define ARG_4(A0, A1, A2, A3, A4, ...)      A4
#define ARG_5(A0, A1, A2, A3, A4, A5, ...)  A5
#define ARG_6(A0, A1, A2, A3, A4, A5, A6, ...)      A6
#define ARG_7(A0, A1, A2, A3, A4, A5, A6, A7, ...)  A7
#define ARG_8(A0, A1, A2, A3, A4, A5, A6, A7, A8, ...)      A8
#define ARG_9(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, ...)  A9
#define ARG_10(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, ...)    A10

/* above should be in a pp_helper.h header file or some such */

#define SIZE_LIST_1 ( 2,  7,  23,  33,  12,   76)
#define SIZE_LIST_2 (11, 65, 222, 112, 444, 1000)

#define S1 ARGN(MODE, SIZE_LIST_1)
#define S2 ARGN(MODE, SIZE_LIST_2)

#define MODE 4

int a[S1], b[S2];

您可以使用样板代码(boost PP,P99)获得一堆预处理器“库”,或者您可以自己滚动。主要问题是您需要根据您想要处理的最大数量的参数来定义 ARG 宏。

于 2012-10-10T17:56:13.587 回答
11

可能你能做的最好的事情是这样的:

#define SIZE_LIST_1_0 2
#define SIZE_LIST_1_1 7
#define SIZE_LIST_1_2 23
#define SIZE_LIST_1_3 33
#define SIZE_LIST_1_4 12

#define SIZE_LIST_2_0 11
#define SIZE_LIST_2_1 65
#define SIZE_LIST_2_2 222
#define SIZE_LIST_2_3 112
#define SIZE_LIST_2_4 444

#define MODE 4

#define S1 SIZE_LIST_1_##MODE
#define S2 SIZE_LIST_2_##MODE

int a[S1], b[S2];
于 2012-10-10T17:16:15.490 回答
5

恐怕没有这种可能。

我建议改用以下方法:

#define MODE 0

#define DECLARE_ARRAYS_WITH_SIZES(S1, S2, S3) \
    int arr1[S1]; \
    int arr2[S2]; \
    int arr3[S3];

#if MODE == 0
DECLARE_ARRAYS_WITH_SIZES(3, 6, 7)
#elif MODE == 1
DECLARE_ARRAYS_WITH_SIZES(8, 2, 1)
#endif
于 2012-10-10T17:26:55.153 回答
4

我知道我有点太晚了,但你也可以这样做,这更简单,我认为它不是很快,但对于小程序来说它会成功

#include <stdio.h>
#define SIZE_LIST (int[]){2, 7, 23, 33, 12, 76}

int main(void)
{
    for (int i = 0; i < 6; i++)
        printf("%d\n", SIZE_LIST[i]);
    return (0);
}
于 2021-03-25T18:42:08.323 回答