罗浮视窗网站建设,网站支付方案的设计,网站建设需求分析表怎么写,优质网站建设的设计要点C static 修饰全局变量时的作用探究
作为一个c开发者#xff0c;我们面试时经常被问到 static 变量的作用#xff0c;其中有一个问题是#xff0c;static 修饰全局变量时起什么作用。
通常我们会回答#xff0c;“static 修饰全局变量时代表限制这个变量为此源文件可见 static 修饰全局变量时的作用探究
作为一个c开发者我们面试时经常被问到 static 变量的作用其中有一个问题是static 修饰全局变量时起什么作用。
通常我们会回答“static 修饰全局变量时代表限制这个变量为此源文件可见其他源文件无法访问到这个变量“。
但是之前我更多的是认为重点在于限制作用域今天的一个小实验让我对它有了更深入的体会。 这里先问一个问题。
如果我们 在 某个头文件中声明一个 static 变量然后用两个 source file 来引用它可以做到共享全局变量通信吗换句话说某个 cpp 文件改动了它的值另一个cpp能感知到吗
答案是不会实验表明每一个源文件单独有一份属于自己的static 变量所以一个源文件的更改不会影响到另一个源文件这正是面试八股文里 “限制变量为本源文件可见的真正含义”。
头文件 schema.h
#ifndef __SCHEMA__
#define __SCHEMA__
#include stringstatic std::string input_schema R(this is input schema);#endif
源文件 A help.cpp
#include help.hpp#include iostream
using namespace std;
void change_input() {input_schema new input schema;return;
}void show_input() {cout help.cpp: input_schema endl;cout help.cpp: input_schema endl;return;
}
源文件 B main.cpp
#include iostream#include help.hpp
// #include schema.h
using namespace std;int main() {cout main.cpp: input_schema endl;change_input();cout main.cpp: input_schema endl;show_input();// 打印地址cout main.cpp: input_schema endl;return 0;
}输出 main.cpp: this is input schema main.cpp: this is input schema help.cpp: new input schema help.cpp: 0x5631f26841a0 main.cpp: 0x5631f2684180 可以看出 源文件A(help.cpp) 对 input_schema 的修改只有它自身感知到了没有影响到 源文件B. 从打印的地址也可以看出这是两个变量。