Granularity of restrict qualifier for overlapping pointers, types

六月ゝ 毕业季﹏ 提交于 2019-12-04 14:57:22

The relevant text of the standard is 6.7.3.1 Formal definition of restrict:

1 Let D be a declaration of an ordinary identifier that provides a means of designating an object P as a restrict-qualified pointer to type T.

2 If D appears inside a block and does not have storage class extern, let B denote the block. If D appears in the list of parameter declarations of a function definition, let B denote the associated block. Otherwise, let B denote the block of main (or the block of whatever function is called at program startup in a freestanding environment).

3 In what follows, a pointer expression E is said to be based on object P if (at some sequence point in the execution of B prior to the evaluation of E) modifying P to point to a copy of the array object into which it formerly pointed would change the value of E.137) Note that ''based'' is defined only for expressions with pointer types.

4 During each execution of B, let L be any lvalue that has &L based on P. If L is used to access the value of the object X that it designates, and X is also modified (by any means), then the following requirements apply: T shall not be const-qualified. Every other lvalue used to access the value of X shall also have its address based on P. Every access that modifies X shall be considered also to modify P, for the purposes of this subclause. If P is assigned the value of a pointer expression E that is based on another restricted pointer object P2, associated with block B2, then either the execution of B2 shall begin before the execution of B, or the execution of B2 shall end prior to the assignment. If these requirements are not met, then the behavior is undefined.

5 Here an execution of B means that portion of the execution of the program that would correspond to the lifetime of an object with scalar type and automatic storage duration associated with B.

Your first example (the interleaved array) is perfectly valid by my reading of the standard.

The second example with the struct is less clear, and depends on whether the use of the -> operator (your wrote . but meant ->) with foo0 (or foo1) means that *foo0 (or foo1) is "used to access the value of the object that it designates". This is not clear to me since the struct is not used as a value; only its members are.

The restrict keyword is strictly advisory to the compiler that the application won't modify the same addresses through another pointer not derived from it, within the type qualified scope.

Nothing actually restricts the application from doing so though. However, it's safe to assume modifying an address that's accessed through a restrict qualified pointer through something other than that restrict qualified pointer will result in undefined behavior (beware dragons).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!