在初始化新指针时使用“restrict”是否真的起作用?

在初始化新指针时使用“restrict”是否真的起作用?,c,pointers,C,Pointers,我一直在阅读关于restrict关键字的文章,我看到的每个例子都在定义函数时使用它 void foo (int *restrict bar, float *restrict baz); 我一直在阅读有关它的文章,想知道这是否是一个有效的东西 intmain() { int*restrict bar=malloc(sizeof(int)); //…使用条形码 返回0; } 我用gcc测试了它,没有收到任何编译器警告,但它真的会做什么吗?编译器是否会发现该指针在其生命周期内不会重叠,也不会被任何

我一直在阅读关于
restrict
关键字的文章,我看到的每个例子都在定义函数时使用它

void foo (int *restrict bar, float *restrict baz);
我一直在阅读有关它的文章,想知道这是否是一个有效的东西

intmain()
{
int*restrict bar=malloc(sizeof(int));
//…使用条形码
返回0;
}

我用gcc测试了它,没有收到任何编译器警告,但它真的会做什么吗?编译器是否会发现该指针在其生命周期内不会重叠,也不会被任何其他指针共享,或者仅在定义函数时才起作用?

主菜单中的受限“栏”告诉编译器数据不会通过任何其他指针引用。根据main的功能,它可能有助于优化“main”。如果
的唯一操作是在功能
foo
中,则无需使其
限制

作为旁注,在Linux/gcc上,“malloc”被标记为
\uuuuuu attribute\uuuuu((\ uuuumalloc\uuuuu))
,它告诉编译器返回的值是restrict指针,这将允许编译器执行所需的优化(如果相关)。见:

马洛克


restrict
在您的示例中没有意义。好吧,这基本上回答了我的问题。在它的位置上,编译器不会意识到,对于int main中的bar的生命周期,它是受限制的。@FiddlingBits我认为这需要解释。我不相信:)。它只有很少的合法用途。
This tells the compiler that a function is malloc-like, i.e., that the pointer P 
returned by the function cannot alias any other pointer valid when the function
returns, and moreover no pointers to valid objects occur in any storage addressed by P.

Using this attribute can improve optimization. Compiler predicts that
a function with the attribute returns non-null in most cases.
Functions like malloc and calloc have this property because they
return a pointer to uninitialized or zeroed-out storage. However,
functions like realloc do not have this property, as they can return a
pointer to storage containing pointers.