📜  C 语言中的常量 vs 变量

📅  最后修改于: 2021-09-12 11:23:09             🧑  作者: Mango

不变

顾名思义,C 编程语言中的变量或值被赋予名称常量,一旦定义就不能修改。它们是程序中的固定值。可以有任何类型的常量,如整数、浮点数、八进制、十六进制、字符常量等。每个常量都有一定的范围。太大而无法放入 int 的整数将被视为 long。现在有各种不同的范围,从无符号位到有符号位。在有符号位下,int 的范围从 -128 到 +127,在无符号位下,int 的范围从 0 到 255。

例子:

#include 
  
// Constants
#define val 10
#define floatVal 4.5
#define charVal 'G'
  
// Driver code
int main()
{
    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: 4.500000
Character Constant: G

多变的

简单来说,变量就是分配了一些内存的存储位置。基本上,用于存储某种形式的数据的变量。不同类型的变量需要不同的内存量,并且有一些可以应用于它们的特定操作集。

变量声明:
典型的变量声明格式如下:

type variable_name;

or for multiple variables:
type variable1_name, variable2_name, variable3_name;

变量名可以由字母(大写和小写)、数字和下划线“_”字符。但是,名称不得以数字开头。

例子:

#include 
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

变量和常量的区别

Constants Variable
A value that can not be altered throughout the program A storage location paired with an associated symbolic name which has a value
It is similar to a variable but it cannot be modified by the program once defined A storage area holds data
Can not be changed Can be changed according to the need of the programmer
Value is fixed Value is varying
想要从精选的视频和练习题中学习,请查看C 基础到高级C 基础课程