#define(C预处理器)的数组格式

use*_*592 10 c c-preprocessor

可能是一个天真的问题 - 我曾经在20年前编程并且自那时起编码不多.我C preprocessor对此后作品如何萎缩的记忆......

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

两个快速点:我知道我可以arrays根据任何所需的最大尺寸来确定尺寸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];
Run Code Online (Sandbox Code Playgroud)

Fay*_*ure 13

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

#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);
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*odd 11

在以简单的方式执行此操作之前,您需要首先定义一堆帮助程序宏:

#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];
Run Code Online (Sandbox Code Playgroud)

你可以通过样板代码(boost PP,P99)获得一堆预处理器'库',或者你可以自己动手.主要问题是您需要根据您想要处理的最大数量的参数来定义ARG宏.


Pau*_*l R 8

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

#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];
Run Code Online (Sandbox Code Playgroud)

  • 谢谢保罗 - 这有点乱,但可以解决问题。我不知道你能做到这一点。我认为没有“更优雅”的方法吗? (2认同)
  • 我也没有理由认为它应该被投票.再次感谢您的想法. (2认同)

dpc*_*.pw 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
Run Code Online (Sandbox Code Playgroud)