当前位置:网站首页>C language -- 4 first-time constant

C language -- 4 first-time constant

2022-06-10 21:29:00 Try!

1、 Classification of constants

C Constants in languages are divided into the following categories :

  • Literal constants , Such as :10,3.14,“abc”,'a’ etc.
  • const Constant decorated
  • #define Defined identifier constant
  • Enumeration constants

2、const Constant decorated

#include <stdio.h>
int main()
{
    
	int num = 10;// Variable is num
	num = 20;
	printf("%d\n",num);
	return 0;
}

The running result is :20. On this basis will int num = 10; Change it to const int num = 10;, Then run time num=20 There will be an error :
 Insert picture description here
Because you add const The value of the variable is given dead , This value cannot be modified , At this time num It's called “ Constant variable ” instead of “ Variable ” 了 , Has constant attribute ( Properties that cannot be changed ), But still pay attention to , It is also different from constants , Let's verify that it is not the same as a constant .
 Insert picture description here
stay int n = 10; prefix const I still report mistakes , Show “ The expression must contain a constant value ”. So const The modified variable is a constant variable .

3、#define Defined identifier constant

#include <stdio.h>
#define MAX 1000;
int main()
{
    
	int n = MAX;
	printf("%d\n",n);
	return 0;
}

The running result is 1000.

4、 Enumeration constants

Enumerated constants refer to constants that can be enumerated one by one , Such as : When you log in to some software and fill in some information , You can choose male sex 、 Woman , You can also choose “ Private ”.
Want to use enum Keyword to define gender type .

#include <stdio.h>
enum sex
{
    
	male,
	female,
	secret
};// This contains all possible values of the enumeration type 
int main()
{
    
	enum sex s = male;
	printf("%d\n", male);//male It refers to any possible value 
	printf("%d\n", female);
	printf("%d\n", secret);
	return 0;
}

The running result is :

0
1
2

The reason for this running result is : Enumeration constants are constants , Its value starts from zero , The default is 0 At the beginning .
 Insert picture description here

原网站

版权声明
本文为[Try!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101730495701.html