糊涂了很久,看了别人的解释,似懂非懂的。今天终于看了stackoverflow里面的解释。自己写了点程序验证了下,终于明白了。
局部变量:作用域在一个block里
例如
if(ture)
{
int i = 0;
}
{
int i = 0;
}
i就是局部变量,作用域就在大括号里。
再看
function()
{
i = 0;
}
{
i = 0;
}
局部变量实质在存放在函数的栈中,每一次invoke函数,都会产生变量i,多次调用i之间是不受影响的。
#include <iostream>
void f();
int main()
{
f();
f();
return 0;
}
void f()
{
std::string localA;
localA += "ab";
std::cout << localA<<"\n";
}
void f();
int main()
{
f();
f();
return 0;
}
void f()
{
std::string localA;
localA += "ab";
std::cout << localA<<"\n";
}
静态局部变量:作用域在namespace scope and local scope and class scope,内存存放在Global data中。但是对于函数的多次调用,是shared变量的值的,因为它不存放在函数栈里面嘛,这个解释的通。
例子:
#include <iostream>
void f();
int main()
{
f();
f();
return 0;
}
void f()
{
static std::string localA;
localA += "ab";
std::cout << localA<<"\n";
}
void f();
int main()
{
f();
f();
return 0;
}
void f()
{
static std::string localA;
localA += "ab";
std::cout << localA<<"\n";
}
全局变量存放地和静态变量一致,但是作用域是定义全局变量的文件scope。如果其他文件需要使用这个变量,需要用extern声明。
全局静态变量同样存放在global里,但是其作用域在translation unit。
下面是关于translation unit的解释:本source文件+include的文件。
A source file toghether with all the headers and source files included via the preprocessing directive #include less any source line skipped by any of the conditional inclusion preprocessing directives is called a translation unit.
A "translation unit" is a source file plus any headers or other source files it #includes, plus any files that THEY include, and so on. A source file is just that...one source file.
A translation unit is the basic unit of compilation in C++. It contains:
- all the contents of a single source file after the preprocessor has run its course
- the contents of any header files directly or indirectly included by it
- minus any lines ignored using conditional preprocessing statements
A single translation unit gets compiled into an object file, library, or executable program.
A source file, by contrast, is a stand-alone file, just like any other file on your file system. Once compiled, it can be a component of a translation unit as mentioned above.