• 作用域是程序的一个区域
  • 局部变量
  • 在函数或者代码块内定义声明的变量
  • 形式参数
  • 在函数参数的定义声明的变量
  • 全局变量
  • 在所有函数外部声明的变量
#include <iostream>

using namespace std;
// 全局变量变量声明
int s = 11;

int main(int argc,char *args[]){
// int argc,char *args[]在这里可以称作为函数的形式参数

int k = 0;


// 代码块,也称作局部变量
{
for (int i = 0; i < 10; ++i) {
cout<<i<<endl;
}
}

cout<<"全局变量s:"<<s<<endl;
cout<<"局部变量k:"<<k<<endl;
return 0;
}

C++从入门到精通——变量作用域以及常量_全局变量

  • 同名称局部变量会覆盖全局变量的值
#include <iostream>

using namespace std;
// 全局变量变量声明
int s = 11;

int main(int argc,char *args[]){
// int argc,char *args[]在这里可以称作为函数的形式参数

int s = 0;

cout<<"s:"<<s<<endl;

return 0;



}

C++从入门到精通——变量作用域以及常量_c++_02

  • 常量
  • readonly var_num
  • 常量只读
#include <iostream>
using namespace std;
// 整数常量
const int num = 7;
// 字符常量
const char* seq = "I love you !";
int main(int argc,char *args[]){
// 布尔变量,打印出来是1,0
// 名义上虽然说是1,0。 // 布尔变量,打印出来是1,0
bool is_male= true;
bool is_female= false;
cout<<is_male<<endl;
cout<<is_female<<endl;
// 字符常量
cout<<"\\"<<endl;
cout<<"\t"<<endl;
// 回车符
cout<<"\r"<<endl;

cout<<seq<<endl;
cout<<num<<endl;

}
#include <iostream>
using namespace std;
#define name "tom"
#define user "陈伟峰"
// 整数常量
const int num = 7;
// 字符常量
const char* seq = "I love you !";
int main(int argc,char *args[]){
// 布尔变量,打印出来是1,0
// 名义上虽然说是1,0。 // 布尔变量,打印出来是1,0
bool is_male= true;
bool is_female= false;
cout<<is_male<<endl;
cout<<is_female<<endl;
// 字符常量
cout<<"\\"<<endl;
cout<<"\t"<<endl;
// 回车符
cout<<"\r"<<endl;

cout<<seq<<endl;
cout<<num<<endl;
// 打印预编译常量
cout<<name<<endl;
cout<<user<<endl;

}