9

我明白什么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

在这种情况下,限制如何工作并由编译器解释?

gcc 版本:5.4.0

4

2 回答 2

10

首先,

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

是相同的

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

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

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

这里的目的restricted是提示编译器对于函数的每次调用,实际参数只能通过指针访问s

于 2018-10-09T15:47:57.053 回答
5

限制类型限定符

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

和例子:

void f(int m, int n, float a[restrict m][n], float b[restrict m][n]);
于 2018-10-09T15:41:10.857 回答