Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

c - Is it legal to assign a restricted pointer to another pointer, and use the second pointer to modify the value?

Does the following method respect the "restrict" contract?

void fun(int* restrict foo) {
     int* bar = foo + 32;
     for (int i = 0; i < 32; ++i)
         *bar = 0;
}

My guess is no, but I need some clarification.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it sure respects the contract.

6.7.3 Type qualifiers

8 An object that is accessed through a restrict-qualified pointer has a special association with that pointer. This association, defined in 6.7.3.1 below, requires that all accesses to that object use, directly or indirectly, the value of that particular pointer.135) The intended use of the restrict qualifier (like the register storage class) is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).

In short, at the point foo is defined (the function-call), foo is guaranteed by the programmer to be the only way to refer to the objects (if any) it points to.
All other expressions referring to those object must thus be derived from that pointers value (like bar which is set to foo+32).
Breaking faith is, as always in such cases, duly punished by undefined behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...