【问题标题】:What is the purpose of restrict as size of array?限制为数组大小的目的是什么?
【发布时间】:2018-10-09 15:25:41
【问题描述】:

我了解restrict 的含义,但我对这种用法/语法有点困惑:

#include <stdio.h>

char* foo(char s[restrict], int n)
{
        printf("%s %d\n", s, n);
        return NULL;
}

int main(void)
{
        char *str = "hello foo";
        foo(str, 1);

        return 0;
}

gcc main.c -Wall -Wextra -Werror -pedantic编译成功

在这种情况下,restrict 是如何工作并由编译器解释的?

gcc 版本:5.4.0

【问题讨论】:

标签: c gcc restrict-qualifier


【解决方案1】:

首先,

  char* foo(char s[restrict], int n) { ....

相同
  char* foo(char * restrict s, int n) {...

根据C11,第 6.7.6.2 章允许使用语法

[...] 可选类型限定符和关键字static 只能出现在 声明具有数组类型的函数参数,然后仅在最外层 数组类型推导。

在此处使用restricted 的目的是提示编译器对于函数的每次调用,实际参数通过指针s 访问。

【讨论】:

  • 这不仅仅是一个提示。它是一个承诺,是函数、编译器和调用代码之间的契约。破坏它会导致 UB。
【解决方案2】:

来自restrict type qualifier

在函数声明中,关键字restrict 可能出现在方括号内,用于声明函数参数的数组类型。它限定了数组类型转换为的指针类型:

还有例子:

void f(int m, int n, float a[restrict m][n], float b[restrict m][n]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2018-03-06
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2022-07-21
    相关资源
    最近更新 更多