How to initialize all members of an array to the same value?

后端 未结 23 1813
清歌不尽
清歌不尽 2020-11-21 04:34

I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I

23条回答
  •  孤街浪徒
    2020-11-21 05:26

    For statically initializing a large array with the same value, without multiple copy-paste, you can use macros:

    #define VAL_1X     42
    #define VAL_2X     VAL_1X,  VAL_1X
    #define VAL_4X     VAL_2X,  VAL_2X
    #define VAL_8X     VAL_4X,  VAL_4X
    #define VAL_16X    VAL_8X,  VAL_8X
    #define VAL_32X    VAL_16X, VAL_16X
    #define VAL_64X    VAL_32X, VAL_32X
    
    int myArray[53] = { VAL_32X, VAL_16X, VAL_4X, VAL_1X };
    

    If you need to change the value, you have to do the replacement at only one place.

    Edit: possible useful extensions

    (courtesy of Jonathan Leffler)

    You can easily generalize this with:

    #define VAL_1(X) X
    #define VAL_2(X) VAL_1(X), VAL_1(X)
    /* etc. */
    

    A variant can be created using:

    #define STRUCTVAL_1(...) { __VA_ARGS__ }
    #define STRUCTVAL_2(...) STRUCTVAL_1(__VA_ARGS__), STRUCTVAL_1(__VA_ARGS__)
    /*etc */ 
    

    that works with structures or compound arrays.

    #define STRUCTVAL_48(...) STRUCTVAL_32(__VA_ARGS__), STRUCTVAL_16(__VA_ARGS__)
    
    struct Pair { char key[16]; char val[32]; };
    struct Pair p_data[] = { STRUCTVAL_48("Key", "Value") };
    int a_data[][4] = { STRUCTVAL_48(12, 19, 23, 37) };
    

    macro names are negotiable.

提交回复
热议问题