Initialization of a normal array with one default value

This question already has an answer here:

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

  • Using the syntax that you used,

    int array[100] = {-1};
    

    says "set the first element to -1 and the rest to 0 " since all omitted elements are set to 0 .

    In C++, to set them all to -1 , you can use something like std::fill_n (from <algorithm> ):

    std::fill_n(array, 100, -1);
    

    In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.


    There is an extension to the gcc compiler which allows the syntax:

    int array[100] = { [0 ... 99] = -1 };
    

    This would set all of the elements to -1.

    This is known as "Designated Initializers" see here for further information.

    Note this isn't implemented for the gcc c++ compiler.


    The page you linked to already gave the answer to the first part:

    If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero.

    There is no built-in way to initialize the entire array to some non-zero value.

    As for which is faster, the usual rule applies: "The method that gives the compiler the most freedom is probably faster".

    int array[100] = {0};
    

    simply tells the compiler "set these 100 ints to zero", which the compiler can optimize freely.

    for (int i = 0; i < 100; ++i){
      array[i] = 0;
    }
    

    is a lot more specific. It tells the compiler to create an iteration variable i , it tells it the order in which the elements should be initialized, and so on. Of course, the compiler is likely to optimize that away, but the point is that here you are overspecifying the problem, forcing the compiler to work harder to get to the same result.

    Finally, if you want to set the array to a non-zero value, you should (in C++, at least) use std::fill :

    std::fill(array, array+100, 42); // sets every value in the array to 42
    

    Again, you could do the same with an array, but this is more concise, and gives the compiler more freedom. You're just saying that you want the entire array filled with the value 42. You don't say anything about in which order it should be done, or anything else.

    链接地址: http://www.djcxy.com/p/78482.html

    上一篇: 哪个更优化:`new`还是`calloc`?

    下一篇: 用一个默认值初始化普通数组