c - volatile value-only 语句会触发 C 中的读访问吗?

标签 c volatile

如果我有以下声明:

extern volatile int SOME_REGISTER;

及以后:

void trigger_read_register()
{
    SOME_REGISTER;
}

调用 trigger_read_register() 会在 SOME_REGISTER 上发出读取请求吗?

最佳答案

根据 C11 规范,访问 volatile 被认为是一种副作用,因此编译器不应优化您示例中的(否则无用的)访问。

所以,答案是肯定的,它应该从内存中读取。

参见 C11 标准(草案)第 5.1.2.3 节第 2 节:

Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object.

此外,4 说:

In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

关于c - volatile value-only 语句会触发 C 中的读访问吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38377981/

相关文章:

C - 线程同步

c++ - gcc: 加载共享库时出错 -> 查找错误的库版本

c - 什么时候需要 CAMLparamX?

c++ - 了解 volatile asm 与 volatile 变量

c++ - 将 volatile C 字符串与 std::cout 一起使用

c++ - 如何在 C++ 中将命令行字符串转换为 hwnd?

c++ - wxDev-C++ - HtmlHelp 未声明

.net - 有没有更简单的方法在 .net 中创建注册表 volatile 子项?

java - 为什么我的两个线程可以通过非 volatile 字段进行协调?

c++ - 指向 volatile 的指针的迭代器特征