Initialization of all elements of an array to one default value in C++?

前端 未结 13 1050
礼貌的吻别
礼貌的吻别 2020-11-22 07:59

C++ Notes: Array Initialization has a nice list over initialization of arrays. I have a

int array[100] = {-1};

expecting it to be full with

相关标签:
13条回答
  • 2020-11-22 08:43

    Another way of initializing the array to a common value, would be to actually generate the list of elements in a series of defines:

    #define DUP1( X ) ( X )
    #define DUP2( X ) DUP1( X ), ( X )
    #define DUP3( X ) DUP2( X ), ( X )
    #define DUP4( X ) DUP3( X ), ( X )
    #define DUP5( X ) DUP4( X ), ( X )
    .
    .
    #define DUP100( X ) DUP99( X ), ( X )
    
    #define DUPx( X, N ) DUP##N( X )
    #define DUP( X, N ) DUPx( X, N )
    

    Initializing an array to a common value can easily be done:

    #define LIST_MAX 6
    static unsigned char List[ LIST_MAX ]= { DUP( 123, LIST_MAX ) };
    

    Note: DUPx introduced to enable macro substitution in parameters to DUP

    0 讨论(0)
提交回复
热议问题