博学而笃志 切问而近思 仁在其中
详情
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
十六进制常数 0x2a0x7b0xaa
字符常量 'a', 'b','x'
字符串常量 "c", "c program", "c in h3"

在c语言中定义常量的两种方式

在c语言编程中定义常量有两种方法。

  • const关键字
  • #define预处理器

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



下一篇:测试
相关文章
loading......
最新动态
所有评论

loading......

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册