挥发function

简介 :关键字volatile在应用于C和C ++中的函数声明时会做什么?

细节

我看到可以编译一个标记为volatile的函数。 但是,我不确定这会阻止什么编译器优化(如果有的话)。 例如,我创建了以下测试用例:

 volatile int foo() { return 1; } int main() { int total = 0; int i = 0; for(i = 0; i < 100; i++) { total += foo(); } return total; } 

当我使用clang -emit-llvm -S -O3 test.c编译时(gcc也可以工作,但我认为llvm IR更具可读性)我得到:

 target triple = "x86_64-unknown-linux-gnu" define i32 @foo() #0 { ret i32 1 } define i32 @main() #0 { ret i32 100 } 

很明显,编译器能够优化掉对函数foo()的调用,以便main()返回一个常量,即使foo()被标记为volatile 。 所以我的问题是,在限制编译器优化方面,当应用于函数声明时, volatile是否会做任何事情。

(注意我对这个问题的兴趣主要是了解volatile作用而不是解决任何特定问题。)

(此外,我将此问题标记为C和C ++,不是因为我认为它们是相同的语言,而是因为我有兴趣知道在这两种语言中volatile是否存在差异)。

在您的代码中, volatile关键字不适用于该函数,但是对于返回类型,它相当于:

 typedef volatile int Type; Type foo(); 

现在,在C ++中,您可以使成员函数volatile ,与const限定符相同,行为相同:

 struct test { void vfunction() volatile; }; 

基本上你不能在类型的volatile(const)实例上调用非易失性(alterantively non-const)函数:

 struct test { void vfunction() volatile; void function(); }; volatile test t; t.vfunction(); // ok t.function(); // error 

foo()不易变。

它是一个返回volatile int的函数。

这是合法的。 但对于返回的int很奇怪。

另一方面,成员函数可以是volatile ,因为它们可以是const – 它们都描述了它所指向的对象。