📜  C语言中的常量与变量

📅  最后修改于: 2021-05-26 03:32:22             🧑  作者: Mango

不变

顾名思义,常量是用C编程语言给此类变量或值赋的,一旦定义它们就不能修改。它们是程序中的固定值。可以有任何类型的常量,例如整数,浮点数,八进制,十六进制,字符常量等。每个常量都有一定范围。太大而无法容纳为int的整数将被视为一个长整数。现在有各种范围,从无符号位到有符号位都不同。在有符号位下,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基础课程》。