Array initialization with {0}, {0,}?

前端 未结 6 493
死守一世寂寞
死守一世寂寞 2020-12-24 06:00

Say I want to initialize myArray

char myArray[MAX] = {0};  
char myArray[MAX] = {0,};  
char myArray[MAX]; memset(myArray, 0, MAX);  

相关标签:
6条回答
  • 2020-12-24 06:16

    I think the first solution is best.

    char myArray[MAX] = {0};  //best of all
    
    0 讨论(0)
  • 2020-12-24 06:28

    Either can be used

    But I feel the below more understandable and readable ..

      char myArray[MAX]; 
      memset(myArray, 0, MAX);
    
    0 讨论(0)
  • 2020-12-24 06:36

    Assuming that you always want to initialize with 0.

    --> Your first way and 2nd way are same. I prefer 1st.

    --> Third way of memset() should be used when you want to assign 0s other than initialization.

    --> If this array is expected to initialized only once, then you can put static keyword ahead of it, so that compiler will do the job for you (no runtime overhead)

    0 讨论(0)
  • 2020-12-24 06:37

    Actually, in C++, I personally recommend:

    char myArray[MAX] = {};
    

    They all do the same thing, but I like this one better in C++; it's the most succinct. (Unfortunately this isn't valid in C.)

    By the way, do note that char myArray[MAX] = {1}; does not initialize all values to 1! It only initializes the first value to 1, and the rest to zero. Because of this, I recommend you don't write char myArray[MAX] = {0}; as it's a little bit misleading for some people, even though it works correctly.

    0 讨论(0)
  • 2020-12-24 06:39

    They are equivalent regarding the generated code (at least in optimised builds) because when an array is initialised with {0} syntax, all values that are not explicitly specified are implicitly initialised with 0, and the compiler will know enough to insert a call to memset.

    The only difference is thus stylistic. The choice will depend on the coding standard you use, or your personal preferences.

    0 讨论(0)
  • 2020-12-24 06:42

    You can use also bzero fn (write zero-valued bytes)

    #include <strings.h>
    void bzero(void *s, size_t n)
    

    http://linux.die.net/man/3/bzero

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