Unexplained C++ default int values

前端 未结 6 1578
悲哀的现实
悲哀的现实 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:19

    thats a really dangerous assumption your making.

    on a good compiler you might get a constant default value like the closest to -infinity(edit: or 0xCCCCCCCC thx acidezombie24), otherwise you'll just get random numbers

    ALWAYS initialize your variables

    something like

    static const int mouseBufferSize = 10;
    int mouseBufferX[mouseBufferSize];
    memset(mouseBufferX,0,sizeof(mouseBufferX));
    int mouseBufferY[mouseBufferSize];
    memset(mouseBufferY,0,sizeof(mouseBufferY));
    

提交回复
热议问题