常量是程序中無法更改的值或變量,例如:10,20,'a',3.4,“c編程”等等。
C語(yǔ)言編程中有不同類型的常量。
| 常量 | 示例 |
|---|---|
| 整數(shù)常量 | 10, 20, 450等 |
| 實(shí)數(shù)或浮點(diǎn)常數(shù) | 10.3, 20.2, 450.6等 |
| 八進(jìn)制常數(shù) | 021, 033, 046等 |
| 十六進(jìn)制常數(shù) | 0x2a,0x7b,0xaa等 |
| 字符常量 | 'a', 'b','x'等 |
| 字符串常量 | "c", "c program", "c in yiibai"等 |
在C語(yǔ)言編程中定義常量有兩種方法。
const關(guān)鍵字#define預(yù)處理器const關(guān)鍵字用于定義C語(yǔ)言編程中的常量。
const float PI=3.14;
現(xiàn)在,PI變量的值不能改變。
示例:創(chuàng)建一個(gè)源文件: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);
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
The value of PI is: 3.141590
請(qǐng)按任意鍵繼續(xù). . .
如果您嘗試更改PI的值,則會(huì)導(dǎo)致編譯時(shí)錯(cuò)誤。
#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);
}
執(zhí)行上面示例代碼,得到以下的錯(cuò)誤 -
Compile Time Error: Cannot modify a const object
#define預(yù)處理器也用于定義常量。稍后我們將了解#define預(yù)處理程序指令。參考以下代碼 -
#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
}
參考閱讀: http://www.yiibai.com/cprogramming/c-preprocessor-define.html