C语言常量
作者:--
发布时间:2019-11-20
评论:0
阅读:0
常量是程序中无法更改的值或变量,例如:10,20,'a',3.4,“c编程”等等。
c语言编程中有不同类型的常量。
| 常量 |
示例 |
| 整数常量 |
10, 20, 450等 |
| 实数或浮点常数 |
10.3, 20.2, 450.6等 |
| 八进制常数 |
021, 033, 046等 |
| 十六进制常数 |
0x2a,0x7b,0xaa等 |
| 字符常量 |
'a', 'b','x'等 |
| 字符串常量 |
"c", "c program", "c in h3"等 |
在c语言中定义常量的两种方式
在c语言编程中定义常量有两种方法。
1. const关键字
const关键字用于定义c语言编程中的常量。
const float pi=3.14;
现在,pi变量的值不能改变。
示例:创建一个源文件:const_keyword.c,代码如下所示 -
#include <stdio.h>
#include <conio.h>
void main() {
const float pi = 3.14159;
printf("the value of pi is: %f \n", pi);
}
执行上面示例代码,得到以下结果 -
the value of pi is: 3.141590
请按任意键继续. . .
如果您尝试更改pi的值,则会导致编译时错误。
#include <stdio.h>
#include <conio.h>
void main() {
const float pi = 3.14159;
pi = 4.5;
printf("the value of pi is: %f \n", pi);
}
执行上面示例代码,得到以下的错误 -
compile time error: cannot modify a const object
2. #define预处理器
#define预处理器也用于定义常量。稍后我们将了解#define预处理程序指令。参考以下代码 -
#include <stdio.h>
#define pi 3.14
main() {
printf("%f",pi);
}
参考阅读: http://www.h3.com/cprogramming/c-preprocessor-define.html