定义变量时未初始化赋值的问题

变量定义时未初始化,导致生命周期结束后,重新定义变量时,仍然保存有之前的数据,或者数据为内存中的随机值。

如下代码:

#include <iostream>
using namespace std;

typedef struct s_xy
{
    int x;
    int y;
} s_xy;

int main() {
    // your code goes here
    for(int i = 0; i < 3; ++i)
    {
        s_xy point;
        volatile int num;
        if(1 == i)
        {
            // int j = 1
            cout << i << ": FuZhi" << endl;
            num = 3;
            point.x = 1;
            point.y = 2;
        }
        cout << i << ": point.x: " << point.x << endl;
        cout << i << ": num: " << num << endl;
    }
    return 0;
}

以上代码的输出是:

编译器:http://ideone.com/gLxtqh

0: point.x: 1
0: num: 0
1: FuZhi
1: point.x: 1
1: num: 3
2: point.x: 1
2: num: 3

编译器gcc:

0: point.x: 687612(一个随机值)
0: num: 0
1: FuZhi
1: point.x: 1
1: num: 3
2: point.x: 1
2: num: 3

 

所以,一般情况下,定义变量时必须初始化,结构体需要:

memset(&struct_name, 0, sizeof(struct_name));

否则不能直接读取。

posted on 2017-04-24 09:41  _bob  阅读(2060)  评论(1编辑  收藏  举报