首页 > 解决方案 > 在 c 中转换一个 volatile 变量后,该变量仍然是 volatile 吗?

问题描述

假设我有一个静态全局变量 a,它在 init() 期间的函数调用中被强制转换为 int。在 init() 之后,在函数 my_function_2 中使用时仍然是 volatile 吗

static volatile int a;

init(void)
{
  my_function_1((int)a);
}

my_function_2(void)
{
/* After init(), is a still volatile? */
}

是否需要在 my_function_2() 中重新认定为 volatile?我用的是c99。

标签: cc99volatile

解决方案


该变量a在其整个生命周期内都是易变的。volatile如果您将其转换为某种不同的类型并将其分配给一个新变量,那么除非您这样指定,否则这个新变量将不会存在。

volatile意味着编译器不依赖先前已知的值并且不应该应用适当的优化,因此如果您将其丢弃并仍然引用它,那么它就是未定义的行为。

在这里您不需要将 b 声明为 volatile

volatile int a;

void func(int b)
{
     // This doesn't need to be volatile as it will never be changed from the outside, since it was passed by value.
     printf("%d\n", b);
}

init(void)
{
    // Access a and pass the value to func
    // This is fine, because volatile applies only to access of 'a'.
    func(a);
}

另一个例子:

void func(volatile int *p)
{
     // 'p' needs to be volatile as it will reference 'a' which is volatile
     printf("%d\n", *p);
}

init(void)
{
    func(&a);
}

推荐阅读