C is an earlier languageProgramming 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 inUnderlying development。C language can compile and process low-level in a simple waystorage。C language only produces a small amountmachine languageAnd efficient programming language that can run without any support of running environment.Although C language provides many low-level processing functions, it still keepsCross platformC language program written in a standard specification can includeEmbedded processoras well asSupercomputerAnd many other operating platformsComputer platformCompile on.[1]
C language is aProcess orientedOfComputer programming language, and C++, C #JavaAnd other object-oriented programming languages.C languagedesign goal It provides a simple way to compile and process low-levelstorage. Only a small amount ofMachine codeAnd programming languages that can run without any support from the running environment.C language describes the problem ratioassembly languageFast, small workload, good readability, easy debugging, modification and transplantation, and code qualityassembly languageEquivalent.C language is generally only better thanassembly languagecode generationOfTarget programThe efficiency is 10% - 20% lower.Therefore, C language can write system software.[2]
At present, C language is widely used in the field of programminghigh-level languageCompared with other programming languages, it has more advantages than assembly language.computersystem designAnd application programming are two major areas of C language application.At the same time, C language is widely used in many computersoperating systemBoth can be applied to, and the efficiency is remarkable.[3]
C language has a completeTheoretical system, plays an important role in programming languages.[4]
Development history
Announce
edit
C language was born in the United StatesBell Laboratories, byDennis Ritchie (Dennis MacAlistair Ritchie)Kenneth Lan Thompson(Kenneth Lane Thompson)Language BIt 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 ThompsonLanguage B, andLanguage BFromBCPLLanguage.
In the 1960s, the United StatesAT&TcompanyBell 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 himselfsolar systemSpace Travel, a video game for sailing.He found a free table behind his boss's backSmall computer——PDP-7。But this computer doesn'toperating 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 simpleLanguage B(Take the first letter of BCPL), and write the first version in B languageUNIXOperating system (called UNICS).
In 1971, Dennis Ritchie, who also loved Space Travel, joined Thompson's development project in order to play games earlier,Cooperative developmentUNIX。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 completelyUNIX。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 Ritchiecode。[6]
In development, they also considerUNIXMigrate to other types ofcomputerUsed on.The powerful portability of C language is shown here.machine languageandassembly languageAre not transplantablex86The developed program cannot be used in AlphaSPARCandARMWait for the machine to run.C program can be used in any architectureprocessorAs long as the processor of that architecture has the corresponding C languagecompilerAnd libraries, and then Csource codeCompile and link to targetBinary fileThen 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 andAmerican 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 manufacturerscompilerAnd otherssoftware toolManufacturerSoftware designer, consultants, academics, C language authors andapplication programMember 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 wasInternational 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 ofStructured LanguageIt 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 comprehensiveoperatorAnd diversedata type, can easily complete variousdata structureThe pointer type can be used for memoryDirect addressingAnd hardwareDirect operationTherefore, 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 variousControl statementThere are only 9 types, and only 32 keywords. The programming requirements are not strict andLowercase lettersMainly, 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/outputfile managementAnd other functions. If such functions are required, coordination is requiredCompiling systemSupportedClass libraryC language has a very concise compilation system.[5]
(2) With structured control statements
C language is a kind ofStructuredThe provided control statements have structural features, such as for statements, if... else statements, andswitchStatement, etc.Can be used to implement thelogical control , convenientProcess orientedProgram design of.[5]
(3) Rich data types
C language contains a wide range of data types, including not only traditional character typeinteger、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 34operator, which treats assignment, parentheses, etc. as operators, so that theexpressionTypes and operator types are very rich.[5]
C language allows hardwareMemory addressDirect reading and writing can realize the main functions of assembly language and can be operated directlyHardware。C language not only hashigh-level languageIt 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]
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 hardwarehardware 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]
Compared with other high-level languages, C language can generate high-quality andhigh efficiencyObject code, so it is usually applied to those with high requirements for code quality and execution efficiencyEmbedded system Programming.[5]
Special features
C language isUniversalityThe strongest computerprogramEditing 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, etcdata structureTherefore, 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 programmingApplicability, not only can it be appliedProgrammerTo improve itswork efficiencyAt 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 hasSignificant advantagesAt 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 programsubscript out of boundsNo inspection, etc.From the perspective of application, C language is better than other languageshigh-level languageIt is difficult to master.That is to say, people who use C language are required to be more proficient in programming.[7]
The value of a constant cannot be changed. Symbolic constant names are usually capitalized.
The variable is based on aidentifier Is a name, and its value can be changed.identifier YesletterorUnderlineThe 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 correspondingStorage unit。
array
If a variable name is followed by a numericBrackets, this declaration is an array declaration.character stringIt is also an array.They useASCIINULL as the end of the array.It should be noted that the index value in the brackets starts from 0.
Pointer
If aVariable declarationThe * 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 tounary operator *, the same below.Otherwise in C languagebinary operator *) is to retrieve the contentOperator, meaning to take thisMemory addressContent stored in.Pointer is the difference between C language and other contemporarieshigh-level languageOne of the main characteristics of.
Pointer can be not only the address of a variable, but also an arrayArray element, the address of the function.By pointer asFormal parameterYou can get more than one return value during the function call, which is different fromreturn(z) Only one return value can be obtained.
Pointer is onedouble-edged swordMany 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 languagecharacter stringIn 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 fromCharacter array。Using these functions requires a reference toHeader file。
File input/output
In C language, input and output are realized through a set of functions in the standard library.stayANSI CThese functions are defined in the header file;Medium.
The operation of C language is very flexible, and its functions are very rich. The types of operation are far more than othersProgramming language。stayexpressionCompared with othersprogramming languageMore 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 andOperation orderIncomplete 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 calledReserved wordA 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, etcidentifier 。
Data Type Keyword
short: decorated int, shortInteger 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.(C99New 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 adata objectThe initial and unique way of.(Added to C99 standard)
Auto: specify asAutomatic 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 asStatic variable, allocated in the static variable area, when modifying the function, specify the functionScopeIs internal to the file.(Introduced in K&R period)
register: Specify asregisterVariables. 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 ofstackPass parameters.(Introduced in K&R period)
Extern: specify the corresponding variable asExternal variablesThat 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, forcingcompilerGet the value of this variable from memory every time, preventing the compiler from optimizing this variable toregister variable。(New to C89 standard)
Sequential structureThe 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 asCompound statement、Cyclic structureThe circulator in.
Sequential structureAlthough 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 andanalysis programProcess, select appropriateSelect statement。Select a structure suitable for use withLogical ORThe calculation of conditional judgment, such as relationship comparison, is usually first drawn when designing such programsProcedure flow chart, and then write according to the procedure flowsource programIn 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 analysisflow chart。
Cyclic structure
Cyclic structureIt 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 loopdo whileCycle andFor 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 loopVariable valueOtherwise, 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 usedbreak statement Jump out of the loop and end the loop with the continue statement, whilegotoThe 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 intomodularizationStructure.
Specific contents:
For loop
For loop structure is the most characteristic of c languageLoop statementIt 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 controlLogical 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 circularControl conditionsA 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 extentLoop 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, whenConditional expressionIf 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 functionsCode 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 programI 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 functionPrincipal functionStart 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 directlyLibrary function。
Turbo C 2.0, which is preferred by C language beginners, provides more than 400Runtimefunction, 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, andBIOSandDOSRelevant functions, character screen and graphic function functions, process control functions, directory functions, etc.
WindowsSystem providedWindows SDKIt contains thousands of functions related to Windows application development.Other operating systems, such asLinux, 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;AsLinuxApplication developers should be familiar with Linux system calls andPOSIXFunction specification.[1]
Operational symbol
In particular, the bit shift right (>>) operator can be arithmetic (left end complementMost significant bit)Or logical (0 is added at the left end) displacement.For example, move 11100011 3 bits to the right,Arithmetic Shift RightThen it becomes 11111100, and the logical right shift is 00011100.Due to the right shift of arithmetic bit, it is more suitable for processing bandminus signInteger, so almost all compilers shift arithmetic bits to the right.
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.
two
The next line, int main(), is the main function. The program starts from here.
three
The next line, printf (...), is another available function in C. The message "Hello, World!" will be displayed on the screen.
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 parametersReturn valueFunction.Since the function is defined at the calling function, it must be declared.
2. The fourth line is the definition of variables, which defines twoInteger variable。
3. Enter two numbers in the sixth line, which must be 1,0commaInput in the mode of.Put two numbers into variables a and b."&" is to get the addressoperator。
4. Line 7 calls the move function to convert the values of the two variables.
fiveMain functionThis is followed by the definition of the move function.