c - 在 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。
解决方案
该变量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);
}
推荐阅读
- sql - SQL,如何组合记录
- entity-framework-core - 使用 AutoMapper 在 Entity Framework Core 中进行多对一映射
- laravel - Laravel - 如何根据需要验证电话的任一电子邮件
- java - 在java中继承final方法有什么用?如果我们不能覆盖它
- python - 如何转换矩阵并保存到 csv 文件
- javascript - 点击时不出现下拉菜单
- elasticsearch - 具有嵌套属性的 Elasticsearch 搜索
- html - Bootstrap flex 在底部放置文本
- mysql - mysqldump exclude tables 在变量中使用时不排除表
- mysql - MYSQL - 修改查询 - 将参数传递给外部查询而不是子查询