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
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
.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With