在 C 中将变量声明为常量
可以使用 const 关键字或预处理指令 #define 将变量声明为常量。以下给出了它们的详细信息。
const关键字
可在变量的数据类型前使用“const”关键字将变量声明为常量。常量变量只能初始化一次。常量变量的默认值为零。
使用 const 关键字在 C 中声明常量变量的程序如下所示。
示例
#include <stdio.h>
int main() {
const int a;
const int b = 12;
printf("The default value of variable a : %d", a);
printf("
The value of variable b : %d", b);
return 0;
}以上程序的输出如下所示。
The default value of variable a : 0 The value of variable b : 12
#define 预处理指令
可以使用预处理指令 #define 将变量声明为常量,因为它声明了任意值的别名。
使用预处理指令 #define 在 C 中声明常量变量的程序如下所示。
示例
#include <stdio.h>
#define num 25
int main() {
printf("The value of num is: %d", num);
return 0;
}输出
以上程序的输出如下所示。
The value of num is: 25
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP