1
2
3
4
5
6
7
8
9
10
|
int
main()
{
// start main block
int
nValue = 5;
// nValue created here
double
dValue = 4.0;
// dValue created here
return
0;
}
// nValue and dValue destroyed here
|
因为值,值是在定义的主要功能块的声明,他们都被main()执行完毕。
一块中声明的变量只能在该块内见。因为每个函数都有它自己的块,在一个函数中的变量不能从另一个功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
void
someFunction()
{
int
nValue;
}
int
main()
{
// nValue can not be seen inside this function.
someFunction();
// nValue still can not be seen inside this function.
return
0;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
int
main()
{
int
nValue = 5;
{
// begin nested block
double
dValue = 4.0;
}
// dValue destroyed here
// dValue can not be used here because it was already destroyed!
return
0;
}
// nValue destroyed here
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
int
main()
{
// start outer block
using
namespace
std;
int
x = 5;
{
// start nested block
int
y = 7;
// we can see both x and y from here
cout << x <<
" + "
<< y <<
" = "
<< x + y;
}
// y destroyed here
// y can not be used here because it was already destroyed!
return
0;
}
// x is destroyed here
|