【发布时间】:2015-04-28 05:00:08
【问题描述】:
我正在使用符合 C99 标准的 mingw32-gcc。我粘贴了下面的代码,并在一篇关于 restrict 关键字 - http://wr.informatik.uni-hamburg.de/_media/teaching/wintersemester_2013_2014/epc-1314-fasselt-c-keywords-report.pdf 的文章中进行了一些编辑。根据作者的说法,"Result One" 和"Result Two" 应该是不同的,但是当我运行它时,它们是相同的。我没有收到任何编译器警告。有没有我遗漏的设置?
#include <stdio.h>
void update(int* a, int* b, int* c)
{
*a += *c;
*b += *c;
}
void update_restrict(int* a, int* b, int* restrict c)
{
printf("*c = %d\n",*c);
*a += *c;
printf("\n*c = %d - ",*c);
printf("shouldn't this have stayed the same?\n\n");
*b += *c;
}
int main()
{
int a = 1, b = 2;
update(&a, &b, &a);
printf("Result One: a, b = %d, %d\n", a, b);
a = 1; b = 2; // reset values
update_restrict(&a, &b, &a);
printf("Result Two: a, b = %d, %d\n", a, b);
getchar();
return 0;
}
【问题讨论】:
-
restrict不必影响您的输出。只有编译器才能进行可能的优化。结果可能相同,也可能不同。 -
我认为在
update_restrict中 *c 的值在 *a 更改后会保持不变,因为它只加载一次。我看不出这对结果有何影响。 -
你没有说你是如何编译的(编译器版本、命令行标志等)。 gcc 对restrict 含义的解释很弱:标记单个变量restrict 对gcc 基本上没有用,它只假设both 限制的2 个变量没有别名。此外,编译器可以很好地内联函数,这可能会使问题消失。在 update_restrict 上使用
__attribute__((noinline,noclone))来避免这种情况。 -
我使用的是 4.8.1 版本,带有 -std=c99。
-
我添加了
__attribute__((noinline,noclone)),但仍然得到相同的结果。我将尝试一些具有多个限制的示例。
标签: c gcc restrict restrict-qualifier