【问题标题】:restrict-Keyword not working?限制关键字不起作用?
【发布时间】: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


【解决方案1】:

About the usage of restrict

来自 wikipedia.org:

如果未遵循意向声明并且对象是 由独立指针访问,这将导致未定义 行为。

update_restrict(&amp;a, &amp;b, &amp;a); 这一行导致未定义的行为

结果可能相同,也可能不同。

【讨论】:

    猜你喜欢
    • 2017-06-25
    • 2012-07-03
    • 2014-10-24
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多