C++ 学习笔记1 变量的初始化与定义
关键字:变量;声明;初始化;定义;地址;内存
在写C++代码学习的时候,突然遇到在for循环中初始化遍历变量的情况。就很好奇,对于这种循环结构,里面的变量初始化的时候,是每次都会重新真的初始化一个变量,还是只在第一次初始化该变量,后面就不会变。因此有了如下代码:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int i;
for(i = 0;i<5;i ++)
{
for(int j = 0;j<2;j++)
{
cout<< "j = "<<&j<<endl;
}
if(i ==1)
{
int b = 12;
cout<< "b = "<<&b<<endl;;
}
else
{
int d = 12;
cout<< "d = "<<&d<<endl;;
}
int c= 12;
c = c+1;
}
return 0;
}
运行后得到结果如下,我这里是将每次循环的变量的地址进行输出,从该结果可以判断,对于同一个变量,例如j,其地址都是一样的。因此可以认为变量只会初始化一次。
j = 0x9ce4bff914
j = 0x9ce4bff914
d = 0x9ce4bff90c
j = 0x9ce4bff914
j = 0x9ce4bff914
b = 0x9ce4bff910
j = 0x9ce4bff914
j = 0x9ce4bff914
d = 0x9ce4bff90c
j = 0x9ce4bff914
j = 0x9ce4bff914
d = 0x9ce4bff90c
j = 0x9ce4bff914
j = 0x9ce4bff914
d = 0x9ce4bff90c
那么进一步的,对于int i = 12
,这种情况下,值是否会重置呢?因此编写了如下代码
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int i;
for(i = 0;i<5;i ++)
{
for(int j = 0;j<2;j++)
{
//cout<< "j = "<<&j<<endl;
}
if(i ==1)
{
int b = 12;
//cout<< "b = "<<&b<<endl;;
}
int c= 12; //key
c = c+1;
cout<<"c = "<<c<<",c 地址"<< &c<<endl;
}
return 0;
}
结果如下:可以看到,每次c的结果都是12+1,而非累加。可以认为int c = 12
有两个步骤,第一个步骤是指定一个内存,该命令是指运行一次的,而另一个命令则是定义其值,该命令是每次都会运行的。
c = 13,c 地址0x6ca63ff9f0
c = 13,c 地址0x6ca63ff9f0
c = 13,c 地址0x6ca63ff9f0
c = 13,c 地址0x6ca63ff9f0
c = 13,c 地址0x6ca63ff9f0