Confused about limiter C

Firstly, cppreference has the following conditions:

For each execution of a block in which a bounded pointer P is declared (usually each execution of the body of the function in which P is a parameter of the function), if any object accessible through P (directly or indirectly) changes, by any means, all calls to this the object (both reading and writing) in this block must occur through P (directly or indirectly), otherwise the behavior is undefined.

But below this paragraph it says:

Limited pointers can be freely assigned to unlimited pointers; optimization options remain in place while the compiler is able to parse the code:

void f(int n, float * restrict r, float * restrict s) { float * p = r, * q = s; // OK while(n-- > 0) *p++ = *q++; // almost certainly optimized just like *r++ = *s++ } 

In the above example, r [0] is an object accessible via the restricted pointer r, and it is accessed via p, which seems to contradict the first paragraph (access to r [0] should occur exclusively through r)?

Secondly:

Assigning from one restricted pointer to another is undefined behavior, unless you assign a pointer to an object in some external block to a pointer in some internal block (including using the argument with a restricted pointer when calling a function with a limited pointer parameter) or when returning from a function (and otherwise, when it has finished the pointer block).

So, is the following code ok?

 void foo(char* restrict a, size_t s) { for(char* restrict aa = a; aa < a + s; ++aa) // Is aa in an inner block? { *aa = '\0'; } } 
+5
source share
1 answer

The key in Example 1 is: lvalue *p , which is used to access the base array pointed to by r ha [s] its address based on r . In other words, this is indirect access through r . Since *q also has its own s based address, all calls occur, even if indirectly, through the original bounded pointers: there is no UB.

Example 2 is even more trivial. You declare a new restricted pointer based on the source. So there is no UB. But in Example 2, both limited qualifiers do not add exactly any value, because inside the block (function definition foo ) only one pointer is used, since aa based on a .

In Example 1, restrict qualifiers declare to the compiler that the arrays pointed to by r and s do not overlap: access through r (directly or indirectly through p ) must touch the array pointed to by s .

+2
source

Source: https://habr.com/ru/post/1265426/


All Articles