对C限制符号感到困惑

首先,cppreference有关于restrict的以下内容:

During each execution of a block in which a restricted pointer P is declared (typically each execution of a function body in which P is a function parameter), if some object that is accessible through P (directly or indirectly) is modified, by any means, then all accesses to that object (both reads and writes) in that block must occur through P (directly or indirectly), otherwise the behavior is undefined.

但是在这一段下面它说:

Restricted pointers can be assigned to unrestricted pointers freely, the optimization opportunities remain in place as long as the compiler is able to analyze 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++
}

在上面,r [0]是一个可以通过受限制的指针r访问的对象,它通过p访问,这似乎与第一段相矛盾(访问r [0]必须单独通过r)?

第二:

Assignment from one restricted pointer to another is undefined behavior, except when assigning from a pointer to an object in some outer block to a pointer in some inner block (including using a restricted pointer argument when calling a function with a restricted pointer parameter) or when returning from a function (and otherwise when the block of the from-pointer ended).

那么,以下代码是否正常?

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';
    }
}
最佳答案
示例1中的关键是用于访问r指向的底层数组的lvalue * p的地址基于r.换句话说,它是通过r的间接访问.由于* q也有基于s的地址,所有访问都发生,即使间接通过原始的限制指针:这里没有UB.

例2更加微不足道.您基于原始指针声明一个新的受限指针.所以也没有UB.但是在示例2中,两个限制限定符都没有添加任何值,因为在块内(foo函数定义)只使用一个单指针,因为aa基于a.

在示例1中,限制限定符向编译器声明r和s指向的数组不重叠:通过r(直接或间接通过p)访问不应该触及s指向的数组.

转载注明原文:对C限制符号感到困惑 - 代码日志