在C语言中volatile关键字? [英] the volatile keyword in C language?

查看:162
本文介绍了在C语言中volatile关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在C语言中挥发的问题。

I have a question about volatile in C language.

我读了一些教程,但仍然想不通,有的说volatile会通知涉及该变量操作不应该在某些方面进行优化的编译器优化。
这意味着任何时候一个变量的值是寄存器的变化,然后该值应该影响内存。

I read some tutorial but still can not figure out, some says the volatile tells the complier optimizer that operations involving this variable should not be optimized in certain ways. this means anytime the value of a variable is change in register, then the value should affect the memory.

和也有些说,挥发性意味着该值可以通过这种方式code外修改。

And also some say that volatile mean that the value can be changed by means outside this code.

我不明白的第二个说法,所以volatile变量可以通过此方式code以外的改变?怎么样?而且这两个既说对吧?

I can not understand the second saying, so the volatile variable can be changed by means outside of this code? how? and are these two says both right?

推荐答案

的值可以通过这种方式code之外被改变的说法基本上意味着其他程序或硬件可以更新变量。这是完全可能的。的这种思想的一种方式是通过与这个概念是多个程序之间共享的文件。一个文件可以同时打开,写,读很多程序。当你从文件中读取你要确保你正在阅读的最新更新,而不是最古老的。

The statement "the value can be changed by means outside of this code" basically means that another program or hardware can update that variable. This is totally possible. One way of thinking of this is by relating this concept to a file that is shared among multiple programs. A file can be opened, written, and read by many programs at once. When you read from a file you want to make sure that you are reading the latest update and not the oldest.

回过头来看看这个volatile关键字,变量前放置挥发,实际上,做同样的事情。它确保你所读出的变量不是基于编译器的优化,或者你的程序有变量的旧副本。此外,volatile关键字确保变量是从每次访问存储器中取出。因此,对于volatile关键字这两个语句是正确的。

Going back to the volatile keyword, placing volatile before a variable, in effect, does the same thing. It makes sure that what you are reading out of the variable isn't based on the compiler's optimization or an old copy of the variable that your program had. Moreover, the volatile keyword ensures that the variable is fetched from memory on every access. Therefore, both of those statements are correct regarding the volatile keyword.

这篇关于在C语言中volatile关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆