Search code examples
cembedded

Using arrays in MACROS [C language]


#define VAR_X {1,2,3,4}

I am trying to declare arrays in macros like the one above. I am a little confused about whether it is a correct approach because no compilation error occurs. Let me know the correct approach to declare and use it.


Solution

  • I believe you are asking if you can use the following:

    #define VAR_X {1,2,3,4}
    
    int x[] = VAR_X;
    

    If so, yes. The preprocessor replaces the VAR_X token with a sequence of tokens consisting of {, 1, ,, 2, ,, 3, ,, 4 and }, and this produces valid C code.

    Even the following is valid (although illegible):

    #define X ] = {
    #define Y 1,
    #define Z 3,4};
    
    int x[ X Y 2, Z