What is the function of volatile keyword in C language?
The role of the volatile keyword in C language: to remind the compiler that the variable defined later may change at any time, so every time the compiled program needs to store or read this variable, tell the compiler about it If this variable is not optimized, the data will be read directly from the variable memory address, thus providing stable access to the special address to avoid errors.
Tutorial recommendation: "c language tutorial video"
1. Preface
1. Introduction to compiler optimization:
Since the memory access speed is far less than the CPU processing speed, in order to improve the overall performance of the machine, in the hardware Introduce hardware cache Cache to accelerate access to memory. In addition, the execution of instructions in modern CPUs does not necessarily follow a strict order. Instructions without correlation can be executed out of order to make full use of the CPU's instruction pipeline and improve execution speed. The above are hardware-level optimizations. Let’s look at software-level optimization: one is optimized by the programmer when writing code, and the other is optimized by the compiler. Commonly used methods for compiler optimization include: caching memory variables into registers; adjusting the order of instructions to make full use of the CPU instruction pipeline. A common method is to reorder read and write instructions. When optimizing conventional memory, these optimizations are transparent and very efficient. The solution to problems caused by compiler optimization or hardware reordering is to place a memory barrier between operations that must be executed in a specific order from the perspective of the hardware (or other processor). Linux provides a macro solution. Compiler execution order issues.
void Barrier(void)
This function notifies the compiler to insert a memory barrier, but it is invalid for hardware. The compiled code will store all modified values in the current CPU register into memory. These are needed When the data is needed, read it from the memory again.
2. Volatile is always related to optimization. The compiler has a technology called data flow analysis, which analyzes where the variables in the program are assigned, where they are used, and where they fail, and the analysis results It can be used for constant merging, constant propagation and other optimizations, and can further eliminate some code. But sometimes these optimizations are not required by the program. In this case, you can use the volatile keyword to prohibit these optimizations.
2. Detailed explanation of volatile:
##1. Principle and function:
Volatile's original meaning is "volatile", because accessing registers is much faster than accessing memory units, so compilers generally perform optimizations to reduce access to memory, but dirty data may be read.
When required to use volatile to declare a variable value, the system always re-reads the data from the memory where it is located, even if the previous instruction just read it from there Data has been read.
To be precise, when encountering a variable declared by this keyword, the compiler will no longer optimize the code that accesses the variable (data will be read directly from the variable memory address ), thus providing stable access to special addresses; if volatile is not used, the compiler will optimize the declared statement. (To put it simply: the volatile keyword affects the result of compiler compilation. A variable declared with volatile means that the variable may change at any time. Do not perform compilation optimization on operations related to the variable to avoid errors)
2. Look at two examples:
1>Tell the compiler not to do any optimization
For example, if you want to send two instructions to a certain address:
int *ip =...; //设备地址 *ip = 1; //第一个指令 *ip = 2; //第二个指令
The above program compiler may be optimized:
int *ip = ...; *ip = 2;
As a result, the first instruction is lost. If you use volatile, the compiler is not allowed to do any optimization, thereby ensuring the original intention of the program:
volatile int *ip = ...; *ip = 1; *ip = 2;
Even if you want the compiler to do optimization, it will not pay twice. Value statements are reduced to one. It can only do other optimizations.
2>Variables defined with volatile will be changed outside the program and must be read from memory each time , and cannot reuse the backup placed in the cache or register.
For example:
volatile char a; a=0; while(!a){ //do some things; } doother();
如果没有 volatiledoother()不会被执行
3.下面是使用volatile变量的几个场景:
1>中断服务程序中修改的供其它程序检测的变量需要加volatile;
例如:
static int i=0; int main(void) { ... while (1){ if (i) dosomething(); } } /* Interrupt service routine. */ void ISR_2(void) { i=1; }
程序的本意是希望ISR_2中断产生时,在main函数中调用dosomething函数,但是,由于编译器判断在main函数里面没有修改过i,因此可能只执行一次对从i到某寄存器的读操作,然后每次if判断都只使用这个寄存器里面的“i副本”,导致dosomething永远也不会被调用。如果将变量加上volatile修饰,则编译器保证对此变量的读写操作都不会被优化(肯定执行)。此例中i也应该如此说明。
2>多任务环境下各任务间共享的标志应该加volatile
3>存储器映射的硬件寄存器通常也要加voliate,因为每次对它的读写都可能有不同意义。
例如:
假设要对一个设备进行初始化,此设备的某一个寄存器为0xff800000。
int *output = (unsigned int *)0xff800000;//定义一个IO端口; int init(void) { int i; for(i=0;i< 10;i++){ *output = i; } }
经过编译器优化后,编译器认为前面循环半天都是废话,对最后的结果毫无影响,因为最终只是将output这个指针赋值为9,所以编译器最后给你编译编译的代码结果相当于:
int init(void) { *output = 9; }
如果你对此外部设备进行初始化的过程是必须是像上面代码一样顺序的对其赋值,显然优化过程并不能达到目的。反之如果你不是对此端口反复写操作,而是反复读操作,其结果是一样的,编译器在优化后,也许你的代码对此地址的读操作只做了一次。然而从代码角度看是没有任何问题的。这时候就该使用volatile通知编译器这个变量是一个不稳定的,在遇到此变量时候不要优化。
例如:
volatile int *output=(volatile unsigned int *)0xff800000;//定义一个I/O端口
另外,以上这几种情况经常还要同时考虑数据的完整性(相互关联的几个标志读了一半被打断了重写),在1中可以通过关中断来实现,2中禁止任务调度,3中则只能依靠硬件的良好设计。
4.几个问题
1)一个参数既可以是const还可以是volatile吗?
可以的,例如只读的状态寄存器。它是volatile因为它可能被意想不到地改变。它是const因为程序不应该试图去修改它。
2) 一个指针可以是volatile 吗?
可以,当一个中服务子程序修该一个指向一个buffer的指针时。
5.volatile的本质:
1> 编译器的优化
在本次线程内, 当读取一个变量时,为提高存取速度,编译器优化时有时会先把变量读取到一个寄存器中;以后,再取变量值时,就直接从寄存器中取值;当变量值在本线程里改变时,会同时把变量的新值copy到该寄存器中,以便保持一致。
当变量在因别的线程等而改变了值,该寄存器的值不会相应改变,从而造成应用程序读取的值和实际的变量值不一致。
当该寄存器在因别的线程等而改变了值,原变量的值不会改变,从而造成应用程序读取的值和实际的变量值不一致。
2>volatile应该解释为“直接存取原始内存地址”比较合适,“易变的”这种解释简直有点误导人。
6.下面的函数有什么错误:
int square(volatile int *ptr) { return *ptr * *ptr; }
该程序的目的是用来返指针*ptr指向值的平方,但是,由于*ptr指向一个volatile型参数,编译器将产生类似下面的代码:
int square(volatile int *ptr) { int a,b; a = *ptr; b = *ptr; return a * b; }
由于*ptr的值可能被意想不到地该变,因此a和b可能是不同的。结果,这段代码可能返不是你所期望的平方值!正确的代码如下:
long square(volatile int *ptr) { int a; a = *ptr; return a * a; }
注意:频繁地使用volatile很可能会增加代码尺寸和降低性能,因此要合理的使用volatile。
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of What is the function of volatile keyword in C language?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i

C Language Data Structure: Overview of the Key Role of Data Structure in Artificial Intelligence In the field of artificial intelligence, data structures are crucial to processing large amounts of data. Data structures provide an effective way to organize and manage data, optimize algorithms and improve program efficiency. Common data structures Commonly used data structures in C language include: arrays: a set of consecutively stored data items with the same type. Structure: A data type that organizes different types of data together and gives them a name. Linked List: A linear data structure in which data items are connected together by pointers. Stack: Data structure that follows the last-in first-out (LIFO) principle. Queue: Data structure that follows the first-in first-out (FIFO) principle. Practical case: Adjacent table in graph theory is artificial intelligence

Troubleshooting Tips for C language processing files When processing files in C language, you may encounter various problems. The following are common problems and corresponding solutions: Problem 1: Cannot open the file code: FILE*fp=fopen("myfile.txt","r");if(fp==NULL){//File opening failed} Reason: File path error File does not exist without file read permission Solution: Check the file path to ensure that the file has check file permission problem 2: File reading failed code: charbuffer[100];size_tread_bytes=fread(buffer,1,siz

C language functions are reusable code blocks, receive parameters for processing, and return results. It is similar to the Swiss Army Knife, powerful and requires careful use. Functions include elements such as defining formats, parameters, return values, and function bodies. Advanced usage includes function pointers, recursive functions, and callback functions. Common errors are type mismatch and forgetting to declare prototypes. Debugging skills include printing variables and using a debugger. Performance optimization uses inline functions. Function design should follow the principle of single responsibility. Proficiency in C language functions can significantly improve programming efficiency and code quality.
