What is the purpose of restrict as size of array?

  • A+
Category:Languages

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: