C language and c Language
Language is just a tool. Any language is the same, and one language is the best. The key is to understand the thoughts behind the language, understand its thoughts, and use any language. There is no difference between good and bad languages. Since any language exists, it naturally has its own value.
In the era of OOP everywhere, why can process-oriented C language still be so active? This is mainly because of the language features of C. The C language is small and flexible, and there is also a pointer directly dealing with hardware, so it is the only advanced language for embedded development; it is precisely because of its small and flexible, we can use it to develop a series of gadgets. Unix/Linux is an operating system composed of these gadgets. At the same time, we can use C to develop high-performance applications.
1. data type. C is a process-oriented language, but it can still achieve the work that most object-oriented can do. For example, three main features of object-oriented: encapsulation, inheritance, and polymorphism.
Encapsulation:In C, there is a complex data structure called struct. Struct is the struct in C.
If we want to encapsulate the person, the person may include the name, gender, age, height, weight, and other information. We can encapsulate it as follows:
Struct Person {char name [20]; // name char gender; // gender int age; // age int height; // height int weight; // weight };
When we want to create an object like OOP, we can:
struct Person p;
We can assign values to p directly:
p.name = "whc";p.gender = 'b'; //'b' = boy; 'g' = girlp.age = 25; p.height = 175;p.weight = 65;
Inheritance:We also use struct to create a student structure and inherit the structure Person, as shown below:
Struct Student {struct Person p; char number [20]; // Student ID int score; // score };
Create an object for Student and assign a value to it:
struct Student s;s.p.name = "whc";s.p.gender = 'b';s.p.age = 25;s.p.height = 175;s.p.weight = 65;s.number = "20150618";s.score = 90;
Polymorphism:The implementation of polymorphism in C can be implemented by using function pointers. For the sake of simplicity, we assume that there is only one function pointer in the structure "Person.
struct Person{ void (*print)(void *p);};struct Student{ struct Person p;};
The print functions of the two structs "Person" and "Student" are implemented as follows:
void printPerson(void *person){ if(NULL == person) return ; struct Person *p = (struct Person *)person; printf("run in the person!!\n");}void printStudent(void *person){ if(NULL == person) return ; struct Person *p = (struct Person *)person; printf("run in the student!!\n");}
Let's write a function to call them:
Void print (void * person) {if (NULL = person) return; struct Person * p = (struct Person *) person; p-> print (person );} int main () {struct Person person; struct Student student; person. print = printPerson; student. p. print = printStudent; print (& person); // print (& student), an object whose real parameter is Person; // return 0 ;}
Their output is:
In fact, this is not hard to understand. Whether it is Person or Student, they only have one variable in the memory, that is, the function pointer, and void * indicates any type of pointer, when we forcibly convert it to the struct Person * type, p-> print points to the print address of the input real parameter.
2. pointer and Memory Management
Which of the following is a C Project? Basically, we will get the same answer, that is, pointer and memory overflow. The pointer is actually an address. It can be a variable address or a function address. Whatever it is, it is an address in the memory.
For example, if there is variable a, we define a pointer to save the address of variable:
int a = 0;int *p = &a;
What if it is a function? We define a function and use a function pointer to save the function address:
int min(int a,int b){ return a<b?a:b; }int (*f)(int,int);f = min;
Maybe we sometimes think, can we only define a variable or function first, and then give its address to the pointer? Can't I directly use a pointer or directly assign a constant to the pointer? First, we do not know which addresses are available in the memory and which are unavailable. Whenever we define a pointer, this pointer points to an undefined memory, this is the legendary Wild pointer. If we assign a value to the memory pointed to by this pointer, it may overwrite some important data. Therefore, whenever we define a pointer, we 'd better assign it an initial address or NULL; if we assign a constant to a pointer, the same principle is true.
The pointer type must be the same as the variable type (if we didn't intentionally ask them to be different). The so-called type is only the constant expression of the variable, but it is actually in the memory, they are only binary 0101. When we use the original 32bits code, it is unsigned; when we use the 32bits complement code, it is signed; when we use the floating point, it is float; struct is used for more complex User-Defined representation, which can be well understood by union.
Now let's talk about the memory. Here we only discuss the user memory area:
It is generally divided into five areas:
(1) code area: the place where Code commands are stored
(2) Global (static) Variable Area: including initialized and uninitialized global and static variables
(3) character constant area: stores some string constants. in C language, this can easily be mixed with the character array defined in the stack. When we define it as follows:
Int main () {char * str0 = "Hello World! "; // Char str1 [] =" Hello World! "; // Stack return 0 ;}
Str0 points to a string in the character constant area, but str0 itself has this pointer variable in the stack area, which stores "Hello World!" In the character constant area! .
Str1 is a character array, so the strings stored in str1 are in the stack area. What we use here is only a form of character array initialization. In fact, it can be written as follows:
char str1[] = {'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};
(4) stack zone: local variables, form parameters, and function return addresses are managed by the system and grow from high addresses to low addresses in the memory, therefore, the stack space is limited. When a large array is defined in the stack or a deep recursive call is used, Stack Overflow may occur.
(5) Heap: the space allocated by the malloc, calloc, and realloc functions is managed by ourselves. after each use, the memory must be released with free. Otherwise, memory leakage occurs. After the memory is released, although the memory is no longer occupied, the corresponding pointer still points to this area. This pointer is a wild pointer, so after the memory is released, we recommend that you assign NULL to the pointer. As follows:
Int main () {int * p = (int *) malloc (100 * sizeof (int);/* execution statement */free (p ); // at this time, p still points to the memory and becomes the wild pointer p = NULL; // NULL return 0 for p ;}
3. C language I/O Input and Output
C language itself does not have the input and output features, so all its I/O operations are implemented through system calls. Fortunately, the C standard library has encapsulated a series of I/O operation functions for us.
Putchar (): Output A character constant in the variable to the display screen;
Getchar (); input a character constant from the keyboard. This constant is the value of this function;
Printf (); format and control all types of data on the keyboard to output to the display screen;
Scanf (); input various types of data from the keyboard and store the data in program variables;
Puts (): outputs a String constant in the array variable to the display screen.
Gets (): enter a String constant on the keyboard and put it in the array of the program.
Some operations on files, because everything can be viewed as a file, the standard input and output can also be operated as a file. file descriptor: standard input (0), standard output (1), standard error (2)
Fpus (); output to file
Fgets (); input from the file
Fscanf (); format file input
Fprintf (); format file output
The other two very important functions, of course, are similar to their derived functions.
Sscanf (); extracts various types of data from a string.
Sprintf (); writes formatted data to a string
I will not explain each function here, mainlyFormatting FunctionsAnalysis:
(1) When we wantConverts a string to an integer.OrConverts an integer to a string.We generally think of atoi () or itoa () (non-standard function), but we can implement it through the stream:
Int main () {int num = 10; char str [10] = {0}; sprintf (str, "% d", num ); // convert int to char [] num = 0; sscanf (str, "% d", & num); // convert string to int printf ("num: % d str: % s \ n ", num, str); return 0 ;}
The output result is as follows:
Conversion between String Conversion and other types: float, hexadecimal, and unsigned can all be implemented using a stream.
(2) In the Formatting FunctionRegular Expression
All formatting functions can customize their own scan set % [abc], % [a-z], % [^ abc], % [^ a-z], the character in [] is a matched character, and ^ indicates the inverse set.
When we want to input a string that may contain spaces from the standard input, scanf ("% s", str) is used directly; return when space is read, in this case, you can use a regular expression:
Char str [100] = {0}; scanf ("% [^ \ n]", str); // write only when you press ENTER
Only lowercase letters a-z can be read from the standard input, and other characters are returned:
char str[100] = {0};scanf("%[a-z]",str);
The usage of other formatting functions is the same.
4. Summary
I learned the C language from my freshman year in year 45. I personally think that the greatest success of C is its pointer, but it is also the most error-prone. To understand C, you must master the pointer. Although language is just a tool, it is the basis. Maybe, you can say that it is now the world of JAVA, full street is recruiting JAVA engineers; or you can say that C is too low-level, and now it is the era of OOP, who else will use process-oriented ...... do not forget what the operating system uses? The concurrency of nginx implemented by C and C is dozens of times that of apache implemented by C ++. No matter what programming language you use, you can learn it carefully. Do not abandon what you learned yesterday because it is popular today.
All rights reserved. You are welcome to repost this article.