In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to learn C language". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to learn C language"!
Preface
C language is an abstract and process-oriented language. C language is widely used in low-level development. C language plays an irreplaceable role in the computer system. It can be said that C language is the basis of programming, that is to say, no matter you learn any language, you should put C language in the first place. The following picture better illustrates the importance of C language.
As you can see, C language is a low-level language, is a system-level language, the operating system is written in C language, such as Windows, Linux, UNIX. If other languages are beautiful appearance, then C language is the soul, always so simple.
C language characteristics
So, since C language is so important, what is it worth learning? We should not learn just because it is important. We are more concerned about what we can learn and what we can get after learning.
The Design of C language
The C language was designed in 1972 by Dennis Ritchie (Dennis Ritch) and Ken Thompson (Ken Thompson) of Bell Labs when they developed the UNIX operating system. C language is a popular language, which combines computer science theory and engineering practice theory perfectly, so that users can complete modular programming and design.
Computer science theory: referred to as CS, is the theoretical basis for the systematic study of information and computing and how to achieve and apply them in computer systems.
C language has high efficiency.
C language is an efficient language, which is designed to give full play to the advantages of computers, so C language programs run very fast, and C language can reasonably use memory to obtain maximum running speed.
C language is portable.
C language is a portable language, which means that C language programs written on one computer can be easily run on another computer, thus greatly reducing the workload of program transplantation.
Features of C language
C language is a concise language, because the design of C language is closer to the bottom, so it does not need the features of many high-level languages such as Java and C #, and the programming requirements are not very strict.
C language has structured control statements. C language is a structured language. The control statements it provides have structural characteristics, such as for loop, if ⋯else judgment statement, switch statement and so on.
C language has rich data types, including not only traditional character type, integer type, floating point type, array type and other data types, but also data types that other programming languages do not have, such as pointers.
C language can read and write memory address directly, so it can realize the main functions of assembly language and operate the hardware directly.
The speed of C language is fast and the execution efficiency of the generated object code is high.
Let's illustrate the C language through a simple example.
Entry-level C language program
Let's take a look at a very simple C language program. I am a mac computer, so I use xcode for development. I think it doesn't matter if you can use it easily.
The first C language program
# include int main (int argc, const char * argv []) {printf ("Hello, World!\ n"); printf ("my Name is cxuan\ n") printf ("number =% d\ n", number); return 0;}
You may not know what this code means, but don't worry, let's run it first to see the results.
This program outputs Hello,World! And My Name is cxuan, the last line is the execution result of the program, indicating whether there is an error in the program. Let's explain the meaning of each line of code.
First, the first line of # include, which contains another file, tells the compiler to include the contents of stdio.h in the current program. Stdio.h is the standard part of the C compiler package, which can provide keyboard input and display output.
What is the C standard software package? C is a general, procedural, imperative computer programming language developed by Dennis M in 1972. The C standard library is a set of C language built-in functions, constants and header files, such as, and so on. This library will be used as a reference manual for C programmers.
We'll introduce stdio.h later, and now you know what it is.
The next line of code in stdio.h is the main function.
C programs can contain one or more functions, and functions are the foundation of the C language, just as methods are the basic components of Java. Main () represents a function name, and int indicates that the main function returns an integer. Void indicates that main () does not take any parameters. We'll explain these in more detail later, just remember that int and void are part of the standard ANSI C definition main () (ignore void if you use a compiler prior to ANSI C).
Then / * A simple C language program * / represents a comment, which is represented by / * /, and the content of the comment is between the two symbols. These symbols can improve the readability of the program.
Note: comments are only intended to help programmers understand the meaning of the code, and the compiler ignores comments
Here is {, this is the left curly bracket, which represents the beginning of the function body, and the last right curly bracket} indicates the end of the function body. {} the middle is the place where the code is written, also known as the code block.
Int number means that a variable named number will be used, and number is an integer type of int.
Number = 11 represents a variable that assigns a value of 11 to number.
Printf (Hello,world!\ n); means to call a function that uses the printf () function to display Hello,world on the screen. The printf () function is one of the C standard library functions that can output the results of the program to the display. And the code\ nrepresents a new line, that is, another line, moving the cursor to the next line.
Then the next line printf () is the same as the previous line, so we won't say much about it. The last line printf () is interesting, and you'll find that there is a syntax for% d, which means to output a string using shaping.
The last line of the code block is return 0, which can be thought of as the end of the main function, and the last line is the code block}, which represents the end of the program.
Well, now that we have finished writing the first C language program, do we have a better understanding of C? Definitely not. Where is it? go on with your study.
Now, we can sum up several elements of the C language program, as shown in the following figure
C language execution flow
The reason why a C language program becomes a high-level language is that it can read and understand people's thoughts. However, in order to be able to run hello.c programs in the system, each C statement must be converted from other programs into a series of low-level machine language instructions. These instructions are packaged as executable object programs and stored in binary disk files. An object program is also called an executable object file.
In UNIX systems, the conversion from source files to object files is performed by the compiler.
Gcc-o hello hello.c
The gcc compiler driver reads hello.c from the source file and translates it into an executable file called hello. The translation process can be represented by the following figure
This is a complete hello world program execution process, which will involve several core components: preprocessor, compiler, assembler, connector, which we will break down one by one.
In the preprocessing phase (Preprocessing phase), the preprocessor modifies the source C program based on the initial # character. The # include command tells the preprocessor to read the contents of the system header file stdio.h and insert it into the program as text. Then you get another C program, hello.i, which usually ends with .i.
Then there is the compilation phase (Compilation phase), where the compiler translates the text file hello.i into the text hello.s, which includes an assembly language program (assembly-language program).
After compilation, the assembly phase (Assembly phase) is completed, in which the assembler as translates the hello.s into machine instructions, which are packaged into relocatable binaries (relocatable object program) and placed in the hello.c file. The 17 bytes it contains is the instruction encoding of the function main, and if we open hello.o in a text editor, we will see a pile of garbled code.
The last one is the linking phase (Linking phase), where our hello program calls the printf function, which is part of the C standard library provided by the C compiler. The printf function is located in a file called printf.o, which is a separate precompiled object file that must be linked to our hello.o, and the ld handles the merge operation. As a result, the hello file, which is an executable object file (or executable), is ready to be loaded into memory and executed by the system.
You need to understand what the compiler does.
For the simple hello program above, we can rely on the compiler system (compilation system) to provide a correct and effective machine code. However, for the programmers we mentioned above, there are several characteristics of compilers that you need to know.
To optimize program performance (Optimizing program performance), modern compilers are efficient tools for generating good code. For programmers, you don't have to understand what's going on inside the compiler in order to write high-quality code. However, in order to write efficient C language programs, we need to understand some basic machine code and the process by which the compiler converts different C statements into machine code.
Understanding the Understanding link-time errors of linking, in our experience, some very complex errors are mostly caused by the linking phase, especially when you want to build large software projects.
Avoid security vulnerabilities (Avoiding security holes). In recent years, buffer overflow (buffer overflow vulnerabilities) is the main culprit of network and Internet services, so it is necessary for us to avoid this problem.
Hardware composition of the system
In order to understand what happens when the hello program is running, we need to first have an understanding of the hardware of the system. Here is a model of the Intel system product, which we will explain.
Buses: what runs throughout the system is a collection of electrical pipes called buses that transfer byte information back and forth between components. The bus is usually designed to transmit fixed-length blocks of bytes, namely words (word). The number of bytes (word length) in a word is a basic system parameter, which varies from system to system. Now most words are 4 bytes (32 bits) or 8 bytes (64 bits).
The Input/Output device is the connection between the system and the outside world. There are four types of Istroke O devices in the image above: a keyboard and mouse for user input, a display for user output, and a disk drive for storing data and programs for a long time. At the beginning, the executable program is saved on disk. Each I controller O device that connects to the I hand O bus is called a controller (controller) or an adapter (Adapter). The main difference between the controller and the adapter is the way it is encapsulated. The controller is a chipset on either the Icano device itself or the system's main printed board circuit (commonly referred to as the motherboard). The adapter is a card plugged into the slot of the motherboard. Regardless of the form of organization, their ultimate goal is to exchange information with each other.
Main memory (Main Memory), which is a temporary storage device, not permanent storage, and a disk is a permanent storage device. Main memory saves not only the program, but also the data processed by the processor. In terms of physical composition, main memory is a set of DRAM (dynamic random access memory) dynamic random storage. Logically, memory is a linear array of bytes with its unique address number, starting at 0. Generally speaking, each machine instruction that makes up a program is made up of a different number of bytes, and the size of the data item corresponding to the C program variable varies according to the type. For example, on Linux's x86-64 machine, data of type short requires 2 bytes, int and float need 4 bytes, and long and double need 8 bytes.
A processor (Processor), CPU (central processing unit), or a simple processor is an engine that interprets (and executes) instructions stored in main memory. A storage device (or register) whose core size is one word, called a program counter (PC). At any time, the PC points to a machine language instruction in main memory (that is, the address that contains the instruction). From the time the system is powered on, until the system is powered off, the processor continues to execute the instruction pointed to by the program counter, and then updates the program counter to point to the next instruction. The processor operates according to the instruction model defined by its instruction set architecture. In this model, instructions are executed in a strict order, and the execution of an instruction involves a series of steps. The processor reads the instruction from the memory pointed to by the program counter, interprets the bits in the instruction, performs some simple operations indicated by the instruction, and then updates the program counter to point to the next instruction. Instructions may be continuous or discontinuous (for example, jmp instructions will not be read sequentially) here are a few steps that CPU may perform simple operations
Load: copy a byte or word from main memory into memory, overwriting the previous contents of the register
Store: copies bytes or words in a register to a location in the main memory, overwriting the previous contents of that location
Operate: copy the contents of the two registers to ALU (Arithmetic logic unit). Perform an arithmetic operation on the two words, and store the result in the register, rewriting the previous contents of the register.
Arithmetic logic unit (ALU) is a combined digital electronic circuit that performs arithmetic and bitwise operations on digital binary numbers.
Jump: extract a word from an instruction and copy the word to the program counter (PC), overwriting the original value
Analyze the execution process of hello program
Earlier, we briefly introduced the composition and operation of the computer's hardware, and now we formally introduce what happened when running the sample program. We will describe it from a macro point of view and will not cover all the technical details.
At first, the shell program executes its instructions, waiting for the user to type a command. When we type the characters. / hello on the keyboard, the shell program reads the characters into the register one by one and puts them into memory, as shown in the following figure.
When we hit enter on the keyboard, the shell program knows that we have finished typing the command. Shell then executes a series of instructions to load the executable hello file, which copies the code and data in the target file from disk to main memory.
Using DMA (Direct Memory Access) technology, you can directly copy the data from the disk to memory, as follows
Once the code and data in the hello in the object file are loaded into main memory, the processor begins to execute the machine language instructions in the main program of the hello program. These instructions copy the bytes in the hello,world\ nstring from the main memory to the register file, then from the register to the display device, and finally display them on the screen. As shown below
Cache is the key
Above we introduced the execution process of a hello program, and the system spent a lot of time moving information from one place to another. The machine instructions of the hello program are initially stored on disk. When programs are loaded, they are copied to main memory. When CPU starts running, the instructions are copied from memory to CPU. Similarly, the string data hello,world\ nwas originally on disk and was copied to memory and then output to the display device. From the programmer's point of view, most of this replication is overhead, which slows down the efficiency of the program. Therefore, for system design, one of the most important tasks is to make the program run faster and faster.
Because of the laws of physics, larger storage devices are slower than smaller ones. Due to the increasing efficiency of register and memory processing, system designers use a smaller and faster storage device, called cache memory (cache cache for short), as a temporary assembly area to store information that may be needed in the near future. As shown in the following figure
In the figure, we mark the location of the cache. The L1 cache capacity in the cache can reach tens of thousands of bytes, and the access speed is almost as fast as accessing the register file. The larger L2 cache links CPU through a special bus. Although L2 cache is 5 times slower than L1 cache, it is still 5-10 times faster than memory. L1 and L2 are implemented using a hardware technology of static random access memory (SRAM). The latest, more processor-powerful systems even have three levels of cache: L1, L2, and L3. The system can obtain a large memory, and the access speed is faster because of the locality principle of cache.
Again: details of the getting started program
Now, let's take a look at the details of the entry-level program and take a look at the features of the C language.
# include
As we mentioned above, # include is something to be processed before the program is compiled, which is called the compilation preprocessing command.
The preprocessing command is processed before compilation. The preprocessor usually starts with the # sign
All C compiler packages provide stdio.h files. This file contains the input and output functions used by the compiler, such as println () information. The file name means standard input / output header file. Typically, the collection of information at the top of a C program is called a header file (header).
The first standard of C was published by ANSI. Although this document was later adopted by the International Organization for Standardization (ISO) and the revised version released by ISO was adopted by ANSI, the name ANSI C (rather than ISO C) is still widely used. Some software developers use ISO C, while others use Standard C.
C standard library
In addition to the C standard library, the following header files are included
A keyword called assert is provided, which is used to verify the hypothesis made by the program and to output diagnostic messages when the hypothesis is false.
The ctype.h header file of the C standard library provides functions that can be used to test and map characters.
These characters accept int as a parameter, and its value must be EOF or an unsigned character
EOF is a computer term, an abbreviation for End Of File, which means that there is no more data to read from the data source in the operating system. A data source is often referred to as a file or stream. This character usually exists at the end of the text to indicate the end of the data.
The errno.h header file of the C standard library defines the integer variable errno, which is set by the system call, and these library functions indicate what went wrong.
The float.h header file of the C standard library contains a set of platform-dependent constants related to floating-point values.
The limits.h header file determines the various attributes of various variable types. The macros defined in this header file restrict the values of various variable types, such as char, int, and long.
Locale.h header files define region-specific settings, such as date formats and currency symbols
The math.h header file defines various mathematical functions and a macro. All functions available in this library take a parameter of type double and return results of type double.
The setjmp.h header file defines the macro setjmp (), function longjmp (), and variable type jmp_buf, which bypasses the normal function call and return rules.
The signal.h header file defines a variable type sig_atomic_t, two function calls, and some macros to handle the different signals reported during program execution.
The stdarg.h header file defines a variable type va_list and three macros that can be used to obtain parameters in a function when the number of parameters is unknown (that is, the number of parameters is variable).
The stddef .h header file defines various variable types and macros. Most of these definitions also appear in other header files.
The stdlib .h header file defines four variable types, some macros, and various general utility functions.
The string .h header file defines a variable type, a macro, and various functions that manipulate an array of characters.
The time.h header file defines four variable types, two macros, and various functions for manipulating dates and times.
Main () function
The main function sounds like a naughty child deliberately naming a method a major method to tell others that he is the center of the world. But this is not the case, and the main () method is indeed the center of the world.
C language programs must start from the main () function, in addition to the main () function, you can name other functions. Usually, some incoming information is indicated in the () after the main, which is not passed in our example above, because the input in parentheses is void.
In addition to the above, there are two ways to express the main method, one is void main () {}, the other is int main (int argc, char* argv []) {}
Void main () declares a constructor with uncertain parameters
The argc in int main (int argc, char* argv []) {} is a non-negative value indicating the number of parameters passed to the program from the environment in which the program is running. It is a pointer to the first element of the argc + 1 pointer array, the last of which is null, and the previous, if any, points to a string that represents the parameters passed to the program from the host environment. If argv [0] is not a null pointer (or equivalent, if argc > 0), it points to a string that represents the program name, which is empty if the program name cannot be used in the host environment.
Annotation
In the program, the use of / * / to express comments is of no practical use to the program, but it is very useful to programmers. It can help us understand the program and let others understand the program you have written. We are very disgusted with people who do not write comments in our development work, so it can be seen that comments are very important.
The advantage of C language comments is that they can be placed anywhere, even if the code is on the same line. Longer comments can be represented by multiple lines, we use / * / to represent multiple-line comments, and / / to represent only single-line comments. Here are several representations of comments
/ / this is a single-line comment / * multiple-line comments are represented by one line * / * multiple-line comments are represented by multiple lines * /
Function body
After the header file and the main method is the function body (comments are not usually counted). The function body is the execution body of the function, where you write a lot of code.
Variable declaration
In our entry-level code, we declare a variable named number, which is of type int, which is called a declaration, which is one of the most important features of the C language. This declaration does two things: it defines a variable named number that defines the specific type of number.
Int is a keyword (keyword) of C language, which represents a basic C language data type. Keywords are used for language definition. You cannot use keywords as variables to define.
The number in the example is an identifier, that is, the name of a variable, function, or other entity.
Variable assignment
In the starter example program, we declare a number variable and assign it a value of 11, which is one of the basic operations of the C language. This line of code means to assign a value of 1 to the variable number. When executing int number, the compiler reserves space for the variable number in computer memory, and then stores the value in the previously reserved location when executing this line of assignment expression statements. You can assign different values to number, which is why number is called a variable.
Printf function
In the starter example program, there are three lines of printf (), which is the standard function of the C language. The contents in parentheses are passed from the main function to the printf function. There are two types of parameters: actual parameters (actual argument) and formal parameters (formal parameters). The parentheses of the printf function we mentioned above are all arguments.
Return statement
In the starter example program, the return statement is the last statement. The int in int main (void) indicates that the main () function should return an integer. C functions with return values should have return statements, and programs with no return values are also advised to keep the return keyword, which is a good habit or a unified coding style.
semicolon
In C, the end of each line is used; the end, which indicates the end of a statement, will be prompted by the compiler if you forget or will miss the semicolon.
Keyword
The following are the keywords in C language. There are 32 keywords in C language, which are divided according to their different functions.
Data type keyword
There are 12 main keywords for data types, which are
Char: declare a character variable or function
Double: declare a double-precision variable or function
Float: declare floating-point variables or functions
Int: declare an integer variable or function
Long: declare long integer variables or functions
Short: declare a short integer variable or function
Signed: declare a signed type variable or function
_ Bool: declare Boolean types
_ Complex: declare plural
_ Imaginary: declare imaginary numbers
Unsigned: declare unsigned type variables or functions
Void: declares that the function has no return value or arguments, and declares no typed pointer
Control statement keyword
There are also 12 keywords to control the statement loop, which are
Loop statement
For: for loop, most used
Do: the prerequisite loop body of a loop statement
While: the loop condition of a loop statement
Break: jump out of the current cycle
Continue: ends the current cycle and starts the next cycle
Conditional statement
If: the judgment condition of conditional statement
Else: the negative branch of a conditional statement, used with if
Goto: unconditional jump statement
Switch statement
Switch: for switch statements
Case: another branch of the switch statement
Default: other branches in the switch statement
Return statement
Retur: subroutine returns statements (with or without parameters)
Storage type keyword
Auto: declaring automatic variables is generally not used
Extern: declaring a variable is being declared in another file (can also be seen as a reference variable)
Register: declare register variables
Static: declare static variables
Other keywords
Const: declare read-only variables
Sizeof: calculating the length of the data type
Typedef: used to alias data types
Volatile: indicates that variables can be implicitly changed during program execution
At this point, I believe you have a deeper understanding of "how to learn C language". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 292
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.