01. First knowledge of C language
For the learning notes of bit C language, please go to bit homepage: https://m.cctalk.com/inst/s9yewhfr , or B station search bit pengge, a very good teacher in C language! This note is mainly from brother Peng's handouts and pictures!!, If you think it's good, go to pengge's station B video for praise, coin, collection and forwarding! This note is mainly for personal study and review. It cannot be used for commercial purposes. If there is infringement, please tell me to delete it!
I also re learn the C language. I learned it before I was an undergraduate. I don't know if I blame the teacher or myself. I learned it the same as Mitian! Now the understanding is not very clear. If there are mistakes, please comment and correct! Thank you very much! Write on CSDN also hope to meet predecessors, a lot of guidance!
Bit home page
Station B: bitpengge
C language Chinese network
0. What is C language?
C language is a process oriented computer programming language, which is different from object-oriented programming languages such as C + +, Java and so on.
Its compilers mainly include Clang, GCC, WIN-TC, SUBLIME, MSVC, Turbo C, etc.
1. The first C language program
If the error is scanf:this function may be unsafe. Please add a sentence: (what is the specific reason? Brother Peng said it at that time, but didn't remember it!)
#define _CRT_SECURE_NO_WARNINGS
//#define _CRT_SECURE_NO_WARNINGS #Include < stdio. H > / / header file int main() { printf("hello bit\n"); printf("he he\n"); return 0; } //Explanation: //The main function is the entry to the program //There is only one main function in a project
2. Data type
char / / character data type
Short / / short integer
int / / shaping
Long / / long integer
long long / / longer shaping
float / / single precision floating point number
Double / / double precision floating point number
//Does c language have string type? The answer is No. There is no string type in c language. String is constructed by char array.
Byte size occupied by each data type:
#include <stdio.h> int main() { //The following are the results displayed in vs2017 of win10 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; }
There are so many types, in fact, in order to more enrich the expression of various values in life.
Use of type:
char ch = 'w'; //character int weight = 120; //integer float salary = 20000.0f; //Single precision floating point
3. Variables and constants
Some values in life are constant (such as pi, gender, ID number, blood type, etc.).
Some values are variable (e.g. age, weight, salary).
Constant values are represented by the concept of constants in C language, and variable values are represented in C language.
3.1 method of defining variables
Syntax: variable type variable name = initial value;
int age = 150; float weight = 45.5f; char ch = 'w';
3.2 classification of variables
1) Local variable
2) Global variable
#include <stdio.h> int global = 2019;//global variable int main() { int local = 2018;//local variable //Is there a problem with the global defined below? no problem int global = 2020;//Local variables. When local variables and global variables have the same name, local variables are preferred. This person feels related to the search path! printf("global = %d\n", global); return 0; }
3.3 use of variables
#include <stdio.h> int main() { int num1 = 0; int num2 = 0; int sum = 0; printf("Enter two operands:>"); scanf("%d %d", &num1, &num2); //int -- %d float -- %f double -- %lf char -- %c sum = num1 + num2; printf("sum = %d\n", sum); return 0; }
Here are the input and output statements
scanf(): input
printf(): output
int – %d float – %f double – %lf char – %c
//scanf() definition: when I understand it later, I'll come back and explain. Rookies cry! _Check_return_ _CRT_INSECURE_DEPRECATE(scanf_s) _CRT_STDIO_INLINE int __CRTDECL scanf( _In_z_ _Scanf_format_string_ char const* const _Format, ...) //printf() definition: _Check_return_opt_ _CRT_STDIO_INLINE int __CRTDECL printf( _In_z_ _Printf_format_string_ char const* const _Format, ...)
3.4 scope and life cycle of variables
1) Scope: scope is a programming concept. Generally speaking, the names used in a piece of program code are not always valid / available
of The scope of the code that limits the availability of the name is the scope of the name.
(1) The scope of a local variable is the local scope of the variable. For example: {int a = 10;}, {} is the scope of local variable a.
(2) The scope of the global variable is the whole project. For example: int b =100;int main(){};, Variables outside the main () function {} that are not in other ranges.
2) Life cycle: the life cycle of a variable refers to the period between the creation of a variable and its destruction
(1) The life cycle of a local variable is the beginning of the scope life cycle and the end of the scope life cycle. For example, the formal parameters of a function.
(2) The life cycle of a global variable is the life cycle of the entire program. The global variable life cycle ends when the program ends.
3.5 constants
The definition forms of constants and variables in C language are different.
Constants in C language are divided into the following types:
1) Literal constant
2) const modified constant variable syntax: cont variable type
3) #define defined identifier constant syntax: #define constant identifier constant value
4) Enumeration constant syntax: enum enumeration constant name {constant 1, constant 2,...}// Remember to add a semicolon here! There is no constant type in front of a constant
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> //give an example enum Sex { MALE, //Ale = 2, / / you can specify the default value, and the subsequent value is incremented by + 1 on the basis of 2 FEMALE, SECRET }; //Add a semicolon here; //Mal, female and secret in parentheses are enumeration constants int main() { //Literal constant presentation 3.14;//Literal constant 1000;//Literal constant //const modified constant const float pai = 3.14f; //pai here is a constant variable modified by const //pai = 5.14;// It cannot be modified directly! vs2017 will prompt that the expression must be a modifiable lvalue //#Demonstration of identifier constants for define #define MAX 100 / / there is no semicolon "; “ printf("max = %d\n", MAX); // 100 //Enumeration constant demo printf("%d\n", MALE); // 0 printf("%d\n", FEMALE); // 1 printf("%d\n", SECRET); // 2 //Note: enumeration constants start from 0 by default and increase by 1 in turn return 0; }
Note (constant variable):
The PAI in the above example is called const modified constant variable. Const modified constant variable in C language only limits the variable pai at the grammatical level and cannot be changed directly, but Pai is essentially a variable, so it is called constant variable.
4. String + escape character + comment
4.1 string
"hello bit.\n"
This string of characters enclosed by double quotes is called String Literal, or string for short.
Note: the end flag of the string is an escape character of \ 0. When calculating the string length, \ 0 is the end flag and is not counted as the string content.
#include <stdio.h> //What is the print result of the following code? Why? (highlight the importance of '\ 0') int main() { char arr1[] = "bit"; char arr2[] = { 'b', 'i', 't' }; char arr3[] = { 'b', 'i', 't', '\0' }; printf("%s\n", arr1); //bit contains' \ 0 'by default printf("%d\n", sizeof(arr1)/sizeof(char)); //4, but it is included when calculating the length!!! printf("%s\n", arr2); //B it random value //printf("%d\n", sizeof(arr2) / sizeof(char)); printf("%s\n", arr3); //bit display write out '\ 0' printf("%d\n", sizeof(arr3) / sizeof(char)); // 4 return 0; }
4.2 escape characters
Join us to print a directory on the screen: c:\code\test.c
How do we write code?
#include <stdio.h> int main() { printf("c:\code\test.c\n"); return 0; }
In fact, the result of the program is as follows:
Here we have to mention the escape character. As the name suggests, the escape character is to change its meaning.
Let's look at some escape characters.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { //Question 1: how to print a single quotation mark 'on the screen? //Question 2: print a string on the screen. The content of the string is a double quotation mark ". What should I do? printf("%c\n", '\''); //Note: the corresponding% c enclosed in single quotation marks' 'and the corresponding% s enclosed in double quotation marks printf("%s\n", "\'"); printf("%s\n", "\""); printf("%c\n", '\"'); return 0; }
//What does the program output? #include <stdio.h> int main() { //strlen() finds the length of the string printf("%d\n", strlen("abcdef")); // 6 // \62 is parsed into an escape character printf("%d\n", strlen("c:\test\628\test.c")); //14 = 11 + 3 escape characters printf("%c\n", '\62'); //2 ??? return 0; }
5. Notes
1) Unnecessary code in the code can be deleted directly or commented out
2) Some codes in the code are difficult to understand. You can add notes
//Comment line
/*Comment code block*/
#include <stdio.h> int Add(int x, int y) { return x + y; } /*C Language style notes int Sub(int x, int y) { return x-y; } */ int main() { //C + + annotation style //int a = 10; //Call the Add function to complete the addition printf("%d\n", Add(1, 2)); return 0; }
6. Select a statement
If you study hard, you can get a good offer and reach the peak of your life.
If you don't study, graduation is unemployment. Go home and sell sweet potatoes.
This is the choice!
#include <stdio.h> int main() { int coding = 0; printf("Will you type the code? (option 1) or 0):>"); scanf("%d", &coding); if(coding == 1) { prinf("Hold on, you'll have a good time offer\n"); } else { printf("Give up and go home to sell sweet potatoes\n"); } return 0; }
7. Circular statement
Some things must be done all the time, such as my lectures day after day, such as everyone's study day after day.
For example:
The loop structure of C language includes:
1) while statement - explanation
While (end condition) / / if the end condition is met, the loop body will jump out
{
Circulatory body;
}
2) for statement (later explanation)
3) do... while
If you want to be a Daniel! To type 20000 lines of valid code, go to the data structure after this!!! awesome
//An instance of a while loop #include <stdio.h> int main() { printf("Add bit\n"); int line = 0; while (line <= 20000) { line++; printf("I'll keep trying to type the code\n"); } if (line > 20000) printf("good offer\n"); return 0; }
8. Function
#include <stdio.h> int main() { int num1 = 0; int num2 = 0; int sum = 0; printf("Enter two operands:>"); scanf("%d %d", &num1, &num2); sum = num1 + num2; printf("sum = %d\n", sum); return 0; }
The above code is written as a function as follows:
Function is characterized by code simplification and code reuse.
Function syntax:
Function return value type function name (function parameter)
{
Function body
}
#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("Enter two operands:>"); scanf("%d %d", &num1, &num2); sum = Add(num1, num2); printf("sum = %d\n", sum); return 0; }
9. Array
How to store 1-10 numbers?
C language gives the definition of array: a set of elements of the same type
9.1 array definition
Syntax: array element type array name [array length] = {element 1, element 2,...};
int arr[10] = {1,2,3,4,5,6,7,8,9,10};//Define an integer array with up to 10 elements
9.2 subscript of array
C language stipulates that each element of the array has a subscript, which starts from 0.
Arrays can be accessed by subscripts. For example:
int arr[10] = {0}; //If the array has 10 elements, the subscript range is 0-9
9.3 use of arrays
Using loop for to traverse array
#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; }
10. Operator
Brief introduction
1) Arithmetic operator
+ - * / % //Addition, subtraction, multiplication and division
2) Shift operator
>> << //Move operation symbol right move operation symbol left
3) Bit operator
& ^ | //Bitwise and bitwise reverse bitwise OR
4) Assignment operator
= += -= *= /= &= ^= |= >>= <<=
5) Monocular operator
! // Logical reverse operation - // negative + // positive & // Get address sizeof // The type length of the operand in bytes ~ // Bitwise negation of a number -- // Front and rear-- ++ // Front and rear++ * // Indirect access operator (dereference operator) (type) cast
6) Relational operator
> >= < <= != // Used to test "inequality" == // Used to test equality
7) Logical operator
&& // Logic and || // Logical or
8) Conditional operator
exp1 ? exp2 : exp3 //If the ternary operator exp1 is true, take exp2, otherwise take exp3
9) Comma operator
exp1, exp2, exp3, ....
10) Subscript references, function calls, and structure members
[] () . -> //->Pointer to structure
11. Common keywords
These keywords cannot be used when defining variable names.
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
Note: for keywords, first introduce the following, and then explain them later.
11.1 keyword typedef
typedef, as the name suggests, is a type definition, which should be understood here as type renaming. For example:
//Rename unsigned int to uint_32, so uint_32 is also a type name typedef unsigned int uint_32; int main() { //Look at num1 and num2. These two variables are of the same type unsigned int num1 = 0; uint_32 num2 = 0; return 0; }
11.2 keyword static
In C language:
static is used to modify variables and functions
- Decorated local variables - called static local variables
- Modify global variables - called static global variables
- Decorating functions - called static functions
11.2.1 modifying local variables
Compare the effects of code 1 and code 2 to understand the meaning of static modifying local variables.
//Code 1 #include <stdio.h> void test() { int i = 0; i++; printf("%d ", i); //Each time the function ends, the i value is released } int main() { int i = 0; for(i=0; i<10; i++) { test(); //Print 1 every time } return 0; }
//Code 2 #include <stdio.h> void test() { //static modifies a local variable static int i = 0; //After test() is executed, the i value is retained i++; printf("%d ", i); } int main() { int i = 0; for(i=0; i<10; i++) { test(); //1 to 10 prints at a time } return 0; }
Conclusion: static modification of local variables changes the life cycle of variables, so that static local variables still exist out of the scope. The life cycle will not end until the end of the program.
11.2.2 modify global variables
Code 1 is normal, and code 2 will have connectivity errors during compilation.
//Code 1 //add.c int g_val = 2018; //test.c int main() { printf("%d\n", g_val); return 0; } //Code 2 //Add. C static global variable static int g_val = 2018; //test.c int main() { printf("%d\n", g_val); return 0; }
Conclusion: a global variable is modified by static, so that this global variable can only be used in this source file, not in other source files.
11.2.3 modification function
Code 1 is normal, and code 2 will have connectivity errors during compilation, just like modifying global variables.
//Code 1 //add.c int Add(int x, int y) { return x+y; } //test.c int main() { printf("%d\n", Add(2, 3)); return 0; } //Code 2 //Add. C static modifier function static int Add(int x, int y) { return c+y; } //test.c int main() { printf("%d\n", Add(2, 3)); return 0; }
Conclusion: a function is modified by static, so that this function can only be used in this source file, not in other source files.
(the remaining keywords will be explained in subsequent courses.)
12. #define define constants and macros
Note that #define is not followed by a semicolon;
#define constant name constant value
#define macro name macro expression
//define defines an identifier constant #define MAX 1000 //define macro #Define add (x,y) ((x) + (y)) / / note that X and y should be enclosed in parentheses #include <stdio.h> int main() { int sum = ADD(2, 3); printf("sum = %d\n", sum); sum = 10 * ADD(2, 3); printf("sum = %d\n", sum); return 0; }
13. Pointer
13.1 memory
Memory is a particularly important memory on the computer. The operation of programs in the computer is carried out in memory.
Therefore, in order to use memory effectively, the memory is divided into small memory units, and the size of each memory unit is 1 byte.
In order to effectively access each unit of memory, the memory unit is numbered. These numbers are called the address of the memory unit.
Variables are created in memory (space is allocated in memory). Each memory unit has an address, so variables also have an address. Take out the variable address as follows:
#include <stdio.h> int main() { int num = 10; #//Fetch the address of num //Note: there are 4 bytes of num, each byte has an address, and the address of the first byte (smaller address) is taken out printf("%p\n", &num);//Print address,% p is printed as an address return 0; }
How to store the address needs to define the pointer variable.
int num = 10; int *p; //p is an integer pointer variable p = #
Use examples of pointers:
#include <stdio.h> int main() { int num = 10; printf("%d\n", num); // 10 int *p = # *p = 20; printf("%d\n", *p); // 20 printf("%d\n", num); // 20 return 0; }
Taking the integer pointer as an example, it can be extended to other types, such as:
#include <stdio.h> int main() { char ch = 'w'; char* pc = &ch; // Initialize the pointer variable pc with the address of CH, that is, the pc stores the address of the variable ch *pc = 'q'; //The value on the (ch) address pointed to by pc is changed to 'q' printf("%c\n", ch); // q return 0; }
13.2 pointer variable size
#include <stdio.h> //The size of the pointer variable depends on the size of the address, that is, no matter what type of pointer depends on the size of the address //The address under 32-bit platform is 32 bits (i.e. 4 bytes) //The address under 64 bit platform is 64 bit (i.e. 8 bytes) 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 platform and 8 bytes on 64 bit platform.
14. Structure
Structure is a particularly important knowledge point in C language. Structure makes C language capable of describing complex types.
For example, describe the student. The student includes: Name + age + gender + student number.
Only structures can be used here. For example:
Syntax: struct structure type name
{
Member variable type 1 member variable 1;
Member variable type 2;
}
Personally, it feels like a class, but it only contains the properties of the class without methods.
struct Stu { char name[20];//name int age; //Age char sex[5]; //Gender char id[15]; //Student number };
Initialization of structure and point operator. - >:
//Print structure information struct Stu s = {"Zhang San", 20, "male", "20180101"}; //. access operators for structure members are used to access members for structure variables printf("name = %s age = %d sex = %s id = %s\n", s.name, s.age, s.sex, s.id); //->Operators are used to access member variables from structure pointer variables struct Stu *ps = &s; printf("name = %s age = %d sex = %s id = %s\n", ps->name, ps->age, ps->sex, ps- >id);
(the content of the consortium union is missing!)
This is the end of the initial C language!