Unexplained C++ default int values

前端 未结 6 1576
悲哀的现实
悲哀的现实 2021-01-12 04:55

I\'ve been refactoring some code and I noticed some wonky behavior involving an uninitialized int array:

int arr[ARRAY_SIZE];

I set a break

6条回答
  •  礼貌的吻别
    2021-01-12 05:28

    C++ doesn't initialize variables. When a chunk of memory is allocated for the variable, that chunk of memory is left as-is and contains the value it did when it was allocated.

    However, some compilers (like g++, I believe) will automatically initialize things to 0 - but don't depend on this behaviour as it will make your code less portable.

    To get an array to have all the values in it initialized to a value, you can do this:

    int mouseBufferX[mouseBufferSize] = {0};
    
    int mouseBufferY[mouseBufferSize] = {0};
    

    You can provide as many values as you want in the initialization list and the elements will be assigned those values.

提交回复
热议问题