将易失性分配给非易失性语义和C标准 [英] Assign volatile to non-volatile sematics and the C standard

查看:52
本文介绍了将易失性分配给非易失性语义和C标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

volatile int vfoo = 0;
void func()
{
    int bar;
    do
    {
        bar = vfoo;  // L.7
    }while(bar!=1);
    return;
}

此代码忙于等待变量变为 1 .如果第一次将 vfoo 设置为 1 ,我会卡在里面吗.

This code busy-waits for the variable to turn to 1. If on first pass vfoo is not set to 1, will I get stuck inside.

此代码编译时没有警告.标准对此有何说法?

This code compiles without warning. What does the standard say about this?

  • vfoo 被声明为 volatile .因此,应优化对该变量的读取.
  • 但是,酒吧不合格 易失性.是否允许编译器优化对此 bar 的写入?.IE.编译器将对 vfoo 进行读取访问,并允许丢弃此值,而不将其分配给 bar (在L.7).
  • 如果是在特殊情况下标准有话要说,您能否包括该条款并解释标准的律师谈话?
  • vfoo is declared as volatile. Therefore, read to this variable should not be optimized.
  • However, bar is not volatile qualified. Is the compiler allowed to optimize the write to this bar? .i.e. the compiler would do a read access to vfoo, and is allowed to discard this value and not assign it to bar (at L.7).
  • If this is a special case where the standard has something to say, can you please include the clause and interpret the standard's lawyer talk?

推荐答案

标准对此要说的内容包括:

What the standard has to say about this includes:

5.1.2.3程序执行

5.1.2.3 Program execution

¶2访问易失性对象,修改对象,修改文件或调用执行任何这些操作的函数都是副作用,它们都是执行环境状态的变化.对表达式的评估通常包括值计算和副作用的启动.左值表达式的值计算包括确定指定对象的身份.

¶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在抽象机中,所有表达式均按语义指定的方式求值.如果实际实现可以推断出未使用其值并且没有产生所需的副作用(包括由调用函数或访问易失性对象引起的副作用),则无需对表达式的一部分进行求值.

¶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).

¶6对符合的实现的最低要求是:

¶6 The least requirements on a conforming implementation are:

  • 严格根据抽象机的规则评估对易失对象的访问.
  • ...

尤其是从¶2得出的结论应该是,访问易失性对象与调用 printf 之类的东西没有什么不同-它不能被忽略,因为它有副作用.想象一下您的程序,其中 bar = vfoo; 替换为 bar = printf("hello \ n");

The takeaway from ¶2 in particular should be that accessing a volatile object is no different from something like calling printf - it can't be elided because it has a side effect. Imagine your program with bar = vfoo; replaced by bar = printf("hello\n");

这篇关于将易失性分配给非易失性语义和C标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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