Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the core point of C language programming?

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the core points of C language programming". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "what are the core points of C language programming"?

C simplified grammar set and standard library allow us to focus on the really important things such as design, rather than getting lost in the ocean of grammar, which is especially important for beginners. Although C has the shortcomings of lack of abstraction, but I prefer its ingenuity, only need to spend a small amount of time to study every knowledge point, look at any C source code, there will be no grammatical obstacles, we need to establish enough knowledge consensus, less is more, less is better.

I have taught six people programming, HTML, JAVA and C++. Recently, I was teaching my child programming, he is only ten years old, many people suggested that I choose Python, but I finally chose C, because C is simple and powerful, and now it seems to be a good choice.

Types

C is a strongly typed language with build-in data types such as short, long, int, char, float, double and so on. Type is the core concept throughout the whole curriculum of c language.

Struct, union and enum belong to the construction type of c, which is used to customize the type and extend the type system.

Variable

The variable is used to hold the data, the data is the object of operation, and the modification of the variable means that it can be modified at run time.

The variable is determined by the type name + variable name. Defining the variable requires allocating memory for the variable, which can be initialized while defining the variable.

Int i; float F1 = 0.5, f2 = 0.8

Constant

Const int i = 100; const char* p = "hello world"

If it is constant and immutable in operation, the compilation time can be determined.

Array

It is obviously not enough to have simple variables, we need an array, which simulates multiple elements of the same type in reality, these objects are closely adjacent, and each element can be accessed through the array name + position index.

Two-dimensional, three-dimensional and high-latitude arrays are linear in nature, and two-dimensional arrays give people a sense of plane by simulating rows and rows, but they are actually stored in the way of continuous memory.

The array is static, and the length of the array is confirmed when it is defined, and it cannot be scaled in operation, so sometimes we have to allocate more space to cope with the expansion. Array elements are wherever they are, no matter how much or less they are used. Sometimes we use an int n to define the number of elements that are actually used in the array.

Function

The function encapsulates the behavior, which is the smallest unit of modularization, and the function makes logic reuse possible.

C is procedural, the real world can be encapsulated as a process (function), through the process series and choreography to simulate the world.

Programming in C, behavior and data are separate. When the function is called, the caller passes information to the function through parameters, and the function feedback the result to the caller through the return value.

The function had better have no side effects, the modification of global variables or static local variables should be avoided as far as possible, a better way is to pass in parameters, such a function is just a logical box, it meets the requirements of thread safety.

With variables and functions, you can write simple programs.

Control statement

Branches: if, else, else if, switch case,?

Loops: while, do while, for

Break 、 continue 、 goto 、 default

Structural body

Build-in data types are not enough to describe the real world, or the description of build-in types is not direct enough. Structures are used to simulate composite types, which give us the ability to extend the type system. We combine types together to build more complex types, and each component that is combined is called a member variable.

The composition in the body of the structure, and the object passes through the point (.) Operator, and the pointer accesses the member through the arrow (- >).

Pointer

The soul of C is the pointer, the pointer brings elasticity, and the essence of the pointer is the address.

It is necessary to distinguish between the pointer and the object that the pointer points to. Multiple pointer variables can point to the same object, and a pointer cannot point to multiple objects at the same time.

The basic operations related to the pointer include: assigning (modifying the pointer to), dereferencing (accessing the object pointed to by the pointer), taking the address (& variable), and the pointer supports addition and subtraction.

Because the pointer variable should be able to cover the entire memory space, the length of the pointer variable is equal to the word length, 32-bit 4-byte in 32-bit system and 64-bit 8-byte in 64-bit system.

The meaning of the pointer is much richer than the above, the pointer is combined with the array to have the pointer array (int* p [n]) and the array pointer (int (* p) [n]), the pointer is combined with the function to have the function pointer (ret_type (* pf) (param list)), the pointer is combined with const to have the const char*/char* const/const char* const, and the pointer to the pointer (int* * p).

You can define both pointers to build-in data types and pointers to struct. Void* stands for universal pointers, which cannot be dereferenced or perform pointer arithmetic operations.

Function pointer and callback (callback)

After the c source code is compiled and linked, the function is converted to the text section of the executable program file. When the process starts, the contents of the text section will be loaded into the process's code segment, which is part of the c process memory space, so any c function will occupy a piece of memory space. The function pointer points to the function's first assembly instruction in the code segment, and the function call will jump to the first instruction of the function.

Function pointers are often used as callback, and the c language also simulates OOP with structures that contain function pointer members, essentially passing on what the C++ compiler does to the programmer (C++ builds virtual function tables for classes that contain virtual functions and appends pointers to virtual function tables to class objects containing virtual functions).

String

Char* is a special kind of pointer, which is called c-style string, because it always ends with'\ 0', so to identify a string, it is enough to have a char* pointer, the length of the string is implicitly indicated by 0, and most STD C API related to strings start with str, such as strlen/strcpy/strcat/strcmp/strtok.

Memory and memory management

The pointer provides the ability for c language to operate the underlying memory directly. C program distinguishes stack memory from heap memory. Stack memory is a local variable within the function, which dynamically expands as the program executes, so do not return pointers to temporary variables. Stack memory capacity is limited (8pm 16m), so we should avoid creating excessive local variables in the function, and we should guard against recursive stack bursts.

Heap memory, also known as dynamic memory, is managed by a standard library component called dynamic memory Configurator. Glibc's default dynamic memory Configurator is called ptmalloc, and the initial version has performance problems, but later solved the competition with thread proprietary to improve performance. Dynamic memory Configurator is a layer between kernel and application layer. From the perspective of kernel, ptmalloc is an application, and ptmalloc is a system library from the application layer. Malloc and free must be paired, which is the programmer's responsibility, and dynamically allocated memory missing references can lead to memory leaks, pointing to freed blocks of memory commonly known as wild (dangling) pointers.

Pretreatment

From c source file to executable program needs to go through several stages of preprocessing-compiling-assembling-linking. In the preprocessing stage, replacement, elimination and expansion are done, and the preprocessing statement starts with #.

Macro definition, # define, macro definition can be used as a line concatenation, # to generate strings, # # to concatenate, macro definition should be careful to add () to avoid operator priority interference, you can use do while (0) to define as a separate statement, # undef is the anti-operation of define.

# if # ifdef # ifndef # else # elif # endif is used for conditional compilation. In order to avoid repeated header files, # ifndef # define # endif is often used.

# include is used to include header files; # pragma is used to control behavior; and # error is used to output error messages at compile time.

Standard predefined macros such as _ _ FILE__, _ _ LINE__, _ DATE_, _ TIME_, _ STDC_ can be used for some debug purposes.

# typedef is used to define type aliases. For example, typedef int money_t;money_t is more meaningful than int.

Typedef can also be used to alias structures, sometimes like this:

Typedef struct {int a; int b;} xyz_t

In this way, you can make fewer keystrokes when defining structural body variables.

Typedef can also be used to redefine function pointer types, such as typedef void (* PF) (int a, int b); PF is a function pointer type, not a function pointer variable.

Enumerate

Enumerations can increase the readability and maintainability of the code. Enumerations are essentially int, but for more meaning, put several int values with limited values together, such as defining gender: enum sex {male = 1, female}

You can assign a value when you define it, such as male=1, which is incremented by 1 in turn, and starts at 0 if it is not assigned.

Complex (union)

The difference between a structure and a consortium (common body) is that the members of the structure occupy different memory and have no influence on each other, while all the members of the common body occupy the same section of memory, and modifying one member will affect all the other members.

Union u_data {int n; char ch; double f;}

In fact, in essence, a consortium is a variety of interpretations of a piece of memory, the size according to the largest.

Bit domain (bitfield)

Struct SNField {unsigned char seq:7; / / frame sequnce unsigned char startbit:1; / / indicate if it's starting frame 1 for yes. }

Save space, in the low-level coding, or write programs to deal with the network, etc., note that this syntax feature is related to the machine architecture.

Bit operation

Bit and &

Bit or |

The position is reversed ~

Bit XOR ^

Displacement >

Static 、 extern 、 register 、 volatile 、 sizeof

Static modifies the global function to indicate that it is available within the module (compilation unit), and there is no need to export global symbols.

Static modifies local variables, meaning that beyond the life cycle of a function call, it is not stored on the stack and will only be initialized once.

Extern declares external variables.

Register, register variables, suggest the compiler to put variables in registers.

Volatile, tell the compiler not to do optimization, read from memory every time, not do register optimization.

Sizeof size, can act on variables, types, expressions

Variable parameter

Void simple_printf (const char* fmt,...) Va_list 、 va_start 、 va_arg 、 va_end

The advanced sense of C

Generics: linux kernel linked list, through offset and embedded node, write generic linked list

OOP: by defining a structure with function pointer member variables, the upper function pointer is set for the structure object to simulate runtime binding to achieve a feeling similar to OOP polymorphism.

GNU C extension

GNU C extension is not standard C, it is recommended to write C code in a way that conforms to standard C, but if you read linux kernel code, you will find that there are a lot of interesting syntax that you don't understand. It comes from GNU C extension, and it does bring some convenience.

For example, structure members can be initialized out of the defined order:

Struct test_t {int a; int b;}; struct test_t T1 = {.b = 1, .a = 2}

For example, you can initialize an array by specifying an index:

Int a [5] = {[2] 5, [4] 9}

Or int a [5] = {[2] = 4, [4] = 9}

Equivalent to int a [5] = {0,0,4,0,9}

Or int a [100] = {[0... 9] = 1, [10... 98] = 2,3}

For example, a 0-length array

Struct foo {int i; char a [0];}

For example, use variables as the length of the array

Void f (int n) {char a [n];...}

For example, case range, case 'A'... 'Z' case 1... 10

Such as expression extension ({.}), such as ternary operator extension.

Thank you for your reading. The above is the content of "what are the core points of C language programming?" after the study of this article, I believe you have a deeper understanding of what the core points of C language programming are. Specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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: 0

*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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report