C++ 不同作用域中的静态变量和全局变量

C++ 不同作用域中的静态变量和全局变量,c++,c++11,c++14,C++,C++11,C++14,我是一个初学者程序员…这里我有一段代码,有两个函数…其中一个使用全局变量,另一个使用局部静态变量 下面是代码: //Scope Rules #include <iostream> using namespace std; int num {52}; //Global Variable - Declared outside any class or function void globalExample(); void staticLocalExample(); void

我是一个初学者程序员…这里我有一段代码,有两个函数…其中一个使用全局变量,另一个使用局部静态变量

下面是代码:

//Scope Rules
#include <iostream>
using namespace std;

int num {52};     //Global Variable - Declared outside any class or function

void globalExample();
void staticLocalExample();

void globalExample(){
    cout << "\nGlobal num in globalExample is: " << num << " - start" << endl;
    num *= 4;
    cout << "Global num in globalExample is: " << num << " - end" << endl;
}
void staticLocalExample(){
    static int num {5};      //local to staticLocalExample - retains it's value between calls
    cout << "\nLocal static num in staticLocalExample is: " << num << " - start" << endl;
    num += 20;
    cout << "Local static num in staticLocalExample is: " << num << " - end" << endl;
}

int main() {

    globalExample();
    globalExample();
    staticLocalExample();
    staticLocalExample();

    return 0;
}
//范围规则
#包括
使用名称空间std;
int num{52}//全局变量-在任何类或函数外部声明
void globalExample();
void staticLocalExample();
void globalExample(){

我想我得出了一个结论…所以如果我错了,请告诉我

全局变量:您可以更改它们,并在其范围外或范围内分配不同的数字

静态变量:只能在其范围内更改,不能在其范围外更改

总之,让我们稍微修改一下这段代码:

#include <iostream>
using namespace std;

int num {52};     //Global Variable - Declared outside any class or function

void globalExample();
void staticLocalExample(int x);

void globalExample(){
    cout << "\nGlobal num in globalExample is: " << num << " - start" << endl;
    num *= 4;
    cout << "Global num in globalExample is: " << num << " - end" << endl;
}
void staticLocalExample(int x){
    static int num {5};      //local to staticLocalExample - retains it's value between calls
    cout << "\nLocal static num in staticLocalExample is: " << num << " - start" << endl;
    num += 20;
    cout << "Local static num in staticLocalExample is: " << num << " - end" << endl;
}

int main() {

    globalExample();
    num = 20;
    globalExample();
    staticLocalExample(10);
    staticLocalExample(15);

    return 0;
}
#包括
使用名称空间std;
int num{52};//全局变量-在任何类或函数外部声明
void globalExample();
void staticLocalExample(intx);
void globalExample(){

如果不是完全重复的话,也可能是相关的。这回答了你的问题吗?全局可以在任何地方更改。静态局部只能通过其作用域所在的函数进行更改。这有助于管理代码的复杂性,因为它变大了(相信我,代码库可能会很大)事实上,没有太多其他的问题。正如其他人所说,这一问题最好由一本好书来回答。一本书可以向你展示并解释为什么在全局名称空间中有很多东西是不好的几个原因。ideaC++是当今使用的最复杂和最难的通用编程语言C++的运行大约2000页。没有一本好书,你会发现它很难学很多。
Global num in globalExample is: 52 - start
Global num in globalExample is: 208 - end

Global num in globalExample is: 20 - start     <-------
Global num in globalExample is: 80 - end

Local static num in staticLocalExample is: 5 - start
Local static num in staticLocalExample is: 25 - end

Local static num in staticLocalExample is: 25 - start
Local static num in staticLocalExample is: 45 - end