当前位置:网站首页>C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)
C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)
2022-07-04 08:49:00 【Hu Anmin】
What is constant ?
Constant is a fixed value , Will not change during program execution . These fixed values , Also called literal quantity .
Constants can be any basic data type , For example, integer constants 、 Floating-Point Literals 、 character constants , Or string literals , There are also enumeration constants . Constants are like regular variables , It's just that the value of a constant cannot be modified after it's defined .
It's like having boys and girls in real life , Born a boy, always a boy , Born a girl, you will always be a girl , therefore
Gender is a constant in real life
The type of constant
Integer constant
Integer constants can be decimal 、 A constant in octal or hexadecimal . Prefix specifies cardinality :0x or 0X For hexadecimal ,0 For octal , Without prefix, it means decimal by default .
Integer constants can also have a suffix , Suffix is U and L The combination of ,U Represents an unsigned integer (unsigned),L For long integers (long). Suffixes can be uppercase , It can also be lowercase ,U and L In any order .
Here are a few examples of integer constants :
212 /* legal */
215u /* legal */
0xFeeL /* legal */
078 /* Illegal :8 It's not an octal number */
032UU /* Illegal : You can't repeat the suffix */
Here are examples of various types of integer constants :
85 /* Decimal system */
0213 /* octal */
0x4b /* Hexadecimal */
30 /* Integers */
30u /* Unsigned integer */
30l /* long integer */
30ul /* Unsigned long integers */
Floating-Point Literals
Floating point constants consist of integer parts 、 decimal point 、 The fractional part and the exponential part make up . You can use decimal or exponential forms to represent floating-point constants .
When expressed in decimal form , Must contain decimal point 、 Index , Or both . When expressed in exponential form , Must contain integer part 、 The fractional part , Or both . The index with sign is to use e or E Introduced .
Here are some examples of floating-point constants :
3.14159 /* legal */
314159E-5L /* legal */
510E /* Illegal : Incomplete index */
210f /* Illegal : There are no decimals or exponents */
.e55 /* Illegal : Lack of integers or fractions */
character constants
- Character constants are all in ’'( Single quotation marks ) The enclosed . for example :‘a’、‘b’、‘c’
- A character constant can have only one character in a single quotation mark
- A special case : If it's an escape character , There can be two characters in a single quotation mark . for example :‘\n’、‘\t’
String constant
- Character constants are all in ""( Double quotes ) The enclosed . for example :“a”、“abc”、“lnj”
- The system will automatically add a character... To the end of the string constant ’\0’ As a string end flag
Define constants
stay C in , There are two simple ways to define constants :
- Use #define The preprocessor .
- Use const keyword .
Please note that , Define constants as capital letters , Is a good programming practice .
Use #define The preprocessor defines the form of the constant :#define identifier value
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed , It will produce the following results :
value of area : 50
You can also use it const Prefixes declare constants of the specified type :const type variable = value;
See the following example for details :
#include <stdio.h>
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed , It will produce the following results :
value of area : 50
#define Vs const
1. How the compiler handles
- define – Replacement in the preprocessing stage
- const – Determine its value at compile time
2. Type checking
- define – No type , No type safety check , Unexpected errors may occur
- const – There are data types , Type checking occurs at compile time
3. Memory space
- define – Don't allocate memory , What is given is an immediate number , Replace as many times as you use them , There will be multiple copies in memory , Large memory consumption
- const – Allocate space in static storage , There is only one copy in memory while the program is running
4. debugging
- define You can't debug , Because it has been replaced in the precompile phase .
- const Constants can be debugged .
I just want to emphasize here define It's very powerful , Although it has no type detection , Can't debug , Also consider the boundary effect , But just because there is no type detection , Precompiling is done , To make its use more flexible , More powerful , If we can make good use of define, Can often play an unexpected effect .
What is a variable ?
" The amount " According to the data . Variable , It means some unfixed data , That is, the data that can be changed is like the height of people in real life 、 Same weight , It will change with age , So height 、 Weight is an embodiment of variables in real life , There is also the storage grid in the supermarket in real life , The same grid is used by different people in different periods , The items stored in the grid can be changed . When Zhang San uses this grid, it may contain diapers , But when Li Si used this grid, it might be bread
How to define variables
Why define variables ?, Any variable before it's used , It has to be defined first , Storage space is allocated only when variables are defined , Only then has the space to store the number
Why qualify types ?, Used to constrain the type of data stored in variables . Once the type is specified for the variable , Then this variable can only store this type of data , Memory space is extremely limited , Different types of variables take up different sizes of storage space
Why specify a variable name ?, The space to store data means nothing to us , What we need is the value stored in space , Only , With a name , We can get the value in space , like , Your name is Zhang San , His name is Li Si , If there is no name, how to let the other party know that we are talking to him , Is it just feed feed , When there are many people in the mall , You try , Look back
Format 1: Variable type Variable name ;
int a;
float b;
char ch;
Format 2: Variable type Variable name , Variable name ...;
Use commas between multiple variables (,) The number separated
int a,b,c;
The variable name belongs to the identifier , Therefore, the naming principle of identifiers must be strictly observed
How to use variables ?
stay C In language , utilize = Number
Store data into variables , We call it assigning values to variables
int value;
value = 998; // assignment
Be careful :
there = Number , It's not in mathematics “ equal ”, It is C The prestige operator in language , The function is to set the integer constant on the right 998 Assign to the integer variable on the left value , When you assign ,= The left side of the sign must be a variable , For easy code reading , Used to = Add a space on each side of
Initialization of a variable
C In language , The first assignment of a variable , We call it “ initialization , Two forms of initialization :
Define first and then initialize
int value;
value=998;// initialization
When defined, it is initialized at the same time
int a = 10;
int b = 4,c=2;
How to modify variable values ?
Multiple assignment is enough , Each assignment will override the original value
int i = 10;
i = 20; // Change the value of the variable
Value transfer between variables
You can assign the value stored in one variable to another variable
int a = 10;
int b = a; // Is equivalent to a Stored in the 10 Made a copy to b
How to view the value of a variable ?
Use printf Output the value of one or more variables
int a = 10, c = 11;
printf("a=%d, c=%d", a, c);
Output the values of other types of variables
double height 1.75;
char blood 'A';
printf("hei ght=%.2f, What's the blood type %c",height,blood);
Scope of variable ( important )
In any kind of programming , Scope is the area where variables defined in a program exist , Beyond that area variables cannot be accessed . C All variables in a language have their own scope , Variables are defined in different locations , It also has a different scope , According to the scope, it can be divided into two types , Local variables and global variables
local variable
Local variables are also called internal variables , Local variables are defined within code blocks , Its scope is limited to code blocks , Cannot use... After leaving this code block , Let's look at a few cases :
int main(){
int i = 998; // Scope start
return 0;// Scope end
}
Global variables
Global variables are also called external variables , It is a variable defined outside the code block
int i =666;
int main(){
printf("i = %d\n",i);// have access to
return 0;
}
int call(){
printf("i = %d\n",i);// have access to
return 0;
}
Be careful : Variables with the same name cannot be in the same scope
Variables with the same name can be in different scopes
Variable memory analysis
Byte and address
- In order to better understand the storage details of variables in memory , Let's first get to know the memory “ byte ” and “ Address ”
- Each cell represents a byte
- Each byte has its own memory address
- Memory address is continuous
The storage space occupied by a variable , It is related to the type declared when defining variables and the current compilation environment
Determine how much storage space needs to be opened up according to the type declared when defining variables and the current compilation environment , When developing, start with a large memory address ( Memory addressing from large to small ), Save the data to the corresponding memory space that has been opened up
Don't worry , First contact C Language , It's enough for me to know so much first . The details of storage will be explained in more depth again later
section .
边栏推荐
- Openfeign service interface call
- snipaste 方便的截图软件,可以复制在屏幕上
- Cancel ctrl+alt+delete when starting up
- Guanghetong's high-performance 4g/5g wireless module solution comprehensively promotes an efficient and low-carbon smart grid
- Industry depression has the advantages of industry depression
- Four essential material websites for we media people to help you easily create popular models
- Horizon sunrise X3 PI (I) first boot details
- Leetcode topic [array] - 121 - the best time to buy and sell stocks
- Codeforces Round #793 (Div. 2)(A-D)
- Codeforces Global Round 21(A-E)
猜你喜欢
C语言-入门-基础-语法-[运算符,类型转换](六)
OpenFeign 服务接口调用
到底什么才是DaaS数据即服务?别再被其他DaaS概念给误导了
DM8 uses different databases to archive and recover after multiple failures
C#,数值计算(Numerical Recipes in C#),线性代数方程的求解,Gauss-Jordan消去法,源代码
How to re enable local connection when the network of laptop is disabled
[CV] Wu Enda machine learning course notes | Chapter 9
Azure ad domain service (II) configure azure file share disk sharing for machines in the domain service
Redis sentinel mechanism
DM8 command line installation and database creation
随机推荐
ArcGIS应用(二十二)Arcmap加载激光雷达las格式数据
C # implements a queue in which everything can be sorted
deno debugger
Guanghetong's high-performance 4g/5g wireless module solution comprehensively promotes an efficient and low-carbon smart grid
FOC control
What exactly is DAAS data as a service? Don't be misled by other DAAS concepts
How college students choose suitable computers
老掉牙的 synchronized 锁优化,一次给你讲清楚!
微服務入門:Gateway網關
2022 gas examination registration and free gas examination questions
随机事件的关系与运算
@Role of pathvariable annotation
【无标题】转发最小二乘法
Awk from entry to earth (7) conditional statements
Awk from entry to earth (12) awk can also write scripts to replace the shell
How can we make a monthly income of more than 10000? We media people with low income come and have a look
How does Xiaobai buy a suitable notebook
@Role of requestparam annotation
Call Baidu map to display the current position
没有Kubernetes怎么玩Dapr?