Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of restrict as size of array?

I understand what restrict means, but I'm a little bit confused with such usage/syntax:

#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;
}

Successfully compiled with gcc main.c -Wall -Wextra -Werror -pedantic

How is restrict work in this case and interpret by the compiler?

gcc version: 5.4.0

like image 700
Nick S Avatar asked Oct 09 '18 15:10

Nick S


2 Answers

First of all,

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

is the same as

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

The syntax is allowed as per C11, chapter §6.7.6.2

[...] The optional type qualifiers and the keyword static shall appear only in a declaration of a function parameter with an array type, and then only in the outermost array type derivation.

The purpose of having the restricted here is to hint the compiler that for every call of the function, the actual argument is only accessed via pointer s.

like image 110
Sourav Ghosh Avatar answered Nov 09 '22 05:11

Sourav Ghosh


From restrict type qualifier

In a function declaration, the keyword restrict may appear inside the square brackets that are used to declare an array type of a function parameter. It qualifies the pointer type to which the array type is transformed:

And example:

void f(int m, int n, float a[restrict m][n], float b[restrict m][n]);
like image 25
Mike Kinghan Avatar answered Nov 09 '22 06:11

Mike Kinghan