preface

C language is an abstract, 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 foundation of programming, that is to say, no matter you learn any language, should put C language on the first place to learn. The following chart better illustrates the importance of C

As can be seen, C language is a low-level language, a system-level language, operating systems are written in C language, such as Windows, Linux and UNIX. If other languages are glamorous, C is the soul, always unpretentious.

Original link: C language foundation, come!

C language Features

So, since C is so important, what is there to learn about it? We should not only learn because it is important, we care more about what we can learn and what we can get after learning.

C language design

C was designed in 1972 by Dennis Ritch and Ken Thompson of Bell LABS while developing the UNIX operating system. C language is a popular language, which perfectly integrates computer science theory and engineering practice theory, enabling users to complete modular programming and design.

Computer science theory: CS for short, is the systematic study of the theoretical basis of information and computing and how they are implemented and applied in computer systems.

C language has high efficiency

C language is a highly efficient language, it is designed to give full play to the advantages of the computer, so C language programs run very fast, C language can reasonable use of memory to obtain the maximum speed

C language has the portability

C language is a language with portability, 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 C language design is more close to the bottom, so do not need many Java, C# and other high-level language features, the program writing requirements are not very strict.
  • C language has structured control statements, C language is a structured language, it provides control statements with structured characteristics, such as for loop, if… else statement and switch statement.
  • C language has a wealth of data types, including not only the traditional character type, integer type, floating point type, array type and other data types, but also other programming languages do not have data types, such as Pointers.
  • C language can directly read and write memory address, so it can realize the main functions of assembly language, and can directly operate hardware.
  • C language is fast, the generated object code execution efficiency is high.

Let’s use a simple example to illustrate the C language

Entry-level C language program

Now let’s take a look at a very simple C language program, I think tools don’t matter you use handy line.

The first C language program

#include <stdio.h>

int main(int argc, const char * argv[]) {
    printf("Hello, World! \n");
  
  	printf("my Name is cxuan \n")
    
    printf("number = %d \n", number);
    
    return 0;
}
Copy the code

You may not know what this code means, but don’t worry, let’s run it first and see what happens.

This program prints Hello,World! And My Name is CXuan. Now let’s explain the meanings 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 a standard part of the C compiler package that provides keyboard input and monitor output.

What is a STANDARD C package? C is a general-purpose, procedural, imperative computer programming language developed by Dennis M. in 1972. The C library is a set of built-in C functions, constants, and header files, such as <stdio.h>, <stdlib.h>, <math.h>, etc. This library will be used as a reference manual for C programmers.

We’ll talk about stdio.h later, but now you know what it is.

The line below stdio.h is the main function.

C programs can contain one or more functions, which are fundamental to THE C language, just as methods are fundamental to Java. Main () denotes a function name, and int denotes that main returns an integer. Void indicates that main() takes no arguments. We’ll cover all of this later, just remember that int and void are part of the ANSI C definition of main() (if using a compiler prior to ANSI C, ignore void).

Then /* A simple C program */ represents a comment, which is represented by /**/, with the content of the comment between two symbols. These symbols improve the readability of the program.

Note: Comments are intended only to help the programmer understand what the code means; the compiler ignores them

And then we have {, that’s the open curly bracket, that’s the beginning of the function body, and the last close curly bracket} is the end of the function body. The middle of {} is where the code is written, also called a code block.

Int number means that a variable named number will be used, and number is an int integer.

Number = 11 represents the variable that assigns the value 11 to number.

printf(Hello,world! \n); This statement uses printf() to display Hello,world on the screen. Printf () is one of the C library functions that output the results of a program’s execution to the monitor. The code \n, on the other hand, means newline, that is, starting on another line and moving the cursor to the next line.

And then the next line printf() is the same as the top line, so we won’t go into it. The last line printf() is a little bit interesting, and you’ll notice that there’s a %d syntax that says to print a string using an integer.

The last line of the code block is return 0, which can be seen as the end of main, and the last line is the code block}, which indicates the end of the program.

Ok, now that we’ve written our first C program, have we gained a deeper understanding of C? Definitely not… That’s where it is. Keep studying.

Now, we can summarize the components of a C program, as shown in the figure below

C language to execute the flow

C programs are a high-level language because they can read and understand people’s minds. However, in order to run the hello.c program on the system, individual C statements must be converted by 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.

On UNIX systems, conversion from source files to object files is performed by the compiler.

gcc -o hello hello.c
Copy the code

The GCC compiler driver reads Hello.c from the source file and translates it into an executable file called Hello. This translation process can be illustrated in the figure below

This is the complete Execution of a Hello World program, which involves several core components: a preprocessor, a compiler, an assembler, and a connector, which we’ll break down one by one.

  • In the Preprocessing phase, the preprocessor modifies the source C program based on the # character at the beginning. 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 in.i.

  • The Compilation phase is followed by the compiler translating the text file Hello. I into the text Hello. S, which includes an assembly-language program.

  • Following compilation is the Assembly phase, where the assembler as translates Hello. s into machine instructions and packages these instructions into the Relocatable Object Program in the hello.c file. It contains 17 bytes of instruction encoding the main function, and if we open Hello. o in a text editor we’ll see a bunch of garbled characters.

  • Finally, there is the 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 pre-compiled object file that must be linked to our hello.o. The linker (LD) handles the merge. As a result, the Hello file, which is an executable object file (or executable file), is ready to be loaded into memory and executed by the system.

You need to understand what the compilation system does

For a simple Hello program like the one above, we could rely on the compilation system to provide a correct and valid machine code. However, for the programmers we talked about above, there are a few characteristics of compilers that you need to know

  • Optimizing Program PerformanceModern compilers are an efficient tool for generating good code. As a programmer, you don’t need to understand what’s going on inside the compiler in order to write high-quality code. However, in order to write efficient C programs, we need to understand some basic machine code and how the compiler converts different C statements into machine code.
  • Understanding link-time errorsIn our experience, some very complex errors are mostly caused by the linking phase, especially if you want to build large software projects.
  • Avoiding security holesIn recent years,Buffer overflow vulnerabilities were ignored.Is the main culprit of the network and Internet services, so we need to avoid this problem.

System hardware composition

To understand what happens when the Hello program runs, we need to first have an understanding of the system’s hardware. Here is a model of an Intel system product to explain

  • Bus (Buses)Running throughout the system are collections of electrical pipes called buses that transfer bytes of information back and forth between components. Usually buses are designed to transmit chunks of fixed length, i.eWord (word). The number of bytes in a word (word length) is a basic system parameter that varies from system to system. Most words today are 4 bytes (32 bits) or 8 bytes (64 bits).

  • I/O Devices: Input/Output Devices are the connections between the system and the outside world. In the figure above, there are four types of I/O devices: a keyboard and mouse for user input, a display for user output, and a disk drive for storing data and programs for long periods of time. In the beginning, executable programs are saved on disk.

    Each I/O device connected to the I/O bus is called a controller or Adapter. The main difference between controllers and adapters is encapsulation. A controller is a chipset on the I/O device itself or on the system’s main printed board circuit (usually called the motherboard). The adapter is a card that plugs into a slot on the motherboard. Regardless of the form of organization, their ultimate purpose is to exchange information with each other.

  • Main Memory. Main Memory is a temporary storage device, not permanent storage. Disks are permanent storage devices. Main memory holds both the program and the data processed by the processor to execute the flow. In terms of physical composition, main memory is a set of dynamic random access memory (DRAM). Logically, memory is a linear byte array with its unique address number, starting at 0. Generally, 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 x86-64 machines, short data takes 2 bytes, int and float 4 bytes, and long and double 8 bytes.

  • A Processor, central processing unit (CPU), or simple Processor is an engine that interprets (and executes) instructions stored in main memory. The processor’s core is a one-word storage device (or register) called a program counter (PC). At any given moment, the PC points to a machine-language instruction in main memory (that is, the address containing the instruction).

    From the time the system is powered on until the system is powered off, the processor continuously executes 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 an instruction model defined by its instruction set architecture. In this model, instructions are executed in strict order, and executing an instruction involves executing a series of steps. The processor reads instructions from memory pointed to by the program counter, interprets the bits in the instruction, performs some simple operations that the instruction instructs, and then updates the program counter to point to the next instruction. Instructions may be sequential or dissequential (for example, JMP instructions are not read sequentially)

    Here are a few steps where the CPU might perform a simple operation

  • Load: To copy a byte or word from main memory into memory, overwriting the previous contents of a register

  • Store: The copying of a byte or word in a register to a location in main storage, overwriting the previous contents of that location

  • Operate: copy the contents of the two registers to the Arithmetic logic unit (ALU). To perform arithmetic operations on two words and store the result in a register, overwriting the previous contents of the register.

An arithmetic logic unit (ALU) is a combined digital electronic circuit that performs arithmetic and bitwise operations on numeric binary numbers.

  • Jump, jump): Extracts a word from the instruction and copies the word toProgram counter (PC)Overrides the original value

Analyze the execution of the Hello program

Now let’s take a more formal look at what happens when we run the example program. We’ll describe it from a macro point of view, without getting into all the technical details

At first, the shell program executes its instructions and waits for the user to type a command. When we type the./hello characters on the keyboard, the shell program reads the characters one by one into registers and puts them into memory, as shown in the figure below

When we hit enter on the keyboard, the shell program knows we have finished typing a command. The shell then loads the executable Hello file with a series of instructions that copy the code and data from the object file from disk to main memory.

Using DMA(Direct Memory Access) technology, you can directly copy data from disk to Memory, as shown below

Once the code and data from Hello in the object file are loaded into main memory, the processor starts executing the machine language instructions in the Main program of the Hello program. These instructions copy the bytes in the Hello, World \n string from main memory to a register file, from the register to the display device, and finally to the screen. As shown below.

Caching is key

Above we have described the execution of a Hello program. The system spends a lot of time moving information from one place to another. The machine instructions for the Hello program are initially stored on disk. When programs are loaded, they are copied to main memory. When the CPU starts running, instructions are copied from memory to the CPU. Similarly, the string data Hello,world \n is originally on disk, copied into memory, and then output to the display device. From the programmer’s point of view, much of this copying is overhead, which slows down the efficiency of the program. Therefore, for system design, one of the most important jobs is to make the program run faster and faster.

Due to the laws of physics, larger storage devices are slower than smaller ones. As the processing of registers and memory becomes more and more efficient, system designers address this difference by using smaller and faster storage devices called cache memory (cache memory for short), which serve as temporary staging areas for information that may be needed in the near future. As shown in the figure below

We have indicated the location of the cache. The L1 cache in the cache can be in the tens of thousands of bytes and can be accessed almost as fast as a register file. The larger L2 cache is linked to the CPU through a special bus. Although L2 cache is five times slower than L1 cache, it is still five to ten times faster than memory. L1 and L2 are implemented using a hardware technology called static random access memory (SRAM). The latest, more powerful systems even have three levels of caches: L1, L2, and L3. The system can obtain a large memory and access speed is also faster because of the principle of caching locality.

Again: Getting started with program details

Now, let’s go into the details of an entry-level program and take a step-by-step look at the features of THE C language.

#include<stdio.h>

As we mentioned above, #include

is what is processed before the program is compiled, called a compile preprocessor command.

Preprocessing commands are processed before compilation. Preprocessors typically start with a #.

All C compiler packages come with the stdio.h file. This file contains input and output functions for use by the compiler, such as println() information. The meaning of this file name is standard input/output header file. Typically, the collection of information at the top of a C program is called a header.

The first standard for C was published by ANSI. Although this document was later adopted by the International Organization for Standardization (ISO) and revisions published by ISO were adopted by ANSI, the name ANSI C(rather than ISO C) is still widely used. Some software developers use ISO C, others use Standard C.

The C standard library

In addition to <sdtio.h>, the C library includes the following header files

<assert.h>

A keyword named Assert is provided that validates the assumptions made by the program and prints diagnostic messages if the assumptions are false.

<ctype.h>

The C library’s ctype.h header provides functions that can be used to test and map characters.

These characters take an int as an argument, and their value must be EOF or an unsigned character

EOF is a computer term, short for End Of File, used in an operating system to indicate that a data source has no more data to read. Data sources are often referred to as files or streams. This character usually exists at the end of the text to indicate the end of the data.

<errno.h>

The C library’s errno. H header defines the integer variable errno, which is set through the system call, and these library functions indicate what went wrong.

<float.h>

The C library’s float.h header contains a set of platform-dependent constants related to floating-point values.

<limits.h>

The limits.h header determines various attributes for various variable types. Macros defined in this header file limit the values of various variable types, such as char, int, and long.

<locale.h>

The locale.h header defines location-specific Settings, such as date formats and currency symbols

<math.h>

The math.h header defines various mathematical functions and a macro. All functions available in this library take a double as an argument and return a double.

<setjmp.h>

The setjmp.h header defines the macro setjmp(), the function longjmp(), and the variable type jmp_buf, which circumvents normal function calls and return rules.

<signal.h>

The signal.h header defines a variable type sig_atomic_t, two function calls, and macros to handle the different signals reported during program execution.

<stdarg.h>

The stdarg.h header defines a variable type, va_list, and three macros that can be used to get arguments in a function when the number of arguments is unknown (that is, variable).

<stddef.h>

The stddef.h header defines various variable types and macros. Most of these definitions also appear in other header files.

<stdlib.h>

The stdlib.h header defines four variable types, some macros, and various general-purpose utility functions.

<string.h>

The string. h header defines a variable type, a macro, and various functions that operate on character arrays.

<time.h>

The time.h header defines four variable types, two macros, and various functions that manipulate dates and times.

The main () function

The main function sounds like a mischievous child deliberately naming a method as the main method to tell others that it is the center of the world. But that’s not the case, and the main() method is really the center of the world.

C programs always start with the main() function, and you can name any other function you like. Normally, the () after main represents some incoming information. Our example above did not pass information because the input in parentheses is void.

Void main(){} int main(int argc, char* argv[]) {}

  • Void main() declares a constructor with undefined parameters
  • Int main(int argc, char* argv[]) {} where argc is a non-negative number representing the number of arguments passed to the program from the running program’s environment. It is a pointer to the first element of the array of argc + 1 Pointers, where the last one is null and the previous one (if any) points to a string representing arguments passed to the program from the host environment. If argv [0] is not a null pointer (or, equivalently, if argc> 0), it points to a string representing the program name, which is null if the program name cannot be used in the host environment.

annotation

In the program, use the / * * / comments said, annotation for program there is no actual use, but it is very useful for programmers, it can help us to understand the program, also can make others understand you write programs, we work in the development, all dislike people who do not write comments, so comments are very important.

The nice thing about C comments is that they can be placed anywhere, even on the same line of code. Longer comments can be multiple lines; we use /**/ for multiple lines and // for single lines only. The following are several representations of comments

// This is a one-line comment

/* Multi-line comments represent a single line */

/* Multiline comments */
Copy the code

The body of the function

After the header file, the main method is the body of the function (comments usually don’t count). The body of the function is the body of the function’s execution, where you write a lot of code.

Variable declarations

In our entry level code, we declare a variable called number, which is of type int. This line of code is called declarations, and declarations are one of the most important features of C. This declaration does two things: it defines a variable named number and defines the specific type of number.

Int is a C keyword that represents a basic C data type. Keywords are used for language definitions. You cannot define a keyword as a variable.

In the example, number is an identifier, which is the name of a variable, function, or other entity.

### Variable assignment

In the sample program, we declared a number variable and assigned it a value of 11. Assignment is one of the basic operations in C. This line of code is simply assigning the value 1 to the variable number. When an int number is executed, the compiler reserves space in computer memory for the variable number, and then stores the value in the previously reserved location when the assignment expression statement is executed. You can assign different values to number, which is why it is called a variable.

The printf function

In the introductory example program, there are three lines of printf(), which are standard C functions. The parentheses are passed from main to printf. There are two kinds of parameters: actual argument and formal parameters. The stuff in the parentheses of the printf function that we mentioned above are arguments.

Return statement

In the getting started example program, the return statement is the last statement. The int in int main(void) indicates that main() should return an integer. C functions that return a value should have a return statement. Programs that do not return a value are also advised to keep the return keyword. This is a good practice or uniform coding style.

A semicolon

In C, the end of each line is used; This indicates the end of a statement. Forgetting or missing a semicolon will prompt the compiler with an error.

The keyword

The following are the keywords in C. There are 32 keywords in C and they are classified according to their functions

Data type keyword

There are 12 key words of data type, respectively

  • char: Declares character variables or functions
  • double: Declares a double precision variable or function
  • float: Declares floating point variables or functions
  • int: Declares an integer variable or function
  • long: Declares long integer variables or functions
  • short: Declares a short integer variable or function
  • signed: Declares a signed type variable or function
  • _Bool: Declares a Boolean type
  • _Complex: Statement plural
  • _Imaginary: Declares an imaginary number
  • unsigned: Declares an unsigned type variable or function
  • void: Declares a function with no return value or argument, and declares no type pointer

Control statement keyword

Control statement loop keywords also have 12, respectively

Looping statements

  • for: for loop, most used
  • do: The body of a loop that is the precondition of a loop statement
  • while: Loop conditions for loop statements
  • break: Jumps out of the current loop
  • continue: ends the current loop and starts the next loop

Conditional statements

  • if: Indicates the judgment condition of a conditional statement
  • else: The negative branch of a conditional statement, used with if
  • goto: Unconditional jump statement

The switch statement

  • switch: Used for switch statements
  • case: Another branch of the switch statement
  • default: Switches other branches in the statement

Return statement

Retur: subroutine return statement (with or without arguments)

Storage type keyword

  • auto: Do not declare automatic variables
  • externDeclare variables in other files (also known as reference variables)
  • register: Declares register variables
  • static: Declares static variables

Other Keywords

  • const: Declares read-only variables
  • sizeof: Calculates the length of the data type
  • typedef: used to alias data types
  • volatile: Indicates that variables can be changed implicitly during program execution

Data in C

After we understand the above introductory example program, we are going to have a comprehensive understanding of the C language program, first of all, we will first understand the C language the most basic variables and constants.

Variables and constants

Variables and constants are the two basic objects that programs deal with.

Some data types are set before the program uses them and do not change throughout the process. These data types are called constant. Another data type that can change during program execution is called variable. For example, int number is a variable and 3.1415 is a constant, because once int number is declared, you can assign any value to it, whereas 3.1415, once declared, does not change.

The variable name

It’s worth mentioning the concept of variable names before we talk about data types. A variable name is a sequence of letters and numbers, and the first character must be a letter. The underscore _ is used as a letter in variable names, and underscores are used for long variable names to improve program readability. Variable names do not usually begin with an underscore. In C, case is case-sensitive, that is, a and A are completely different variables. Normal variable names use lowercase letters, and symbolic constants (defined by #define) all use uppercase letters. When choosing variable names, try to describe the purpose of the variable literally, and avoid variables like ABC that make no sense.

Also note that local variables generally have short variable names and external variables have long names.

The data type

Before we look at data types, we need to look at the concepts of bits, bytes, and words.

Bits, bytes, and words are all descriptions of computer storage units. In the computer world, the smallest unit is a bit. A bit is a 0 or a 1. Usually when your friend asks you whether your computer is XXX bit, there are 32 or 64 bits. So 32-bit or 64-bit means either 32-bit or 64-bit. A byte is a basic unit of storage. A basic unit of storage in a computer is stored in bytes. A byte is equal to 8 bits. A word is a unit of natural storage, and in modern computers, a word is equal to 2 bytes.

There are many data types in C language, and we will introduce them in turn.

The integer

In C language, integers are represented by ints, which can be positive integers, negative integers, or zero. The range of values varies in computers with different bits. On both 32-bit and 64-bit computers, the int range is 2^32 (-2147483648 to +2147483647), and the unsigned type range is 0 to 4294967295.

Integers are stored as binary integers and can be divided into signed and unsigned numbers. Signed numbers can store positive integers, negative integers and zero. Unsigned stores only positive integers and zeros.

You can print values of type int using printf, as shown in the code below.

#include <stdio.h> 
int main(a){
 int a = - 5;
 printf("%d\n",a);
 
 unsigned int b = 6;
 printf("%d\n",b);
 
}
Copy the code

C also provides three accessory keywords to modify integer types, short, long, and unsigned.

  • Short Int Storage space occupied by the type (or short)mayLess than int, suitable for scenarios with small values.
  • Storage space occupied by long int or longmayMore than int, suitable for scenarios with large values.
  • Long long int or long long (added by C99) occupies more storage space than long and is suitable for larger values, at least 64 bits. Like int, long long is also a signed type.
  • Unsigned int or unsigned is only used in non-negative scenarios. The value range of this type is different. For example, a 16-bit unsigned int is in the range 0 to 65535 instead of -32768 to 32767.
  • In the C90 standard, we added unsigned long int or unsigned long and unsigned short int or unsigned short, C99 added unsigned long long int or unsigned long long.
  • To emphasize the intent of using a signed type, precede any signed type with signed. For example, short, short int, signed short, and signed short int all represent a type.

For example, the descriptions above can be declared with the following code:

long int lia;
long la;
long long lla;
short int sib;
short sb;
unsigned int uic;
unsigned uc;
unsigned long uld;
unsigned short usd;
Copy the code

Note that unsigned variables can display negative values when formatted as printf. Why? A value that is not unsigned can’t be negative. That’s because unsigned variables are useful in calculation and have no effect on the output. This is also what CXuan did at the beginning of learning.

Those of us who have studied Java were initially puzzled by these definitions. Why would a C language have so many definitions for data types? C language is really troublesome, I give up learning!

Do not have this idea, if you have this idea, you must be protected by the JVM like a child! I have to correct you from now on, because Java is protected by the JVM and many features are optimized, while C is like a child without an umbrella and has to deal with the world by itself!

Short int, long int, long int, short int, long int, long int

This is a unique style of C data types.

In early computers, both int and short were 16 bits, and long was 32 bits. In later computers, 16 bits were used to store short. 32-bit stores ints and longs. Today, computers commonly use 64-bit cpus, and the long long type was introduced to store 64-bit integers. So, in general, the most common Settings on personal computers today are long long 64 bits, long 32 bits, short 16 bits, int 16 or 32 bits.

The type char

The char type is used to store characters

char a = 'x';
char b = 'y';
Copy the code

Char is referred to as a character type and can only be represented by single quotation marks (“) rather than double quotation marks (“), as opposed to the representation of a string.

Although char represents characters, it actually stores integers, not characters. Computers generally use ASCII for characters. Standard ASCII ranges from 0 to 127, requiring only 7 binary digits. C specifies that a char occupies 1 byte.

The compiler automatically converts a char to an integer when it finds one. Conversely, it converts an Int to an integer if it assigns an English character to an int

#include <stdio.h>

int main(a){
 char a = 'x';
 int b;
 b = 'y';
 
 printf("%d\n%d\n",a,b);
}
Copy the code

The output

120

121

So, int and char are just stored in different ranges. Integers can be 2 bytes, 4 bytes, or 8 bytes, while characters are only 1 byte.

Some C compilers implement char as a signed type, which means that char can be represented in the range of -128 to 127, while some compilers implement char as an unsigned type, in which case char can be represented in the range of 0-255. A signed char represents a signed type, and an unsigned char represents an unsigned type.

Type _Bool

The _Bool type is a new data type added to C99 and used to represent Boolean values. The logical values are true and false. Up until C99, it was all 1’s and 0’s in int. So _Bool is sort of a data type. For zeros and ones, one bit is enough.

Float, double, and long double

Integers are sufficient for most software development projects. However, floating point numbers are often used in finance and mathematics. Floating-point numbers in C have the types float, double, and long double. Floating-point types can represent a wider range of numbers, including decimals. Floating – point numbers can represent decimals and represent a wide range. The representation of floating-point numbers is analogous to scientific and technical law. Here are some examples of scientific notation:

C Specifies that float must represent at least six significant digits and the value ranges from 10^-37 to 10^+37. Typically, the system takes 32 bits to store a floating point number.

Another floating-point type provided by C is double. In general, a double occupies 64 bits rather than 32 bits.

The third type provided by C is long double, which is used to meet higher precision requirements than double. However, C only guarantees that long double is at least the same as double.

Floating-point numbers are declared in a similar way to integers. Here are some floating-point numbers.

#include <stdio.h>

int main(a){

 float aboat = 2100.0;
 double abet = 2.14 e9;
 long double dip = 5.32 e-5;
 
 printf("%f\n", aboat);
 printf("%e\n", abet);
 printf("%Lf\n", dip);
 
}
Copy the code

The printf() function uses %f conversion instructions to print decimal floats and double floats, and exponential floats in %e. To print long doubles, use the %Lf conversion instructions.

With floating-point numbers, you also need to be aware of overflows and underflows.

Overflow refers to a number that is too large to be represented by the current type, as shown below

float toobig = 3.4 e38 * 100.0 f;printf("%e\n",toobig);
Copy the code

The output is INF, which means that the result of toobig exceeds its defined range. C assigns toobig a specific value for infinity, and printf displays either INF or infinity.

Underflow: When a value is so small that it is lower than the smallest possible value for the current type that the computer has to move the mantras to the right, leaving the first bit empty, but at the same time losing the digit above the last significant bit. This situation is called underflow. Take this code for example

float toosmall = 0.1234 e-38/10;printf("%e\n", toosmall);
Copy the code

Complex and imaginary types

Many scientific and engineering calculations require complex and imaginary numbers. The C99 standard supports complex and imaginary numbers. There are three complex types in C: float _Complex, double _Complex, and long double _Complex.

C provides three imaginary numbers: float _Imaginary, double _Imaginary, and long double _Imaginary.

If the complex.h header is included, you can replace _Complex with complex and _Imaginary with imaginary.

Other types of

In addition to the above types, C has other types, such as arrays, Pointers, structures, and unions. Although C doesn’t have string types, C handles strings very well.

constant

There are many situations where constants are needed, such as the number of hours in a day, the size of the maximum buffer, the maximum number of sliding Windows, and so on. These fixed values, called constants, can also be called literals.

Constants are also divided into many kinds, integer constants, floating point constants, character constants, string constants, we will introduce them separately

Integer constants

Integer constants can be expressed in decimal, octal, or hexadecimal. The prefix specifies the base: 0x or 0x represents hexadecimal, 0 represents octal, and the default without a prefix is decimal. Integer constants can also have a suffix, which is a combination of U for an unsigned integer and L for a long integer.

330         /* Valid */315u        /* Valid */0xFeeL      /* Valid */048         /* Illegal: base 8 cannot define 8 */
Copy the code

Floating point constant

Floating-point constants consist of an integer part, a decimal point, a decimal part, and an exponential part. You can express floating-point constants in decimal or exponential form.

When expressed as a decimal, it must contain an integer part, a fractional part, or both. When expressed in exponential form, the decimal point, exponent, or both must be included. The signed exponent is introduced with e or e.

3.14159       /* Valid */314159E-5L    /* Valid */510E          /* Illegal: incomplete index */210f          /* Invalid: no decimal or exponent */
Copy the code

Character constants

A character constant in C is a character enclosed in single quotation marks (that is, apostrophes). Such as’ a ‘, ‘x’, ‘D’, ‘? ‘, ‘$’, etc are character constants. Note that ‘a’ and ‘a’ are different character constants.

In addition to the above form of character constants, C also allows a special form of character constants, which are sequences of characters beginning with a “\”. For example, the ‘\n’ in the printf function, which we’ve already encountered, represents a newline character. This is a control character that cannot be displayed on the screen.

Common special characters beginning with “\” are

The characters listed in the table are called “escape characters”, meaning that the characters following the backslash (\) are converted to something else. For example, the “n” in ‘\n’ does not represent the letter n but acts as a “newline” character.

The last second line in the table represents A character in ASCII (octal number), for example, ‘\101’ represents the ASCII (decimal number) 65 character “A”. ‘\012’ (ASCII decimal code 10) represents a newline.

Note that ‘\0’ or ‘\000’ represents the ASCII 0 control character used in strings.

String constant

String constants are usually represented by “”. A string is a collection of characters. A string contains characters similar to character constants: ordinary characters, escape sequences, and generic characters.

Constants defined

In C, there are two ways to define constants.

  1. use#defineThe preprocessor preprocesses
  2. useconstKeyword for processing

Here is the code for constant definition using the #define preprocessor.

#include <stdio.h>#define LENGTH 5#define WIDTH 10int main(){  int area = LENGTH * WIDTH;  printf("area = %d\n", area); }
Copy the code

Similarly, we can define constants using the const keyword, as shown in the following code

#include <stdio.h>int main(){  const int LENGTH = 10; const int WIDTH = 5;  int area; area = LENGTH * WIDTH;  printf("area = %d\n", area); }
Copy the code

So what’s the difference between these two ways of defining constants?

The compiler handles it differently

Use of the #define preprocessor is done during the preprocessing phase, while const constants are modified at compile time.

Type definition and checking are different

With #define you don’t declare data types, and you don’t do type checking, you just define; Using const requires declaring a specific data type, which is checked at compile time.

Reference: www.zhihu.com/question/19…

I have written four PDFS myself, very hardcore, and the links are as follows: Cxuan has done his heart and soul in four PDFS.

Finally, I would like to recommend my own Github, which has a lot of hardcore articles that will definitely help you.