c++全局变量与局部变量初始化情况分析

今天研究了一下c++中全局变量和局部变量在初始化时的赋值情况,发现全局变量和局部变量会有所不同,下面是我的测试结果:

全局变量:

#include <iostream>
using namespace std;
float testFloat;
double testDouble;
int testInt;
char testChar;
int main(){
    cout <<"Hello World";
    cout <<"testInt====="<< testInt;
    cout <<"testDouble====="<< testDouble;
    cout <<"testChar====="<< testChar;
    cout <<"testFloat====="<< testFloat;
    return 0;
}

测试结果:

testInt=====0
testDouble=====0
testChar===== 
testFloat=====0

 

#include <iostream>
using namespace std;
int main(){

    float testFloat;
    double testDouble;
    int testInt; 
    char testChar;
    cout <<"Hello World";
    cout <<"testInt====="<< testInt;
    cout <<"testDouble====="<< testDouble;
    cout <<"testChar====="<< testChar;
    cout <<"testFloat====="<< testFloat;
    return 0;
}

测试结果:

testInt=====0
testDouble=====6.95312e-310
testChar=====
testFloat=====4.9059e-30

通过两次测试结果对比,会发现double类型和float在全局变量和局部变量初始化时的值会有不同,原因在于全局变量会在定义是被系统初始化,按局部变量则不会被初始化,所以在变量定义时需要注意进行手动初始化,不然可能出现意想不到的情况发生,导致查找问题困难

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值