What can human beings make out of the restrict qualifier?

后端 未结 6 1510
盖世英雄少女心
盖世英雄少女心 2021-02-04 05:51

If I got the C99 restrict keyword right, qualifying a pointer with it is a promise made that the data it references won\'t be modified behind the compiler\'s back t

6条回答
  •  不要未来只要你来
    2021-02-04 06:28

    Most of what you know is wrong!

    const does not guarantee that something won't change behind the compiler's back. All it does is stop you from writing to that spot. Something else might still be able to write to that location though, so the compiler canNOT assume it's constant.

    As others have said, the restrict qualifier is about aliasing. In fact, during the first round of C standardization, there was a proposal for a "noalias" keyword. Unfortunately, the proposal was fairly poorly written -- it prompted the one and only time the Dennis Ritchie got involved during that process, when he wrote a letter that said something to the effect that "noalias must go. This is not open to negotiation."

    Needless to say, 'noalias' didn't become part of C. When it came time to try again, the proposal was written enough better that restrict was included in the standard -- and even though noalias would probably have been a more meaningful name for it, that name was so tainted that I doubt anybody even considered trying to use it.

    In any case, the primary intent of restrict is to tell the compiler that there will not be an alias of this item. One reason for this is to allow things to be stored in registers temporarily. For example, consider something like:

    void f(int *a, int *b, int *c) { 
        for (int i=0; i<*a; i++)
            *b += c[i];
    }
    

    The compiler really wants to put i in a register, and load *a into a register, so when it comes time to decide whether to execute another iteration of the loop, it just compares the values in those to registers to each other. Unfortunately, it can't do that -- if somebody who used this function was completely insane, and called it with a==b, every time it writes to *b inside the loop, that new value is also the value of *a -- so it has to read *a from memory at every iteration of the loop, just in case whoever called it was completely insane. Using restrict tells the compiler it can generate code assuming that a and b will always be distinct, so writing to *a will never change *b (or vice versa).

提交回复
热议问题