#include<iostream>// Variables declared outside of a function are global variablesintg_x{};// global variable g_xvoiddoSomething(){// global variables can be seen and used everywhere in the fileg_x=3;std::cout<<g_x<<'\n';}intmain(){doSomething();std::cout<<g_x<<'\n';// global variables can be seen and used everywhere in the fileg_x=5;std::cout<<g_x<<'\n';return0;}// g_x goes out of scope here
#include<iostream>constintg_x;// 错误:const 常量必须初始化constexprintg_w;// 错误:constexpr 常量必须初始化constintg_y{1};// const global variable g_y, initialized with a valueconstexprintg_z{2};// constexpr global variable g_z, initialized with a valuevoiddoSomething(){// global variables can be seen and used everywhere in the filestd::cout<<g_y<<'\n';std::cout<<g_z<<'\n';}intmain(){doSomething();// global variables can be seen and used everywhere in the filestd::cout<<g_y<<'\n';std::cout<<g_z<<'\n';return0;}// g_y and g_z goes out of scope here