C language

Computer programming language
open 2 entries with the same name
Collection
zero Useful+1
zero
C is an earlier language Programming language , was born in Bell Laboratories in 1972. In 1972, Dennis Ritchie designed C language, which inherited many ideas of B language and added the concept of data type and other features. Although the C language was developed with the UNIX operating system, it does not only support UNIX. [11] C is a general (widely available) programming language.
Programming language and compiler are integrated. C compiler includes the famous GCC (GNU Compiler Collection), etc. [12]
Widely used in Underlying development C language can compile and process low-level in a simple way storage C language only produces a small amount machine language And efficient programming language that can run without any support of running environment. Although C language provides many low-level processing functions, it still keeps Cross platform C language program written in a standard specification can include Embedded processor as well as Supercomputer And many other operating platforms Computer platform Compile on. [1]
The latest C language standard is C23 [14]
Software name
C language
Online time
1972
Software language
english
Main compiler
Visual C++ Clang GCC Turbo C etc.
Influence language
C++ C# D language Java JavaScript Object PHP Python Objective-C Swift etc.
Whether case sensitive
yes

brief introduction

Announce
edit
C language is a Process oriented Of Computer programming language , and C++, C # Java And other object-oriented programming languages. C language design goal It provides a simple way to compile and process low-level storage . Only a small amount of Machine code And programming languages that can run without any support from the running environment. C language describes the problem ratio assembly language Fast, small workload, good readability, easy debugging, modification and transplantation, and code quality assembly language Equivalent. C language is generally only better than assembly language code generation Of Target program The efficiency is 10% - 20% lower. Therefore, C language can write system software. [2]
At present, C language is widely used in the field of programming high-level language Compared with other programming languages, it has more advantages than assembly language. computer system design And application programming are two major areas of C language application. At the same time, C language is widely used in many computers operating system Both can be applied to, and the efficiency is remarkable. [3]
C language has a complete Theoretical system , plays an important role in programming languages. [4]

Development history

Announce
edit
C language was born in the United States Bell Laboratories , by Dennis Ritchie (Dennis MacAlistair Ritchie) Kenneth Lan Thompson (Kenneth Lane Thompson) Language B It was developed on the basis of. After the completion of its main body design, Thompson and Ritchie completely rewritten UNIX with it, and with the development of UNIX, c language has also been constantly improved. In order to facilitate the comprehensive promotion of C language, many experts, scholars and hardware manufacturers jointly formed the C language standards committee, and in 1989, the first complete C standard was born, which is called“ C89 ”, that is“ ANSI C ”As of 2020, the latest C language standard is "C18" issued in June 2018. [5]
C language is named C because it originated from the invention of Ken Thompson Language B , and Language B From BCPL Language.
In 1967, University of Cambridge Martin Richards of BCPL (Basic Combined Programming Language).
In the 1960s, the United States AT&T company Bell Laboratories (AT&T Bell Laboratories) Ken Thompson (Kenneth Lane Thompson) He has nothing to do, and his hands are itchy. He wants to play a simulation made up by himself solar system Space Travel, a video game for sailing. He found a free table behind his boss's back Small computer —— PDP-7 But this computer doesn't operating system , and the game must use some functions of the operating system, so he set about developing the operating system for PDP-7. Later, this operating system was named - UNICS (Unified Information and Computing Service).
In 1969, Bell Lab Ken Thompson, based on the BCPL language, designed a very simple Language B (Take the first letter of BCPL), and write the first version in B language UNIX Operating system (called UNICS).
In 1971, Dennis Ritchie, who also loved Space Travel, joined Thompson's development project in order to play games earlier, Cooperative development UNIX。 His main job is to transform the B language to make it more mature. [6]
In 1972, Dennis Ritchie of Bell Laboratories in the United States finally designed a new language based on the B language. He took the second letter of BCPL as the name of this language, which is the C language.
At the beginning of 1973, the main body of C language was completed. Thompson and Rich can't wait to start rewriting it completely UNIX At this time, the fun of programming has made them forget the "Space Travel" completely and devote themselves to the development of UNIX and C languages. With the development of UNIX, C language itself is constantly improving. Until 2020, various versions of UNIX kernel and peripheral tools will still use the C language as the main development language, and many of them will inherit from Thompson and Ritchie code [6]
In development, they also consider UNIX Migrate to other types of computer Used on. The powerful portability of C language is shown here. machine language and assembly language Are not transplantable x86 The developed program cannot be used in Alpha SPARC and ARM Wait for the machine to run. C program can be used in any architecture processor As long as the processor of that architecture has the corresponding C language compiler And libraries, and then C source code Compile and link to target Binary file Then you can run on the processor of which architecture. [6]
In 1977, Dennis Ritchie published the C language compiler text Portable C Language Compiler which does not depend on specific machine systems.
C language continued to develop. In 1982, many people of insight and American National Standards Institute ANSI )In order to make C language develop healthily, it was decided to set up C standards committee and establish C language standards. The committee consists of hardware manufacturers compiler And others software tool Manufacturer Software designer , consultants, academics, C language authors and application program Member composition. In 1989, ANSI released the first complete C language standard - ANSI X3.159-1989, which is called "C89" for short, but people are also used to calling it "ANSI C". C89 was International Organization for Standardization (International Standard Organization, ISO )It is adopted word for word. The official name given by ISO is ISO/IEC 9899, so ISO/IEC 9899:1990 is also commonly referred to as "C90". In 1999, after making some necessary amendments and improvements, ISO issued a new C language standard, named ISO/IEC 9899:1999, which is short for“ C99 ”。 [6] On December 8, 2011, ISO officially released a new standard called ISO/IEC9899:2011, which is called“ C11 ”。
In June 2018, ISO released ISO/IEC9899:2018, referred to as "C18" (or "C17") [10] C18 standard does not introduce new language features, and only supplements and amends C11.
On September 3, 2022, ISO released the new final version of the C language standard, called ISO/IEC 9899:2013, or "C23" for short, on the website of Open Standards. [13-14]

Language characteristics

Announce
edit

main features

C language is a kind of Structured Language It has a clear level, and can write programs in the form of modules, which is very conducive to program debugging, and the processing and presentation capabilities of c language are very strong, relying on a very comprehensive operator And diverse data type , can easily complete various data structure The pointer type can be used for memory Direct addressing And hardware Direct operation Therefore, it can be used to develop both system programs and application software. Through the research and analysis of C language, its main characteristics are summarized as follows:
(1) Concise language
C language includes various Control statement There are only 9 types, and only 32 keywords. The programming requirements are not strict and Lowercase letters Mainly, many unnecessary parts have been simplified. In fact, statement composition is less related to hardware, and C language itself does not provide hardware related input/output file management And other functions. If such functions are required, coordination is required Compiling system Supported Class library C language has a very concise compilation system. [5]
(2) With structured control statements
C language is a kind of Structured The provided control statements have structural features, such as for statements, if... else statements, and switch Statement, etc. Can be used to implement the logical control , convenient Process oriented Program design of. [5]
(3) Rich data types
C language contains a wide range of data types, including not only traditional character type integer float , array type and other data types, as well as data types that other programming languages do not have. Among them, pointer type data is the most flexible and can be used to calculate various data structures through programming. [5]
(4) Rich operators
C language contains 34 operator , which treats assignment, parentheses, etc. as operators, so that the expression Types and operator types are very rich. [5]
(5) Rightness Physical address Direct operation
C language allows hardware Memory address Direct reading and writing can realize the main functions of assembly language and can be operated directly Hardware C language not only has high-level language It has good characteristics and contains the advantages of many low-level languages, so it is widely used in the field of system software programming. [5]
(6) The code has good Portability
C language is a process oriented programming language. Users only need to pay attention to the problem being solved, and do not need to spend too much effort to understand the relevant hardware hardware environment When using C language to realize the same function, the code is basically the same, and the migration can be completed without or only with a few changes, which means that C programs written by one computer can be easily run on another computer, thus greatly reducing the work intensity of program migration. [5]
(7) High quality Object code Efficient procedures
Compared with other high-level languages, C language can generate high-quality and high efficiency Object code, so it is usually applied to those with high requirements for code quality and execution efficiency Embedded system Programming. [5]

Special features

C language is Universality The strongest computer program Editing language , it can not only play the function of high-level programming language, but also has the advantages of assembly language, so compared with other programming languages, it has its own unique characteristics. It is embodied in the following three aspects:
First, Universality The size of the operation range of C language directly determines its advantages and disadvantages. C language contains 34 kinds of operators, so the operation range is beyond many other languages. In addition, the expression form of the operation result is also very rich. In addition, C language includes character type, pointer type, etc data structure Therefore, it can also cope with the larger data structure operations. [3]
Second, Simplicity 9 types of control statements and 32 keywords are the basic features of C language, making it widely used in computer application programming Applicability , not only can it be applied Programmer To improve its work efficiency At the same time, it can also support advanced programming, avoiding the tedious language switching. [3]
Third, the structure is perfect. C language is a structured language, which can realize modularized application programs in the form of modular units, and has Significant advantages At the same time, this feature also enables it to adapt to a variety of different programming requirements, and the execution efficiency is high. [3]

shortcoming

1. The main disadvantage of C language is the weak encapsulation of data, which makes C have a big defect in data security, which is also a big difference between C and C++.
2. The syntax of C language is not too strict, and the constraint on variable type is not strict, which affects the security of the program subscript out of bounds No inspection, etc. From the perspective of application, C language is better than other languages high-level language It is difficult to master. That is to say, people who use C language are required to be more proficient in programming. [7]

Language composition

Announce
edit

Basic composition

data type
The data types of C include: integer short int long , long long), character type( char ), real or float Single precision float and Double precision double)、 Enumeration type enum ), array type Structure type struct )、 Commonality Type( union ), pointer type, and Null type void )。
The value of a constant cannot be changed. Symbolic constant names are usually capitalized.
The variable is based on a identifier Is a name, and its value can be changed. identifier Yes letter or Underline The first string is a sequence of letters, numbers or underscores. Please note that the first character must be a letter or underscore, otherwise it is an illegal variable name. Variables are assigned corresponding Storage unit
array
If a variable name is followed by a numeric Brackets , this declaration is an array declaration. character string It is also an array. They use ASCII NULL as the end of the array. It should be noted that the index value in the brackets starts from 0.
Pointer
If a Variable declaration The * sign is used in front of the, indicating that this is a pointer variable. In other words, this variable stores an address, and * (here specifically refers to unary operator *, the same below. Otherwise in C language binary operator *) is to retrieve the content Operator , meaning to take this Memory address Content stored in. Pointer is the difference between C language and other contemporaries high-level language One of the main characteristics of.
Pointer can be not only the address of a variable, but also an array Array element , the address of the function. By pointer as Formal parameter You can get more than one return value during the function call, which is different from return (z) Only one return value can be obtained.
Pointer is one double-edged sword Many operations can be naturally expressed through pointers, but incorrect or excessive use of pointers will bring a lot of potential errors to the program.
character string
C language character string In fact, it is a char type array ending with the ' 0' character. Using the character type does not need to reference the library, but using the string requires some functions in the C standard library to operate on the string. They are different from Character array Using these functions requires a reference to Header file
File input/output
In C language, input and output are realized through a set of functions in the standard library. stay ANSI C These functions are defined in the header file; Medium.
Standard I/O
There are three standard inputs/outputs that are Standard I/O Library Predefined:
stdin Standard input
stderr Input/output error
operation
The operation of C language is very flexible, and its functions are very rich. The types of operation are far more than others Programming language stay expression Compared with others programming language More concise, such as self addition, self subtraction, comma operation and ternary operation make the expression simpler, but beginners often find this expression difficult to read. The key reason is that operators and Operation order Incomplete understanding. When many different operations form an operation expression, that is, when there are many operators in an operation expression, the priority order and combination rules of operations become very important.

keyword

Keyword is also called Reserved word A word that has been used by C itself and cannot be used for other purposes. For example, keywords cannot be used as variable names, function names, etc identifier
Data Type Keyword
short : decorated int, short Integer data , the modified int can be omitted. (Introduced in K&R period)
long : modify int, long integer data, and the modified int can be omitted. (Introduced in K&R period)
long long : modify int, super long integer data, and the modified int can be omitted. C99 New standard)
signed : decorated integer data, signed data type. (New to C89 standard)
unsigned : decorated integer data, unsigned data type. (Introduced in K&R period)
restrict Used to qualify and constrain pointers and indicate that pointers are used to access a data object The initial and unique way of. (Added to C99 standard)
Complex Type Keyword
struct structural morphology Declaration. (Introduced in K&R period)
union : Consortium statement. (Introduced in K&R period)
enum : Enumeration declaration. (New to C89 standard)
typedef : Declare the type alias. (Introduced in K&R period)
sizeof : Get the size of a specific type or variable of a specific type. (Introduced in K&R period)
inline : Inline function Used to replace macro The definition will be expanded wherever it is called. C99 New standard)
Auto: specify as Automatic variable , automatically allocated and released by the compiler. Usually allocated on the stack. Contrary to static. When the variable is not specified, it defaults to auto. (Introduced in K&R period)
Static: specified as Static variable , allocated in the static variable area, when modifying the function, specify the function Scope Is internal to the file. (Introduced in K&R period)
register : Specify as register Variables. It is recommended that the compiler store variables in registers for use, or modify function parameters. It is recommended that the compiler use registers instead of stack Pass parameters. (Introduced in K&R period)
Extern: specify the corresponding variable as External variables That is, it indicates that the definition of the variable or function is in another file, prompting the compiler to look for its definition in other modules when encountering this variable or function. (Introduced in K&R period)
Const: The specified variable cannot be changed by the current thread (but may be changed by the system or other threads). (New to C89 standard)
volatile : The value of the specified variable may be changed by the system or other threads, forcing compiler Get the value of this variable from memory every time, preventing the compiler from optimizing this variable to register variable (New to C89 standard)
Jump Structure
return : Used in Function body , return a specific value (if the type is void, do not return function value )。 (Introduced in K&R period)
Continue: End the current cycle and start the next cycle. (Introduced in K&R period)
break : Jump out of the current loop or switch structure. (Introduced in K&R period)
goto : Unconditional jump statement. (Introduced in K&R period)
if: Conditional statement , no need to put it in the back semicolon (Introduced in K&R period)
Else: conditional statements deny branches (used with if). (Introduced in K&R period)
Switch: switch statement (multi branch statement). (Introduced in K&R period)
Case: Branch mark in switch statement, used with switch. (Introduced in K&R period)
Default: "Other" branch in switch statement, optional. (Introduced in K&R period) [1]

Grammatical structure

Sequential structure The program design of is the simplest, as long as the corresponding statements are written in the order of solving the problem, and its execution order is from top to bottom, in order to execute.
For example: a=3, b=5, now exchange the values of a and b. This problem is like exchanging the water in two cups. Of course, the third cup is used. If the third cup is c, then the correct procedure is: c=a; a=b;b=c, The execution result is a=5, b=c=3. If the order is changed, it is written as a=b; c=a;b=c; Then the execution result will become a=b=c=5, which can not achieve the expected purpose, and beginners are most likely to make such mistakes. The sequence structure can be used independently to form a simple complete program. The common three-step program of input, calculation and output is the sequence structure. For example, to calculate the area of a circle, the sentence order of the program is to input the radius r of the circle, calculate s=3.14159 * r * r, and output the surface product s. However, in most cases, the sequence structure is a part of the program and forms a complex program together with other structures, such as Compound statement Cyclic structure The circulator in.
Sequential structure Although the program can solve problems such as calculation and output, it can not be judged and selected again. For the problem that needs to be judged before selection, the selection structure should be used. The execution of structure selection is based on certain conditions, rather than strictly following the physical order of statements. The key to selecting a structured programming method is to construct appropriate branching conditions and analysis program Process, select appropriate Select statement Select a structure suitable for use with Logical OR The calculation of conditional judgment, such as relationship comparison, is usually first drawn when designing such programs Procedure flow chart , and then write according to the procedure flow source program In this way, the program design analysis is separated from the language, making the problem simple and easy to understand. The program flow chart is the program execution drawn according to the problem solving analysis flow chart
Cyclic structure
Cyclic structure It can reduce the workload of repeated writing of source program, and is used to describe the problem of repeated execution of a certain algorithm. This is the program structure that can give full play to the computer's specialty in program design. C language provides four kinds of loops, namely goto loop, while loop do while Cycle and For loop The four loops can be used to deal with the same problem. Generally, they can replace each other, but the goto loop is generally not recommended, because changing the order of the program by force often brings unexpected errors to the program operation.
Special attention should be paid to the statements that tend to end in the loop body (that is, the loop Variable value Otherwise, it may become an endless loop, which is a common mistake for beginners.
The similarities and differences of the three loops: when using while and do while loops, the initialization of loop variables should precede the loop body, while the for loop is generally performed in statement 1; Both the while loop and the for loop judge the expression before executing the loop body, while the do while loop executes the loop body before judging the expression, that is, the do while loop body is executed at least once, while the while loop and the for loop may not be executed once. Also note that these three cycles can be used break statement Jump out of the loop and end the loop with the continue statement, while goto The loop formed by statement and if cannot be controlled by break and continue statements.
Sequential structure , branch structure and circular structure are not isolated from each other. There can be branch and order structure in the cycle, and there can also be cycle and order structure in the branch. In fact, no matter what kind of structure, they can be regarded as a statement in a broad sense. In the actual programming process, these three structures are often combined with each other to realize various algorithms and design corresponding programs. However, the problem of programming is large, and the programs written are often very long and have many repeated structures, resulting in poor readability and difficult understanding. The solution to this problem is to design C programs into modularization Structure.
Specific contents:
For loop
For loop structure is the most characteristic of c language Loop statement It is the most flexible and convenient to use. Its general form is:
For (expression 1; Expression 2; Expression 3) Loop body statement. (Among them; cannot be omitted)
Expression 1 is the initial value expression, which is used to assign the initial value to the loop variable before the start of the loop.
Expression 2 is loop control Logical expression , which controls the conditions of loop execution and determines the number of cycles.
Expression 3 modifies the expression for the loop control variable, which makes the for loop end.
Cyclic body sentence is circular Control conditions A statement that is executed repeatedly when it is true.
However, in the whole process of the for loop, expression 1 is only evaluated once, expression 2 and expression 3 may be evaluated multiple times, or they may not be evaluated once. The loop body may be executed multiple times, or it may not be executed once.
First execute expression 2, then execute the loop structure, and finally execute expression 3. The loop continues like this.
The for loop statement is the most powerful statement in C language, and can even replace other statements to some extent Loop statement
do
Do loop structure, do 1 while (2); The execution order of is 1 ->2 ->1... cycle, and 2 is the cycle condition.
while
While loop structure, while (1) 2; The execution order of is 1 ->2 ->1... cycle, and 1 is the cycle condition
The above circular statement, when Conditional expression If it is true, the cycle will continue; if it is false, the cycle will jump out.

function

C programs are composed of a set of variables or external objects of functions. A function is a self contained execution that completes certain related functions Code snippet We can think of a function as a "black box". You can get the results just by sending the data in. How does the function work inside, External program I don't know. What the external program knows is limited to what is input to the function and what is output from the function. Functions provide the means of programming, making it easy to read, write, understand, eliminate errors, modify and maintain.
The number of functions in a C program is actually unlimited. If there is any limit, it is that a C program must have at least one function, and there must be one and only one function named main. This function is called the master function Principal function Start execution.
C language programs encourage and advocate people to divide a big problem into a sub problem, corresponding to the preparation of a function to solve a sub problem. Therefore, C language programs are generally composed of a large number of small functions rather than a small number of large functions, that is, the so-called "small functions constitute large programs". The advantage of this is that all parts are fully independent of each other and have a single task. Therefore, these fully independent small modules can also be used as small "components" with fixed specifications to form new large programs.
Over the years since the development of C language, the systems and programs developed with C language are vast. While developing, it has also accumulated a lot of things that can be used directly Library function
ANSI C provides standards C Library Functions
Turbo C 2.0, which is preferred by C language beginners, provides more than 400 Runtime function , each function completes a specific function, and users can call it at will. These functions are generally divided into input/output functions, mathematical functions, string and memory functions, and BIOS and DOS Relevant functions, character screen and graphic function functions, process control functions, directory functions, etc.
Windows System provided Windows SDK It contains thousands of functions related to Windows application development. Other operating systems, such as Linux , also provides a large number of functions for application developers to call.
As a programmer, you should be familiar with the functions of the target platform library. In this way, we can easily develop applications for specific platforms. For example, as a developer of Windows applications, you should try to be familiar with the Windows SDK; As Linux Application developers should be familiar with Linux system calls and POSIX Function specification. [1]

Operational symbol

In particular, the bit shift right (>>) operator can be arithmetic (left end complement Most significant bit )Or logical (0 is added at the left end) displacement. For example, move 11100011 3 bits to the right, Arithmetic Shift Right Then it becomes 11111100, and the logical right shift is 00011100. Due to the right shift of arithmetic bit, it is more suitable for processing band minus sign Integer, so almost all compilers shift arithmetic bits to the right.

Programming development

Announce
edit

compiler

Clang , open source BSD protocol Based on LLVM Compiler for
Visual C++ :: cl.exe, compiler provided by Microsoft VC++

Integrated development environment

Code::Blocks , open source free C/C++ IDE
Dev-C++ , portable C/C++IDE
Light Table

Sample program

Announce
edit
The following is a standard output device ( stdout )On, print "Hello, world!" character string Simple procedure of. Similar procedures, usually for beginners programing language First program at:
#include <stdio.h> int main(){     printf("Hello, World! \n");     return 0; }
  1. one
    The first line # include of the program is a preprocessor instruction that tells the C compiler to include the stdio. h file before actual compilation.
  2. two
    The next line, int main(), is the main function. The program starts from here.
  3. three
    The next line, printf (...), is another available function in C. The message "Hello, World!" will be displayed on the screen.
  4. four
    Next line return 0 ; Terminate the main() function and return the value 0. [8-9]
#include <stdio.h> int main(){ void move(int *xa,int *xb); int a,b; Printf ("Please enter two numbers a, b:"); scanf_s("%d,%d",&a,&b); move(&a,&b); printf("a=%d,b=%d\n",a,b); return 0; } void move(int *xa,int *xb){ int a; a=*xa; *xa=*xb; *xb=a; }
1. The third line of the program is the declaration of the function, declaring a "none" with two pointer parameters Return value Function. Since the function is defined at the calling function, it must be declared.
2. The fourth line is the definition of variables, which defines two Integer variable
3. Enter two numbers in the sixth line, which must be 1,0 comma Input in the mode of. Put two numbers into variables a and b. "&" is to get the address operator
4. Line 7 calls the move function to convert the values of the two variables.
five Main function This is followed by the definition of the move function.
As can be seen from this example, Pointer variable You can get more Return value This is very convenient.