initializing an array of ints

前端 未结 7 876
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 05:00

Does anyone have a way to initialize an array of ints (any multi-byte type is fine really), to a non-zero and non -1 value simply? By which I mean, is there a w

7条回答
  •  不知归路
    2020-11-29 05:37

    For initialization to a static value, I have generally considered typing it out to be preferred, as in:

    int arr[30] = {1, 1, 1, 1, ...}; 
    

    In this case, the compiler can (and usually does) spit out optimized initialization in preamble code.

    Sometimes the initialization is more dynamic, as in this example:

    int arr[30];
    int x = fetchSomeValue();
    for(int i=0; i<30; i++) arr[i] = x;
    

    In these cases you have to code it and the general rule is to maximize readability, not minimize typing. This code will be written once and read a multitude of times.

提交回复
热议问题