Default variable value

后端 未结 9 1788
生来不讨喜
生来不讨喜 2020-11-22 13:21

If I don\'t assign a value to a variable when I declare it, does it default to zero or just whatever was previously in the memory?

e.g.

float x;
         


        
9条回答
  •  面向向阳花
    2020-11-22 13:43

    I think it's undefined. I think some compilers, when compiling in debug mode, initialize it to zero. But it's also ok to have it be whatever was already there in memory. Basically - don't rely on either behavior.

    UPDATE: As per the comments - global variables will be zero-initialized. Local variables will be whatever.

    To answer your second question:

    Thanks - following on from this then, is there a shortcut to assign zero to all of the following?: float x1, x2, x3, x4, x5, y1, y2, y3, y4, y5

    You could do

    float x[5] = {0,0,0,0,0}; float y[5] = {0,0,0,0,0};
    

    and use x[0] instead of x1.

提交回复
热议问题