First knowledge of C language (basic knowledge of C language)


Preface
This blog is written for everyone to get acquainted with the C language and understand the code. It is also a reflection of my learning achievements. The content of the article is full of details, and the reading of the article in this film will surely lay a solid foundation for future C language learning (due to the limited level of the author, there are errors in the article, thank you for actively correcting them)

1. What is C language

C language is a general-purpose programming language for computers , which is widely used in low-level development . The design goal of the C language is to provide a programming language that can be compiled in a simple way, handle low-level memory , generate a small amount of machine code , and can run without any operating environment support.
insert image description here

Although the C language provides many low-level processing functions, it still maintains a good cross-platform feature. A C language program written in a standard specification can be compiled on many computer platforms, even including some embedded processors (stand-alone chips or MCU) and supercomputers and other operating platforms .
In the 1980s, in order to avoid differences in the C language grammar used by individual developers, the US National Bureau of Standards formulated a complete set of American National Standard Language Laws for the C language, called ANSIC , as the original standard for the C language. [1] At present, on December 8, 2011, the National Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC) released the C11 standard , which is the third official standard of the C language and the latest standard of the C language. This standard better supports Chinese character function names and Chinese character identifiers, and realizes Chinese character programming to a certain extent.
insert image description here

C language is a process-oriented computer programming language, which is different from object-oriented programming languages ​​such as C++ and Java. Its compilers mainly include Clang, GCC, WIN-TC, SUBLIME , MSVC , Turbo C, etc.

2. The first c language program

insert image description here
Write code on VS:

  1. create project

  2. Create a new source file.c file

  3. write the code
    insert image description hereinsert image description here

    insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

int main()//int是整型
{
    
    
	//写代码的地方
	printf("hello world\n");
	printf("欢迎你\n");

	//printf 是库函数 - C语言的标准库中提供的一个现成的函数-直接可以使用
	//功能是在屏幕上打印信息
    //库函数的使用,是需要包含头文件的,printf需要的头文件叫:stdio.h

	return 0;
}
//非常古老的写法 - 不推荐
void main()
{
    
    
	printf("hehe\n");
}

//可以的
int main(void)//void是在明确表示main函数不接收参数
{
    
    
	//...
	return 0;
}
 
//可以的
int main(int argc, char* argv[])//int argc, char* argv[] 是在指定main函数的参数
{
    
    
	//...
	return 0;
}

Note : 1. When writing C language code, it starts to run from the first line of the main function
2. All characters in the language are English characters

3. Data type

insert image description here

common data types

char //character data type
short //short integer
int // integer
long//long integer
long long//longer integer
float//single-precision floating-point number
double//double-precision floating-point number

Test
insert image description here
the units common in computers for the size of each data type:

1 byte = 8 bit;
1 KB = 1024 byte;
1 MB = 1024 KB;
1 GB = 1024 MB;
1 TB = 1024 GB;
1 PB = 1024 TB;

C language standard:

sizeof(long long)>=sizeof(long)>=sizeof(int)>sizeof(short)>sizeof(char)

4. Constant variables

Some values ​​in life are constant (such as: pi, gender, ID number, blood type, etc.) and
some values ​​are variable (such as: age, weight, salary).
Unchanged value, represented by the concept of constant in C language, becomes value represented by variable in C language.

4.1 Method of defining variables

int age = 150 ;
float weight = 45.5f ; //single-precision floating-point number float
double weight = 45.5 ;//double-precision floating-point number double
char ch = 'w' ;

4.2 Naming of variables

  • Can only be composed of letters, numbers, and underscores (_)
  • cannot start with a number
  • Length cannot exceed 63 characters
  • Case sensitive in variable names 0
  • Variable names cannot use keywords
  • Variable names should be as meaningful as possible

例:
insert image description here
补:
1、数据类型关键字(12个):
(1) char :声明字符型变量或函数
(2) double :声明双精度变量或函数
(3) enum :声明枚举类型
(4) float:声明浮点型变量或函数
(5) int: 声明整型变量或函数
(6) long :声明长整型变量或函数
(7) short :声明短整型变量或函数
(8) signed:声明有符号类型变量或函数
(9) struct:声明结构体变量或函数
(10) union:声明联合数据类型
(11) unsigned:声明无符号类型变量或函数
(12) void :声明函数无返回值或无参数,声明无类型指针(基本上就这三个作用)

2. Control statement keywords (12):
A Loop statement: (1) for: a loop statement (can be understood or expressed in words) (2) do: the loop body of the loop statement (3) while: the loop condition of the loop statement (4) break: jump out of the current loop (5) continue: end the current loop and start the next round of loop B condition statement: (1)if: condition statement (2)else: condition statement negates the branch (used in conjunction with if) (3)goto: unconditional Jump statement C switch statement: (1) switch: used for switch statement (2) case: switch statement branch (3) default: "other" branch in switch statement D return: subroutine return statement (can have parameters
or
not
)

3. Storage type keywords (4):
(1) auto: the declaration of automatic variables is generally not used (2) extern: the declaration of the variable is declared in other files (it can also be regarded as a reference variable) (3) register: the declaration of the accumulator variable (4) static: the declaration of the static variable

4. Other keywords (4): (1) const: declare read-only variables (2) sizeof: calculate the length of the data type (3) typedef: used to alias the data type (of course, there are other functions) (4) volatile: indicates that the variable can be implicitly changed during program execution

4.3 Classification of variables

· Global variables

· Local variables

Code display:

#include<stdio.h>
int global = 2019; //全局变量
int main()
{
    
    
	int local = 2018; //局部变量
	int global = 2020; //局部变量
	printf("global = %d\n", global);
	return 0;
}

Global variables: variables defined outside { } are global variables
Local variables: variables defined inside { } are local variables
When local variables and global variables have the same name, local variables are used first

4.4 Use of variables

#include <stdio.h>
int main()
{
    
    
    int a = 0;
   int b = 0;
    int s = 0;
    printf("输入两个值:>");
    scanf("%d %d", &a, &b);
    s = a + b;
    printf("sum = %d\n", s);
    return 0;
}

insert image description here

The brackets after scanf() contain &!

4.5 Scope and Lifecycle of Variables

1 Scope (space)
Scope (scope) is a programming concept. Generally speaking, the name used in a piece of program code is not always valid/available,
and the code scope that limits the availability of this name is the scope of this name.
The scope of a local variable is the local scope in which the variable resides.
·The scope of global variable is the whole project.

2 Life cycle (time)
The life cycle of a variable refers to a period of time between the creation of the variable and the destruction of the variable. The
life cycle of a local variable is: the life cycle of entering the scope begins, and the life cycle of the out of the scope ends.
·The life cycle of global variables is: the life cycle of the entire program.

4.6 Constants

The definition forms of constants and variables in C language are different.
Constants in C language are divided into

  • literal constant

Example: 100, 'a', 20.0, 3.14 // directly writable values

  • const modified constant variable

Format: const data type variable name

//const 常属性的
//修饰变量

int main()
{
    
    
	const int a = 10;//a 就是const修饰的常变量,但是本质上a还是变量

	printf("a=%d\n", a);
	a = 100;//不可修改
	printf("a=%d\n", a);

	return 0;
}

//数组
int main()
{
    
    
	int arr[10] = {
    
    0};
	const int n = 10;
	int arr2[n] = {
    
     0 };

	return 0;
}

insert image description here

  • Identifier constants defined by #define

Format: #define symbolic constant constant value

#define M 100
int main()
{
    
    
	int arr[M] = {
    
    0};
	printf("%d\n", M);
	int a = M;
	printf("%d\n", a);
	return 0;
}

insert image description here

  • Enumeration constants
    Enumeration: list one by one Three
    primary colors: red green blue
    Gender: male, female, confidential
    Week: 1 2 3 4 5 6 7
//自定义的类型
enum Color
{
    
    
	//枚举常量
	RED,   //0
	GREEN, //1
	BLUE   //2
};

int main()
{
    
    
	enum Color c = RED;

	return 0;
}

//enum是枚举的关键字

enum Sex
{
    
    
	MALE=7,
	FEMALE,
	SECRET
};

int main()
{
    
    
	//enum Sex s = SECRET;
	//enum Sex s2 = MALE;

	printf("%d\n", MALE);
	printf("%d\n", FEMALE);
	printf("%d\n", SECRET);

	return 0;
}

insert image description here

Five. String + escape character + comment

5.1 Strings

“hello world.\n”

This string of characters enclosed by double quotes (Double Quote) is called a string literal (String Literal), or simply a string
.
**Note:** The end of the string is a \0 escape character. When calculating the length of the string, \0 is the end mark, and it is not counted as
the content of the string.

//字符串是可以存放在字符数数组中的
//%s 是打印字符串
#include <string.h>
int main()
{
    
    
	char arr1[] = "abc";
	char arr2[] = {
    
    'a', 'b', 'c'};

	//printf("%s\n", arr1);
	//printf("%s\n", arr2);//会显示烫......因为没有出现\0 不可以用%s打印 
	//strlen是一个库函数 - 求字符串长度的,统计的是字符串中\0之前的字符个数
	printf("%d\n", strlen(arr1));
	printf("%d\n", strlen(arr2));//随机值
	return 0;
}

insert image description here

5.2 Escape characters

Let's say we want to print a directory on the screen: c:\code\test.c
How should we write the code?

#include <stdio.h>
int main()
{
    
    
 printf("c:\code\test.c\n");
    return 0;
}

``The running results are as follows
insert image description here
Here I have to mention the escape character. The escape character, as the name suggests, is to change the meaning.
insert image description here
insert image description here
Note:

a—97 A—65 has a difference of 32, so it can be deduced that each letter
0~31 cannot be printed

  • Octal: 0~7
    insert image description here
  • Hexadecimal:
    insert image description here
  • Computers deal with binary
  • Data is also stored in binary
#include <stdio.h>
int main()
{
    
    
    //问题1:在屏幕上打印一个单引号',怎么做?
    //问题2:在屏幕上打印一个字符串,字符串的内容是一个双引号“,怎么做?
    printf("%c\n", '\'');
    printf("%s\n", "\"");
    return 0;
}

Case Analysis:
insert image description here
Supplement: \t==tab

5.3 Notes

  1. Unnecessary code in the code can be deleted directly or commented out
  2. Some codes in the code are more difficult to understand, you can add a comment text
    such as:
#include <stdio.h>
int Add(int x, int y)
{
    
    
    return x+y;
}
/*C语言风格注释
int Sub(int x, int y)
{
    return x-y;
}
*/
int main()
{
    
    
    //C++注释风格
    //int a = 10;
    //调用Add函数,完成加法
    printf("%d\n", Add(1, 2));
    return 0;
}

There are two styles of comments:
C-style comments/ xxxxxx /
Defect: Cannot nest comments
C++-style comments //xxxxxxxx
can comment one line or multiple lines

6. Select statement

If you study hard, get a good offer during school recruitment, and reach the pinnacle of life.
If you don't study, graduation is equivalent to unemployment, go home and sell sweet potatoes.
This is choice!
insert image description here

Code demo:

int main()
{
    
    
	int input = 0;
	printf("计算机学习课\n");
	printf("你打算好好学习吗?(1/0):");
	scanf("%d", &input);//1 / 0 
	if (input == 1)
	{
    
    
		printf("好offer\n");
	}
	else
	{
    
    
		printf("卖红薯\n");
	}

	return 0;
}

Seven. Loop statement

Some things must be done all the time, such as my lectures day after day, like everyone, study day after day.
Also for example:
insert image description here

How to implement loop in C language?

  • while statement
  • for statement
  • do ... while statement
    //while statement code implementation:
//函数声明
int Add(int x, int y);
int main()
{
    
    
	int a = 0;
	int b = 0;
	int s = 0;
	scanf("%d %d", &a, &b);
	//求和
	//s = a + b;
	//...
	s = Add(a, b);//函数调用
	printf("%d\n", s);

	return 0;
}
//
//函数的定义
int Add(int x, int y)
{
    
    
	int z = x + y;
	return z;
}

  • Functions are characterized by code simplification and code reuse
  • Declare first and then use, definition is also a declaration
  • There can be multiple .c files in a process, but multiple .c files can only be controlled by one main function

Nine. Array

How to store numbers from 1-10?
The definition of an array in C language: a collection of elements of the same type

9.1 Array definition

int arr[5] = { 1,2,3,4,5 };//Define an integer array with up to five elements
int arr1[30] = { 1,2,3,4,5,6,7,8,9,10 };//Incomplete initialization, the remaining elements are initialized to 0 by default

9.2 Array Subscripts

The C language stipulates that each element of the array has a subscript, and the subscript starts from 0 .
Arrays can be accessed by subscripting .
for example:
insert image description here

int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	//              0 1 2 3 4 5 6 7 8 9
	printf("%d\n", arr[7]);
	arr[7] = 18;
	printf("%d\n", arr[7]);
	return 0;
}

operation result:
insert image description here

9.3 Use of arrays

int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	//              0 1 2 3 4 5 6 7 8 9
	int i = 0;
	while (i < 10)
	{
    
    
		printf("%d ", arr[i]);
		i = i + 1;
	}
	return 0;
}

operation result:
insert image description here

10. Operators

  • arithmetic operator
    insert image description here
int main()
{
    
    
	printf("%d\n", 17 / 4);//4...1    / -除法-得到是商
	printf("%d\n", 17 % 4);//4...1    % -取余/取模 - 得到是余数
	printf("%.2lf\n", 17.0 / 4);//double
	printf("%lf\n", 17 / 4.0);//double
	printf("%lf\n", 17.0 / 4.0);//double
	//直接写出的浮点数,会被编译器识别为double类型

	printf("%.2f\n", 17.0f / 4);//float .2表示保留两位有效数字

	return 0;
}

% Both sides must be integers, and
the floating-point numbers written directly will be recognized as double by the compiler

  • shift operator
    insert image description here

binary bits are shifted

  • bitwise operator
    insert image description here

Calculate using binary digits

  • assignment operator

insert image description here

a = a + 5-----a += 5
assignment operator
When the local variable is not initialized, a random value is placed in it (int a = 0/int a)

  • Unary operators (operators with only one operand)
    insert image description here

In C language, 0 means false, non-zero means true
insert image description here
insert image description here
insert image description here

sizeof the type length of the operand in bytes
insert image description here

++ Preposition ++, postposition ++
preposition –, postposition –
(++ is the same as - - formula)
insert image description here
insert image description here

(type) mandatory type conversion
insert image description here
structure information -> int cannot be converted

  • relational operator
    insert image description here
  • logical operator
    insert image description here

&&=And if there is false, then it is false, all true is true
||=Or if there is true, then it is true, all false is false

Code example:

int main()
{
    
    
	//3~5月是春天
	int month = 0;
	scanf("%d", &month);

	//if (3 <= month <= 5)//错误含义
	if(month>=3 && month<=5)
		printf("春天\n");

	return 0;
}


//12 1 2 月是冬天

int main()
{
    
    
	int month = 0;
	scanf("%d", &month);
	if (month == 12 || month == 1 || month == 2)
		printf("冬天\n");
}
  • conditional operator
    insert image description here

insert image description here

  • comma expression
    exp1,exp2,exp3,...expN

Calculated sequentially from left to right, the result of the entire expression is the result of the last calculation
insert image description here

  • Subscript references, function calls and structure members
    insert image description here
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5 };
	printf("%d\n", arr[4]);//[] 下标引用操作符
	return 0;
}

int Add(int x, int y)
{
    
    
	return x + y;
}

int main()
{
    
    
	int z = Add(3, 5);//()函数调用操作符,Add,3,5 是()的操作数

	return 0;
}

11. Common keywords

insert image description here

11.1 Keyword typedefs

typedef, as the name suggests, is a type definition, and here it should be understood as a type renaming.

typedef unsigned int uint;
typedef int INT;

int main()
{
    
    
	unsigned int num = 0;
	uint num2  =0;
	INT num3 = 0;
	int num4 = 0;
	return 0;
}

11.2 The keyword static

In C language:
static is used to modify variables and functions

  1. Decorate local variables - called static local variables
  2. Decorate global variables - called static global variables
  3. Decorator functions - called static functions

11.2.1 Decorating local variables

Case 1:
insert image description here
Case 2:
insert image description here

  • At this time, local variables are static local variables
  • An ordinary local variable enters the function creation and exits the function destruction
  • But after being modified by static, it has been created when entering the function, and it will not be destroyed when the function is exited. When the function is called multiple times, a variable is shared
  • The supervisor's feeling: the life cycle has become longer, but the scope remains the same, and it can only be used locally
  • The essence is : Ordinary local variables are placed on the stack area, but after being modified by static, they are stored in the static area of ​​memory. The life cycle of variables in the static area is the same as that of global variables.

11.2.2 Modifying global variables

Case number one:
insert image description here

Case two:
insert image description here

Global variables have an external link attribute, which determines that when multiple files can use static to
modify global variables, the external link attribute becomes an internal link attribute.
g_val can only be used inside the current
.

11.2.3 Decorating functions

Case number one:
insert image description here

Case two:
insert image description here

The function also has an external link attribute, which determines that the function is a
static modifier that can be used across files. The function is changed from the external link attribute of the function to the internal link attribute,
so that the function can only be used in the .c file where it is located.

Supplement:
stack area, heap area, static area
insert image description here

12. #define defines constants and macros

  • Identifier constants defined by #define

insert image description here

  • #define Defining macros

insert image description here

Thirteen. Pointer

13.1 Memory

Memory is a particularly important memory on the computer, and the running of programs in the computer is carried out in the memory.
Therefore, in order to effectively use the memory, the memory is divided into small memory units, and the size of each memory unit is 1 byte.
In order to be able to effectively access each unit of the memory, the memory units are numbered, and these numbers are called the address of the memory unit.

int main()
{
    
    
	int a = 10;
	//& - 取地址操作符
	int * pa = &a;//0x0012ff48  -内存的编号==地址==指针, pa叫指针变量
	//* 是在说明pa是指针变量
	//int 是在说明pa指向的是int类型的变量
	*pa = 20;//* 解引用操作符 - 通过地址找到地址所指向的对象。*pa就等价于a

	printf("%d\n", a);
	return 0;
}

Summary: 1. Memory will be divided into memory units in units of bytes
2. Each memory unit has a number, number = address = pointer
3. A variable created in C language actually applies for a piece of space from the memory, for example: int a = 10, that is, applies for 4 bytes of space from the memory, and each byte has an address 4. When &a, take out the address (number) of the byte with the smaller address among the 4 bytes. Variable: int *pa = &a; 6. The address of a is stored in pa, how to find a through the address
in
pa
? *pa–> Find a through the address in pa *pa = 20;//The essence is to modify a

13.2 Size of Pointer Variables

insert image description here
repair:
insert image description here

Fourteen. Structure

The structure is a particularly important knowledge point in the C language. The structure makes the C language capable of describing complex types.
For example, to describe a student, the student includes: name + age + gender + student number.
Here only structure can be used to describe.

//学生

//学生类型
//int
struct Stu
{
    
    
	char name[20];
	int age;
	float score;
};

int main()
{
    
    
	int num;

	struct Stu s1 = {
    
    "张三", 20, 88.0f};
	struct Stu s2 = {
    
    "李四", 18, 65.5f};
	struct Stu s3 = {
    
    "王五", 19, 99.8f};

	struct Stu * ps1 = &s1;

	printf("%s %d %f\n", ps1->name, ps1->age, ps1->score);

	//printf("%s %d %f\n", s1.name, s1.age, s1.score);
	//printf("%s %d %f\n", s2.name, s2.age, s2.score);
	//printf("%s %d %f\n", s3.name, s3.age, s3.score);

	//结构体变量.结构体成员
	//结构体指针->结构体成员

	return 0;
}

Unknowingly, the first knowledge of C language came to an end. You must have gained a lot from reading the full text, let us continue to forge ahead together for C language learning. Finally, I will give you a sentence from my favorite writer:
——I love my own condensed and solid thoughts. This is the fulcrum of my life

Guess you like

Origin blog.csdn.net/2201_75642960/article/details/131484059