What is the purpose of restrict as size of array?
Asked Answered
L

2

10

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

Lakeesha answered 9/10, 2018 at 15:25 Comment(4)
Must be the same as restrict char *s.Bellyache
@FiddlingBits, or, char * restrict s?Opinionated
It's buried in here: en.cppreference.com/w/c/language/function_declarationAnorexia
@SouravGhosh Thank you for the correction. restrict char *s produces a compiler error; char * restrict s does not.Bellyache
O
11

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.

Opinionated answered 9/10, 2018 at 15:47 Comment(1)
It's more than a hint. It's a promise, a contract between the function, the compiler, and calling code. Breaking it results in UB.Yerga
D
6

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]);
Diminution answered 9/10, 2018 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.