在C++中定义常量

时间:2019-01-25 23:38:39   收藏:0   阅读:215

在 C++ 中,有两种简单的定义常量的方式:

使用 #define 预处理器:

#define identifier value;
#include <iostream>
using namespace std;
 
#define LENGTH 10   
#define WIDTH  5
#define NEWLINE ‘\n‘
 
int main()
{
 
   int area;  
   
   area = LENGTH * WIDTH;
   cout << area;
   cout << NEWLINE;
   return 0;
}

使用 const 关键字:

const type variable = value;

代码:

#include <iostream>
using namespace std;
 
int main()
{
   const int  LENGTH = 10;
   const int  WIDTH  = 5;
   const char NEWLINE = \n;
   int area;  
   
   area = LENGTH * WIDTH;
   cout << area;
   cout << NEWLINE;
   return 0;
}

 

原文:https://www.cnblogs.com/ConnorShip/p/10322304.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!