【C】Initial understanding

Table of contents

【1】What is C language

【2】Interpretation of the first C program

【3】Data type

【4】Variable constant

【4.1】How to define variables

【4.2】Classification of variables

【4.3】Use of variables

【4.4】Scope and life cycle of variables

【4.5】Constant classification

【5】String

【6】Escape characters

【7】Comments

【8】Select statement

【9】Loop statement

【10】Function

【11】Array

【11.1】Array definition

【11.2】Subscript of array

【11.3】Usage of arrays

【12】Operator

【13】Common keywords

【13.1】Keyword typedef

【13.2】Keyword static

【13.2.1】Modify local variables

【13.2.2】Modify global variables

【13.2.3】Modification function

【14】 Define constants and macros #define

【15】Pointer

【15.1】Memory

【15.2】The size of pointer variables

【16】Structure


【1】What is C language

        C language is a general computer programming language that is widely used in low-level development. The design goal of the C language is to provide a programming language that can be easily compiled, handle low-level memory, generate a small amount of machine code, and can run without any runtime environment support.

        Although the C language provides many low-level processing functions, it still maintains good cross-platform characteristics. A C language program written in a standard specification can be compiled on many computer platforms, even including some embedded processors (microcontrollers or (called MCU) and supercomputers and other operating platforms.

        In the 1980s, in order to avoid differences in the C language syntax used by various developers, the American National Bureau of Standards formulated a complete set of American national standard syntax for the C language, called ANSI C, as the original standard for the C language. . [1] Currently on December 8, 2011, the C11 standard released by the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC) is the third official standard of the C language and the latest standard of the C language. This standard is better Supports Chinese character function names and Chinese character identifiers, realizing Chinese character programming to a certain extent.

        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.

Note: The following content is just an overview of the knowledge points, and there will be detailed and in-depth explanations later!

【2】Interpretation of the first C program

【Example code】

// 头文件:头文件是对库函数进行声明的。<stdio.h> 是标准的输入输出文件.
#include <stdio.h>

// main 就是主函数,一个工程有且只能有一个主函数,main 是程序调用入口.
// int 函数的返回值类型 
//()里面为函数的形参,形参是函数外部数据,传递到函数内部的桥梁.
int main(int argc, char *argv[]){
    // {} 是函数体。
    // printf 将() 里面的字体输出到名目上面.
    // ; 分号是结束语句.
    printf("Hello World And Ubuntu!\n");
    
    // return 第一:返回函数值.  第二:结束当前函数.
    return 0;
}

【3】Data type

[Extended description]

  • The smallest storage unit of a computer is binary, and the smallest allocation unit of a computer is bytes.

  • The binary symbol is b.

  • The byte symbol is B.

0000 0000 ~ 1111 1111 | 0 ~ 255

【Correspondence】

1B == 8b 1KB = 1024B1MB = 1024KB1GB = 1024MB1TB = 1024GB1PB = 1024TB1EB = 1024PB

char 		//字符数据类型
short 		//短整型
int 		//整型
long 		//长整型
long long 	//更长的整形
float 		//单精度浮点数
double 		//双精度浮点数
  • Why does this type appear?

  • How is the size of each type proven?

【Example code】

int main() {
	printf("%d\n", sizeof(char));			// 1
	printf("%d\n", sizeof(short));			// 2
	printf("%d\n", sizeof(int));			// 4
	printf("%d\n", sizeof(long));			// 4
	printf("%d\n", sizeof(long long));		// 8
	printf("%d\n", sizeof(float));			// 4
	printf("%d\n", sizeof(double));			// 8
	printf("%d\n", sizeof(long double));	// 8
	return 0;
}

// 类型的使用
char ch = 'w';
int weight = 120;
int salary = 20000;

Note: The existence of so many types is actually to express various values ​​in life more abundantly.

【4】Variable constant

Some values ​​in life are constant (such as: pi, gender, ID number, blood type, etc.).

Some values ​​are variable (for example: age, weight, salary).

Invariant values ​​are represented by the concept of constants in C language, and variable values ​​are represented by variables in C language.

【4.1】How to define variables

【Example code】

int age = 150;
float weight = 45.5f;
char ch = 'w';

【4.2】Classification of variables

  • local variables

  • global variables

【Example code】

#include <stdio.h>

int global = 2019;//全局变量
int main()
{
	int local = 2018;//局部变量
	//下面定义的global会不会有问题?
	int global = 2020;//局部变量
	printf("global = %d\n", global);
	return 0;
}

Summary: There is actually nothing wrong with the definition of the local variable global variable above

【4.3】Use of variables

【Example code】

#include <stdio.h>

int main() {
	int num1 = 0;
	int num2 = 0;
	int sum = 0;
	printf("输入两个操作数:>");
	scanf("%d %d", &num1, &num2);

	sum = num1 + num2;
	
	printf("sum = %d\n", sum);
	return 0;
}

【4.4】Scope and life cycle of variables

Scope is a programming concept. Generally speaking, the name used in a piece of program code is not always valid/available, and the code range that limits the availability of the name is the scope of the name.

  • The scope of a local variable is the local scope where the variable is located.

  • The scope of global variables is the entire project.

    Life cycle  , the life cycle of a variable refers to the period of time between the creation of the variable and the destruction of the variable.

  • The life cycle of local variables is: the life cycle begins when entering the scope and ends when leaving the scope.

  • The life cycle of global variables is: the life cycle of the entire program.

【4.5】Constant classification

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

  • Literal constant.

  • const modified constant variable.

  • #define defined identifier constant.

  • Enum constants.

【Example code】

#include <stdio.h>

// 举例枚举类型
enum Sex {
	MALE,
	FEMALE,
	SECRET
};

//括号中的MALE,FEMALE,SECRET是枚举常量
int main() {
	//字面常量演示
	3.14;//字面常量
	1000;//字面常量
	
	//const 修饰的常变量
	const float pai = 3.14f; //这里的pai是const修饰的常变量
	pai = 5.14;//是不能直接修改的!❌
	
	//#define的标识符常量 演示
#define MAX 100
	printf("max = %d\n", MAX);
	
	//枚举常量演示
	printf("%d\n", MALE);
	printf("%d\n", FEMALE);
	printf("%d\n", SECRET);
	//注:枚举常量的默认是从0开始,依次向下递增1的
	return 0;
}

Note: The above examplepaiis called aconstmodified constant variable.constThe modified constant variable in C language only limits the variable at the grammatical level andpaicannot be changed directly, butpaiit is still a variable in essence, so it is called a constant variable.

【5】String

"hello bit.\n"

        This (Double Quote)string of characters enclosed in double quotes is called a string literal (String Literal), or simply a string.

【Example code】

#include <stdio.h>

// 下面代码,打印结果是什么?为什么?(突出'\0'的重要性)
int main() {
	char arr1[] = "bit";
	char arr2[] = { 'b', 'i', 't' };
	char arr3[] = { 'b', 'i', 't', '\0' };
	printf("%s\n", arr1);
	printf("%s\n", arr2);
	printf("%s\n", arr3);
	return 0;
}

[Illustrated reference]

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

【6】Escape characters

If we want to print a to the screen, 目录: how do we write the code?c:\code\test.c

【Example code】

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

实际上程序运行的结果是这样的:
c:code est.c

I have to mention escape characters here. As the name suggests, escape characters change meaning. Let’s look at some escape characters:

escape character Definition
\? Used when writing multiple question marks in a row to prevent them from being parsed into three-letter words
' used to represent character constants'
\“ Used to represent double quotes inside a string
\ Used to represent a backslash, preventing it from being interpreted as an escape sequence character.
\a Warning character, buzzer
\b backspace character
\f paper feed character
\n newline
\r Enter
\t horizontal tab
\v vertical tab
\ddd ddd represents 1 to 3 octal digits. For example: \130 X
\xdd dd represents 2 hexadecimal digits. For example: \x30 0
#include <stdio.h>
int main() {
	//问题1:在屏幕上打印一个单引号',怎么做?
	//问题2:在屏幕上打印一个字符串,字符串的内容是一个双引号“,怎么做?
	printf("%c\n", '\'');
	printf("%s\n", "\"");
	return 0;
}

[Written test question] Find the length of a string.

//程序输出什么?
#include <stdio.h>
int main() {
	printf("%d\n", strlen("abcdef"));
	// \62被解析成一个转义字符
	printf("%d\n", strlen("c:\test\628\test.c"));
	return 0;
}

// "c:\test\628\test.c"
// c    :    \t   e    s    t   \62    8   \t   e    s    t    .    c 

【7】Comments

If there are unnecessary codes in the code, you can delete them directly or comment them out. Some codes in the code are difficult to understand, so you can add comments.

Comments come in two styles:

  • C language style comments/ xxxxxx /, defect: comments cannot be nested.

  • C++ style comments //xxxxxxxx can comment on one line or multiple lines.

【Example code】

#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;
}

【8】Select statement

        If you study hard, get a good offer during school recruitment, and reach the top of your life. If you don't study, graduation means unemployment, and you go home and sell sweet potatoes. This is your choice!

【Example code】

#include <stdio.h>

int main() {
	int coding = 0;
	printf("你会去敲代码吗?(选择1 or 0):>");
	scanf("%d", &coding);
	if (coding == 1) {
		printf("坚持,你会有好offer\n");
	}
	else {
		printf("放弃,回家卖红薯\n");
	}
	return 0;
}

【9】Loop statement

        Some things must be done all the time, such as my lectures day after day, and everyone's study day after day.

How to implement loop in C language?

【Example code】

//while循环的实例
#include <stdio.h>
int main() {
	printf("努力学习\n");
	int line = 0;
	while (line <= 20000) {
		line++;
		printf("我要继续努力敲代码\n");
	}
	
	if (line > 20000)
		printf("好offer\n");
	return 0;
}

【10】Function

        The characteristics of functions are code simplification and code reuse.

【Example code】

int main()
{
	int num1 = 0;
	int num2 = 0;
	int sum = 0;
	printf("输入两个操作数:>");
	scanf("%d %d", &num1, &num2);
	sum = num1 + num2;
	printf("sum = %d\n", sum);
	return 0;
}

// ----------------------------------------------------------------------------------

// 上述代码,写成函数如下:
#include <stdio.h>
int Add(int x, int y)
{
	int z = x + y;
	return z;
}

int main()
{
	int num1 = 0;
	int num2 = 0;
	int sum = 0;
	printf("输入两个操作数:>");
	scanf("%d %d", &num1, &num2);
	sum = Add(num1, num2);
	printf("sum = %d\n", sum);
	return 0;
}

【11】Array

The definition of array is given in C language: a set of elements of the same type.

【11.1】Array definition

【Example code】

int arr[10] = {1,2,3,4,5,6,7,8,9,10};//定义一个整形数组,最多放10个元素

【11.2】Subscript of array

C language stipulates that each element of the array has a subscript, and the subscript starts from 0. The array can be accessed through the subscript.

【Example code】

int arr[10] = {0};
//如果数组10个元素,下标的范围是0-9

【11.3】Usage of arrays

【Example code】

#include <stdio.h>
int main()
{
	int i = 0;
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	for (i = 0; i < 10; i++)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
	return 0;
}

【12】Operator

  • arithmetic operators

+ - * / %
  • shift operator

>> <<
  • Bit operators

& ^ |
  • assignment operator

= += -= *= /= &= ^= |= >>= <<=
  • Unary operator

! 			// 逻辑反操作
- 			// 负值
+ 			// 正值
& 			// 取地址
sizeof  	// 操作数的类型长度(以字节为单位)
~ 			// 对一个数的二进制按位取反
-- 			// 前置、后置--
++ 			// 前置、后置++
* 			// 间接访问操作符(解引用操作符)
(类型)   	   // 制类型转换
  • Relational operators

>			// 大于
>=			// 大于等于
<			// 小于
<=			// 小于等于
!= 			// 用于测试“不相等”
== 			// 用于测试“相等”
  • Logical operators

&& 			// 逻辑与
|| 			// 逻辑或
  • conditional operator

exp1 ? exp2 : exp3
  • comma expression

exp1, exp2, exp3, …expN
  • Subscript reference

[] 
  • function call

() .
  • structure member

->

【13】Common keywords

        C language provides a wealth of keywords, which are preset by the language itself. Users cannot create keywords themselves.

auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
    
char        // 字符类型
short       // 短整型
int         // 整型
long        // 长整型
float       // 单精度浮点数
double      // 双精度浮点数
    
register    // 寄存器变量
static      // 静态变量
const       // 只读变量
auto        // 自动变量
extern      // 声明变量外部可用(告知编译器 该变量在其他源文件定义 此处请通过编译)

sizeof      // 测量类型的大小
typedef     // 给类型取别名
volatile    // 防止编译器优化

if  else  switch  case  default  // 条件控制语句
for while break continue goto    // 循环控制语句 

【13.1】Keyword typedef

    typedefAs the name suggests, it is type definition, which should be understood as type renaming.

【Example code】

//将unsigned int 重命名为uint_32, 所以uint_32也是一个类型名
typedef unsigned int uint_32;
int main()
{
	//观察num1和num2,这两个变量的类型是一样的
	unsigned int num1 = 0;
	uint_32 num2 = 0;
	return 0;
}

【13.2】Keyword static

staticIt is used to modify variables and functions

  • Modified local variables - called static local variables .

  • Modified global variables - called static global variables .

  • Decorated functions - called static functions  .

【13.2.1】Modify local variables

//代码1
#include <stdio.h>
void test()
{
	int i = 0;
	i++;
	printf("%d ", i);
}

int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		test();
	}
	return 0;
}

//代码2
#include <stdio.h>
void test()
{
	//static修饰局部变量
	static int i = 0;
	i++;
	printf("%d ", i);
}

int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		test();
	}
	return 0;
}

Compare the effects of code 1 and code 2 to understand the meaning of static modified local variables:

Conclusion:  Static modification of local variables changes the life cycle of the variable, allowing static local variables to still exist outside the scope. The life cycle does not end until the end of the program.

【13.2.2】Modify global variables

#include <stdio.h>

//代码1
//add.c
int g_val = 2018;
//test.c
int main()
{
	printf("%d\n", g_val);
	return 0;
}
//代码2
//add.c
static int g_val = 2018;
//test.c
int main()
{
	printf("%d\n", g_val);
	return 0;
}

Code 1 is normal, but code 2 will cause a connectivity error when compiling.

Conclusion:  A global variable is modified by static, so that the global variable can only be used in this source file and cannot be used in other source files.

【13.2.3】Modification function

//代码1
//add.c
int Add(int x, int y)
{
	return x + y;
}
//test.c
int main()
{
	printf("%d\n", Add(2, 3));
	return 0;
}

//代码2
//add.c
static int Add(int x, int y)
{
	return x + y;
}
//test.c
int main()
{
	printf("%d\n", Add(2, 3));
	return 0;
}

Code 1 is normal, but code 2 will cause a connectivity error during compilation.

Conclusion:  A function is statically modified, so that this function can only be used in this source file and cannot be used in other source files.

【14】 Define constants and macros #define

#include <stdio.h>

//define定义标识符常量
#define MAX 1000
//define定义宏
#define ADD(x, y) ((x)+(y))

int main()
{
	int sum = ADD(2, 3);
	printf("sum = %d\n", sum);
	sum = 10 * ADD(2, 3);
	printf("sum = %d\n", sum);
	return 0;
}

【15】Pointer

【15.1】Memory

        Memory is a particularly important memory on a computer. Programs in the computer are all run in the memory. Therefore, in order to use the memory effectively, the memory is divided into small memory units. The size of each memory unit is 1 Bytes . In order to effectively access each unit of memory, the memory unit is numbered, and these numbers are called the address of the memory unit .

Variables are created in memory (space is allocated in memory), and each memory unit has an address, so variables also have addresses.

Get the variable address as follows:

【Sample code】

#include <stdio.h>

int main()
{
	int num = 10;
	&num;//取出num的地址
	//注:这里num的4个字节,每个字节都有地址,取出的是第一个字节的地址(较小的地址)
	printf("%p\n", &num);//打印地址,%p是以地址的形式打印
	return 0;
}

How to store the address requires defining a pointer variable.

int num = 10;
int *p;//p为一个整形指针变量
p = &num;

【Sample code】

#include <stdio.h>
int main()
{
	int num = 10;
	int *p = &num;
	*p = 20;
	return 0;
}

Taking integer pointers as an example, it can be extended to other types, such as:

#include <stdio.h>

int main()
{
	char ch = 'w';
	char* pc = &ch;
	*pc = 'q';
	printf("%c\n", ch);
	return 0;
}

【15.2】The size of pointer variables

#include <stdio.h>
//指针变量的大小取决于地址的大小
//32位平台下地址是32个bit位(即4个字节)
//64位平台下地址是64个bit位(即8个字节)

int main()
{
	printf("%d\n", sizeof(char *));
	printf("%d\n", sizeof(short *));
	printf("%d\n", sizeof(int *));
	printf("%d\n", sizeof(double *));
	return 0;
}

Conclusion: The pointer size is 4 bytes on 32-bit platforms and 8 bytes on 64-bit platforms.

【16】Structure

Structure is a particularly important knowledge point in C language. Structure enables C language to describe complex types.

For example, when describing a student, the student contains: name + age + gender + student number. This can only be described using a structure.

【Example code】

struct Stu
{
	char name[20];//名字
	int age; //年龄
	char sex[5]; //性别
	char id[15]; //学号
};

// 结构体的初始化:
//打印结构体信息
struct Stu s = {"张三", 20, "男", "20180101"};

//.为结构成员访问操作符
printf("name = %s age = %d sex = %s id = %s\n", s.name, s.age, s.sex, s.id);

//->操作符
struct Stu *ps = &s;
printf("name = %s age = %d sex = %s id = %s\n", ps->name, ps->age, ps->sex, ps->id);

おすすめ

転載: blog.csdn.net/lx473774000/article/details/131503633