Dpp*_*Dpp 6 c compiler-construction compiler-theory compiler-optimization visual-c++
我有一个关于编译器可能做的优化的问题.
下面的代码将说明一下(这是一个例子):
typedef struct test
{
short i;
} s_test;
int function1(char *bin)
{
s_test foo;
lock(gmutex);
foo.i = *(int*)bin * 8;
unlock(gmutex);
sleep(5);
//
// Here anything can happen to *bin in another thread
// an inline example here could be: *(volatile int *)bin = 42;
//
int b = foo.i + sizeof(char*);
return (b > 1000);
}
Run Code Online (Sandbox Code Playgroud)
编译器是否可以替换最后一行
return ((*(int*)bin * 8 + sizeof(char*)) > 1000);
Run Code Online (Sandbox Code Playgroud)
似乎没有使用-O2或-O3与gcc 4.4的情况,但是其他编译器和其他编译标志可能是这种情况吗?
我不认为编译器会做这样的优化.
unlock(gmutex)
Run Code Online (Sandbox Code Playgroud)
这是函数,编译器不能假设bin指向的值在解锁函数中是否会被更改.
例如,bin可能来自地球仪.因此bin的优化不能跨越函数调用.