1.列表初始化
c++语言定义了初始化的好几种形式,例如:
int a=0;
int a={0};
int a{0};
int a(0);
使用花括号初始化是c++11标准,当用于内置类型的变量时,该种初始化(花括号)有一个重要特点:如果我们使用列表初始化且初始值存在丢失信息的风险,编译器会报错,例如:
double pi=3.1415926;
int a={[pi},b{pi}; //错误,小数点后数据丢失
int c=(pi),d(pi);//正确
2.默认初始化
定义变量是没有初值,变量会被默认初始化。默认值由变量类型和变量位置共同确定:定义于任何函数体外的变量被初始化为0,定义于函数体内部的内置类型变量将不被初始化。一个不被初始化的内置类型的变量值是未定义的,如果试图拷贝或者以其他形式访问此类型值将引发错误(真的很难察觉)。
例如:在test()和test2()函数中定义a,b,默认初始化随机值:
#include <iostream>
using namespace std;
void test();
void test2();
int main(){
test();
test2();
}
void test(){
int a;
cout<<a<<endl;
}
void test2(){
double b;
cout<<b<<endl;
}
输出结果:
2
4.24399e-314
Process finished with exit code 0
将定义放在函数体外,默认变量初始化是0。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void test();
void test2();
int a;
double b;
int main(){
test();
test2();
}
void test(){
cout<<a<<endl;
}
void test2(){
cout<<b<<endl;
}
输出结果:
0
0
Process finished with exit code 0
未初始化的变量含有不确定的值,使用未初始化的变量的值很容易引发程序错且很难调试,因为编译器只是对部分未初始化的变量行为作出警告,但严格来说,编译器并未要求检查此类错。