我正在浏览 Wikipedia/Restrict , 并发现
The compiler can e.g. rearrange the code, first loading all memory locations, then performing the operations before committing the results back to memory.
后来,我注意到
void updatePtrs(long int *restrict ptrA, long int *ptrB, long int *val)
{
*ptrA += *val;
*ptrB += *val;
}
和
void updatePtrs(long int *restrict ptrA, long int *ptrB, long int *val)
{
*ptrB += *val;
*ptrA += *val;
}
不要使用 -Ofast
生成相同的程序集。这适用于 GCC 和 Clang。
为什么他们有不同的程序集?这是意料之中的事吗?
最佳答案
ptrB
和 val
都不是restrict
,所以 ptrB
和 val
可以指向相同的 long
。当他们这样做时,*ptrA += *val;
和 *ptrB += *val;
的顺序很重要。
即使所有指针都是restrict
,也只允许编译器重新排列操作,而不是强制要求。
关于更改 "Restrict"ed 指针的顺序会产生不同的程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50745990/