How can I restrict array parameters in C (without making them pointers)? [duplicate]

  Kiến thức lập trình

Motivation

Array parameters can alias each other, and the compiler must carefully allow for this possibility. Thus, for example: GodBolt

int foo(int a[10], int b[10]) {
    a[0] += b[0];
    return a[0] + b[0];
}

int bar(int *a, int *b) {
    a[0] += b[0];
    return a[0] + b[0];
}

int baz(int * __restrict a, int * __restrict b) {
    a[0] += b[0];
    return a[0] + b[0];
}

the compiled code for foo() must be like that of bar(), not like that of baz().

Question

I want to use array parameters to my function – possibly even multi-dimension arrays (not arrays-of-pointers; the kind you declare with a pair of square brackets and decay to simple one-level pointers to the first element). And I also want the compiler to assume there is no aliasing, i.e. I want to mark my array parameters as restrict‘ed.

How can I do this in C? And if I can’t – why is that?

8

You can put qualifiers in the leftmost array declaration of a parameter (i.e. the part that gets converted to a pointer):

int foo(int a[restrict 10], int b[restrict 10]) {
    a[0] += b[0];
    return a[0] + b[0];
}

2

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT