Article Directory
Constant (4 types)
Constant, that is, the amount that cannot be directly modified (const modified constant variables can be modified indirectly, as explained in the subsequent blog).
1. Literal constants
(1) The literal meaning is what it means, and you can know its value and type by looking at its representation.
(2) There are values and no names, which are generally used to initialize variables and are associated with a character.
#include <stdio.h>
int main()
{
10;//int型数字10
'c';//char型字符c
"Hello world!";//字符串常量(!C语言无字符串类型)
int sum=10+20;//10,20为字面常量可直接用
int a=10;//与一种字符相关联
return 0;
}
2.const modified constant variable
(1) Constant variables: In the C language, variables modified with const are called constant variables.
(2) Constant variables have constant attributes and cannot be modified directly (it can be modified indirectly, as explained in the follow-up blog).
(3) const---->One of the C language keywords.
#include <stdio.h>
int main()
{
const int x = 100;//也可写成:int const x = 100;
x = 200;//error!
return 0;
}
3.#define defined identifier constant
3.1 Identifier
(1) Identifiers are the names of variables, functions, files, etc.
(2) Identifiers in C language can only consist of letters (az) (AZ), numbers and underscores (_), and the first character must be a letter or underscore.
(3) The identifier is case sensitive (eg: age, Age, aGe are not the same).
(4) The identifier cannot be the same name as the identifier or keyword predefined by the C compilation system.
(5) Identifier naming must be done ---- see the name knows the meaning.
3.2 Macro Constants
Macro constant: equivalent to renaming a literal constant "macro constant".
eg: #define Age 21 (! No; number)
The following uses three sets of examples to illustrate its usage and precautions:
(1) Macro constants can be used as constants for assignment operations.
#include <stdio.h>
#define Age 21
int main()
{
printf("%d\n", Age);
int x=Age;//可当作常量赋值
printf("%d\n", x);
return 0;
}
(2) The macro can appear in any position, but it is only available after the macro definition.
#include <stdio.h>
int main()
{
printf("%d\n", Age);//error!
#define Age 21
return 0;
}
(3) Once the macro is defined, it cannot be modified in the program. If you want to modify, you only need to change the value behind #define, which improves the maintainability of the code.
#include <stdio.h>
#define Age 21
int main()
{
Age = 18;//error!
return 0;
}
4. Enum constants
Enumeration means enumerating one by one (detailed description in subsequent blogs).
eg:
#include <stdio.h>
enum color//自定义类型---->枚举类型
{
Yellow,//枚举常量
Black,
Green,
Orange
};
int main()
{
enum color a = Yellow;//Yellow在此为常量
return 0;
}
Compiled through: