[Basic knowledge of C language (2)]

Tip: This article is a personal summary of C language data types. If the content is incorrect, please contact me in time for correction.

  • If you reprint, please indicate the originality, thank you.


Preface

Hello everyone, I am Xiao Ming. I am sorry that I have stopped updating for a while due to personal reasons. I will resume normal updates from today. Today I will summarize the knowledge related to C language data types.


insert image description here

提示:以下是本篇文章正文内容:

1. Data type

The data types of C language are a very important part of programming. They have a direct impact on memory management, data operations, code quality, program performance and compatibility.

  • Memory management: Different data types occupy different sizes of memory space. Understanding data types can help us manage memory effectively.
  • Data storage and operations: Data types define the characteristics of the data and the operations that can be performed. For example, the integer type can perform arithmetic operations such as addition, subtraction, multiplication and division, the character type can represent text data, and the array type can store a series of data of the same type, etc.
  • Improve code readability and maintainability: Using appropriate data types can make the code more readable and understandable, and facilitate subsequent maintenance work.
  • Improve program performance: Choosing appropriate data types can improve program execution efficiency. Smaller data types generally require less memory space, which can reduce memory usage and access time.
  • Compatibility and portability: Data types may vary across platforms and compilers. Understanding and correctly using the data types of C language can increase the compatibility and portability of the code, allowing the program to run normally in different environments.

So, let’s take a look at the data types of C language:

type of data name Occupied bytes (32 bits)
char character type 1
short short integer 2
int integer 4
long long integer 4
long long longer integer 8
float Single precision floating point number 4
double Double precision floating point number 8
  • View the code for the data type:
#include <stdio.h>
int main()
{
    
    
	//计算各种数据类型的大小(单位是 字节)
    printf("char:%d\n", sizeof(char));
    printf("short:%d\n", sizeof(short));
    printf("int:%d\n", sizeof(int));
    printf("long:%d\n", sizeof(long));
    printf("long long:%d\n", sizeof(long long));
    printf("float:%d\n", sizeof(float));
    printf("double:%d\n", sizeof(double));

    return 0;
}
  • operation result:
    insert image description here

We can use the sizeof keyword to see the size of the space they each occupy (in bytes).

  • byte:
  • From the above knowledge we can come into contact with a new concept:byte. There are many similar measurement units in our lives, such as: computer C drive, D drive memory, mobile phone common 128G, 256G, 512G memory, etc., as well as the traffic we use when surfing the Internet, 200M traffic, 500G traffic, 1TB traffic, etc. wait.

  • Common storage units in computers are: bit (bit), B (byte), KB (kilobyte), MB (megabyte), GB (gigabyte), TB (terabyte), PB (petabytes).
  • Bytes are the basic unit of data storage and are what the hardware 访问cansmallestunit. The smallest unit of data stored in memory is "bit". Bytes are the basic unit for storing data, and bits are 最小the unit for storing data. Don't get confused. A byte in C language usually consists of an 8-bit binary number, which can represent 256 different values, ranging from 0 to 255.
  • What is stored in the memory is all binary code. There are many "small grids" in the memory, and each "grid" can only store one 0 or 1. A "small grid" is abit(bit), so "bit" is either 0 or 1, and there will be no unit smaller than "bit".
    insert image description here
  • 8 "small grids" are one byte, that is, one byte is equal to 8 bits. (Byte, abbreviated as B)
    Conversion relationships of common storage units: 8Bit = 1B; 1024B = 1KB; 1024KB = 1MB; 1024MB = 1GB; 1024GB = 1TB; 1024TB = 1PB.

2. Variables

1. What are variables?

In real life, we will find a box to store items. Firstly, it will look less messy, and secondly, it will be easier to find later. The same is true for computers. We need to first find an area in the memory, specify it to store the values, and give it an easy-to-remember name. As long as the box is there, the values ​​will be saved and can be taken out and changed freely. numerical value.
insert image description here

2. Definition of variables

程序中用到的变量 必须 “先定义,后使用”。

1. Incomplete initialization:
data type variable name ;

int a;
int b; 
int num;//此时a,b,num的值是随机值

2. Initialization:
data type variable name = initialization ;

int a = 10;
int b = 20;
int num = 999; //声明时初始化

int x; 
x = 999; //先声明变量 x,后初始化为 999

3. Define multiple variables continuously:
data type variable name = initialization , variable name = initialization , variable name = initialization ;

注意:To define multiple variables continuously you need to havesameYes 数据类型, variables can be initialized or not.

//中间以逗号(,)隔开,结尾以分号(;)结束
int a = 10, b = 20 , num = 999;//初始化
int a, b, num; //不初始化

char M, N, P;
int a, b, c;  //两个不同类型定义时需分别定义

3. Naming of variables

Variable naming:

1. It can only consist of letters, numbers, and underscores, and the first character 不能isnumber
2. The identifier of C language isdistinguishUppercase and lowercase, that is, the uppercase and lowercase of a letter, are considered two different characters
3. Cannot be usedKeywordsas variable name

4. Global variables and local variables

全局变量With global scope, it can be accessed anywhere throughout the program.

局部变量Has local scope, it can only be accessed within the curly braces in which it is defined { }.

For example:

#include <stdio.h>

int z = 20;//全局变量

int main()
{
    
    
    int x = 10;//局部变量
    int y = 20;//局部变量
    
    return 0;
}

So if we initialize global variables and local variables with the same name, which value should we use?
We can use a piece of code to judge:

#include <stdio.h>
int year = 2023;//全局变量
int main()
{
    
    
    int year = 2022;//局部变量
    printf("现在是 %d 年\n", year);
    
    return 0;
}

insert image description here
It can be seen that when local variables and global variables have the same name, 局部变量优先使用!

5. Scope and declaration cycle of variables

scope:

Generally speaking, scope refers to the scope of the variable visible in the program.

life cycle:

Lifecycle refers to the time span during which a variable or object exists.

Variable scope and life cycle:

Scope life cycle Defaults
Ordinary global variables It is created when the program runs and destroyed when the program exits. It can be used or referenced by other files. 0
static global variable It is created when the program runs and destroyed when the program exits. Cannot be referenced by other files 0
ordinary local variable It is created when entering this function and destroyed when exiting this function. only valid inside the function random value
static local variable It is created when the function is entered for the first time and is not destroyed until the entire program exits. valid inside the function 0

3. Constants

1. Definition of constants

  • Constants represent some fixed data, that is, data that cannot be changed. For example, gender, boy or girl, pi, etc. are fixed and will not change. (If you insist on wanting to go to Thailand, I can only say that I admire you)

2. Classification of constants

  • #defineDefinedidentifierconstant
  • constmodified constant variable
  • 字面constant
  • 枚举constant

We can understand it from the following code:

#include <stdio.h>
enum Sex
{
    
    
 MALE,
 FEMALE,
 SECRET
};
//括号中的MALE,FEMALE,SECRET是枚举常量
int main()
{
    
    
    //字面常量演示
    // 3.1415926;  //字面常量
    // 2022;  //字面常量
    
    //const 修饰的常变量
    const float p = 3.14f;   //这里的p是const修饰的常变量
    pai = 5.14;//是不能直接修改的!    
    //#define的标识符常量 演示
    #define NUM 100
    printf("num = %d\n", NUM);
    
    //枚举常量演示
    printf("%d\n", MALE);
    printf("%d\n", FEMALE);
    printf("%d\n", SECRET);
    //注:枚举常量的默认是从0开始,依次向下递增1的
    //也可赋值依次递增
     
    return 0;
}

3. Common constant types

Integer constant:

  • Decimal integer.
    For example: 666 , -120 , 0
  • Octal integers and constants in octal form all start with 0.
    For example: 0123 , which is 83 in decimal ; -011 , which is -9 in decimal
  • Hexadecimal integers and hexadecimal constants all start with 0x.
    For example: 0x123 , which is 291 in decimal
  • Binary integer, every 2 is entered as 1, starting with 0b.
    For example: 0b0010 , which is 2 in decimal

Real constants:

  • Decimal form
  • Single precision decimal: ends with the letter f or the letter F.
    For example: 0.0f, 1.01f
  • Double precision decimal: decimal form.
    For example: 3.14, 6.66
  • The default is double precision
  • There can be no integer digits, only decimal digits.
    For example: .3, .6f

  • exponential form
  • Expressed in the form of a power, with a letter eor letter Efollowed by a power of base 10.
    For example: 2E3 or 2e3
    in C language means 2 × 10 in mathematics ² 1.23e4 or 1.23E4 in C language means 1.23 in mathematics ×10⁴, or 12300
  • The exponent after the letter E / emustfor整数
  • Letter E / e before and aftermustMust have数字
  • Letter E / e before and aftercannothave空格

Character constants:

  • Character constants are ' 'enclosed in (single quotes).
    For example: 'a' , 'b' , 'c'
  • Character constants can only have one character within single quotes
  • Special case: If it is an escape character, there can be two characters in single quotes.
    For example: '\n' means carriage return, '\t' means tab character

String constants:

  • Character constants are " "enclosed in double quotes.
    For example: "a" , "abc" , "xiaoming"
  • The system will automatically add a character to the end of the string constant '\0'as a string end mark.

Custom constants:

There is no need to understand it here, we will talk about it later when it comes to

4. Strings and escape characters

1. String

From the strings involved in the above constants, we can summarize it in more detail:


A string of characters enclosed by double quotes such as "hello Xiao Ming" is called a string literal, or simply a string .


Note: The end mark of a string is a \0 escape character. This \0 is the end mark when calculating the length of the string and is not counted as the content of the string.

Let's use two pieces of code to explore the specific role of \0:

#include <stdio.h>
int main()
{
    
    
    char arr1[] = "ming";
    char arr2[] = {
    
    'm', 'i', 'n','g'};
    char arr3[] = {
    
    'm', 'i', 'n','g', '\0'};
    printf("%s\n", arr1);
    printf("%s\n", arr2);
    printf("%s\n", arr3);
    return 0;
}

Results of the:
insert image description here

It can be seen that when there is no \0 at the end, arr2 randomly prints a string that we do not need after printing ming. This is because when initializing the string array, only 'm' and 'i' are initialized. , 'n', 'g', but not '\0', so the printf function will not stop when it reads 'g', it will keep going back until it finds '\0'.

Then we use the strlen function to find the lengths of the three strings to observe the difference between \0 and without \0:

#include <stdio.h>
#include <string.h>
int main()
{
    
    
    char arr1[] = "ming";
    char arr2[] = {
    
     'm', 'i', 'n','g' };
    char arr3[] = {
    
     'm', 'i', 'n','g', '\0' };

    printf("arr1: %d\n", strlen(arr1));
    printf("arr2: %d\n", strlen(arr2));
    printf("arr3: %d\n", strlen(arr3));

    return 0;
}

Results of the:
insert image description here

As can be seen from the above, the two strings arr1 and arr3 with \0 normally have a length of 4, while arr2 without \0 as the end has a random value of 16, which shows that we have no Stop and go all the way back to 12 before encountering \0.

2. Escape characters

In layman's terms, an escape character is a special character that starts with a backslash \ and is used to implement special requirements.

escape character meaning
\n Line break, move from the current position to the next line
\t Horizontal tab (skip to next tab position)
\v vertical tab
\b backspace
\r carriage return
\’ single apostrophe character
\‘’ double apostrophe character
\\ Represents a backslash to prevent it from being interpreted as an escape sequence character
\? question mark to prevent it from being interpreted as a three-letter word
\ddd ddd represents a 1~3 octal number
\xdd dd represents 1~2 hexadecimal digits
\0 null character

Finally, Xiao Ming prepared a piece of code for everyone. You can study the results yourself:

#include <stdio.h>
int main()
{
    
    
    printf("\"hr\bi\'\40mil\bng!\"!\b\n");

    return 0;
}

operation result:
insert image description here

end

Okay, after reading this far, you have finished reading the entire content of this blog.
insert image description here

Guess you like

Origin blog.csdn.net/mingloveyang/article/details/132192204