如果我有以下声明:
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/