本篇文章介绍C++语言变量和常量声明、定义和使用,它们的基本数据类型以及作用域(全局、局部)等。
/*
* 【多行注释】
* Author:W;
* 1.变量:基本类型及作用域
* 2.常量
*/
//引入头文件:头文件包含了程序中必需的或有用的信息【单行注释】
#include <iostream>
//命名空间使用
using namespace std;
/*
* 全局变量【系统会自动初始化】
*/
bool isOk;//布尔类型
char c = 'c';//字符型
string path = "image/test.png";//字符串型
int a = 10;//整型
float b = 15.5f;//单精度浮点型
double d = 12.354f;//双精度浮点型
short int f = 10;//短整型
unsigned short int h = 15;//无符号短整型
long int I = 34;//长整型
wchar_t e = 30;//宽字符型,【注意】实际是short int短整型
//枚举类型
enum ColorType
{
White,
Blue,
Yellow,
Red
};
ColorType myColor = Red;
/*常量**/
//方法1:#define预处理器
#define WIDTH 10.5f
#define HEIGHT 2.0f
//方法2:const关键字
const int R = 1;
const float V = 1.25f;
//main程序执行入口函数
int main()
{
/*局部变量
【注意1:系统不会自动初始化,需我们手动赋值】
【注意2:当与全局变量同名时,该函数范围内,会覆盖全局变量的值】
**/
int a = 5;
float size = WIDTH * HEIGHT;
float res = R / V;
cout << "布尔类型 isOK = " << isOk << endl;
cout << "字符型 c = " << c << endl;
cout << "字符串型 path = " << path << endl;
cout << "整型【会覆盖】 a = " << a << endl;
cout << "float型 b = " << b << endl;
cout << "double型 d = " << d << endl;
cout << "短整型 f = " << f << endl;
cout << "无符号短整型 h = " << h << endl;
cout << "长整型 I = " << I << endl;
cout << "宽字符型 e = " << e << endl;
cout << "枚举型 myColor = " << myColor << endl;
cout << "面积 size = " << size << endl;
cout << "余数 res = " << res << endl;
}
运行结果如下