C中的常量和變量都是用來存儲數據的。因此,有必要了解C語言中變量和常量的區別,以便我們根據情況決定使用哪一種。
在本文中,我們將討論 C 語言中常量和變量之間的基本區別。
C 中的變量
A 變量 簡單來說就是分配了一些內存的存儲位置。它用於存儲某種形式的數據並在需要時檢索它。不同類型的變量需要不同數量的內存,並且有一些可以應用於它們的特定操作集。
C 變量聲明
type variable_name; type variable1_name, variable2_name, variable3_name;
變量名稱可以由字母(大寫和小寫)、數字和下劃線‘_’字符組成。但是,名稱不得以數字開頭。
C 變量示例
C
#include <stdio.h>
int main()
{
// declaration and definition of variable 'a123'
char a123 = 'a';
// This is also both declaration
// and definition as 'b' is allocated
// memory and assigned some garbage value.
float b;
// multiple declarations and definitions
int _c, _d45, e;
// Let us print a variable
printf("%c \n", a123);
return 0;
}
輸出:
a
C 中的常量
constants 是 C 語言中的變量或值,一旦在程序中定義就無法修改。
- 它們在程序生命周期內都有固定的值。
- 我們隻能為聲明中的常量賦值。
- 可以是任何類型的常量,如整數、浮點、八進製、十六進製、字符常量等。
C 常數示例
C
#include <stdio.h>
// Constants Macro
#define val 10
// Driver code
int main()
{
// constant variables
const float floatVal = 5.8;
const char charVal = 'a';
// printing constants
printf("Integer Constant: %d\n", val);
printf("Floating point Constant: %f\n", floatVal);
printf("Character Constant: %c\n", charVal);
return 0;
}
輸出
Integer Constant: 10 Floating point Constant: 5.800000 Character Constant: a
常量和變量之間的區別
下表列出了C中常量和變量的區別:
Constant |
Variables |
---|---|
常量是一旦定義就不能更改的變量或值。 | 變量是與某個內存位置關聯的名稱。 |
常量用於保存固定值,我們可以稍後檢索但無法更改。 | 變量用於保存一些可以根據需要更改的值。 |
常量通常存儲在文本段中,因為它們是隻讀的 | 變量存儲在數據段、堆或堆棧中,具體取決於聲明它的環境。 |
我們隻能在定義常量時為其賦值。 | 我們可以隨時給變量賦值。 |
可以使用以下方式定義常量#定義或者常量關鍵詞。 | 變量隻能使用標準變量定義語法來定義。 |
例子:#定義圓周率3.14 常量 int pi = 3.14; |
例子:int var = 25; 變量 = 10; |
相關用法
- C語言 Atoi()用法及代碼示例
- C語言 Getchar()用法及代碼示例
- C語言 abs()用法及代碼示例
- C語言 printf() and scanf()用法及代碼示例
- C語言 strchr()用法及代碼示例
- C語言 strcpy()用法及代碼示例
- C語言 strcat()用法及代碼示例
- C語言 宏 assert()用法及代碼示例
- C語言 isdigit()用法及代碼示例
- C語言 islower()用法及代碼示例
- C語言 setlocale()用法及代碼示例
- C語言 cos()用法及代碼示例
- C語言 cosh()用法及代碼示例
- C語言 sin()用法及代碼示例
- C語言 sinh()用法及代碼示例
- C語言 tanh()用法及代碼示例
- C語言 exp()用法及代碼示例
- C語言 ldexp()用法及代碼示例
- C語言 log()用法及代碼示例
- C語言 log10()用法及代碼示例
- C語言 pow()用法及代碼示例
- C語言 sqrt()用法及代碼示例
- C語言 ceil()用法及代碼示例
- C語言 fabs()用法及代碼示例
- C語言 floor()用法及代碼示例
注:本文由純淨天空篩選整理自sweetsubhashree2013大神的英文原創作品 Difference Between Constants and Variables in C。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。