首页 > 代码库 > 定义变量时未初始化赋值的问题
定义变量时未初始化赋值的问题
变量定义时未初始化,导致生命周期结束后,重新定义变量时,仍然保存有之前的数据,或者数据为内存中的随机值。
如下代码:
#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));
否则不能直接读取。
定义变量时未初始化赋值的问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。