C99 'restrict' 关键字的实际用法? [英] Realistic usage of the C99 'restrict' keyword?

查看:29
本文介绍了C99 'restrict' 关键字的实际用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了一些文档和问题/答案,看到有人提到了.我读了一个简短的描述,说明它基本上是程序员的一个承诺,即不会使用指针指向其他地方.

I was browsing through some documentation and questions/answers and saw it mentioned. I read a brief description, stating that it would be basically a promise from the programmer that the pointer won't be used to point somewhere else.

谁能提供一些实际案例来证明它的实际使用价值?

Can anyone offer some realistic cases where its worth actually using this?

推荐答案

restrict 表示指针是唯一访问底层对象的东西.它消除了指针别名的可能性,使编译器能够进行更好的优化.

restrict says that the pointer is the only thing that accesses the underlying object. It eliminates the potential for pointer aliasing, enabling better optimization by the compiler.

例如,假设我有一台带有特殊指令的机器,可以将内存中的数字向量相乘,我有以下代码:

For instance, suppose I have a machine with specialized instructions that can multiply vectors of numbers in memory, and I have the following code:

void MultiplyArrays(int* dest, int* src1, int* src2, int n)
{
    for(int i = 0; i < n; i++)
    {
        dest[i] = src1[i]*src2[i];
    }
}

如果destsrc1src2 重叠,编译器需要正确处理,这意味着它必须一次进行一次乘法,从开始到结束.通过restrict,编译器可以自由地使用向量指令优化这段代码.

The compiler needs to properly handle if dest, src1, and src2 overlap, meaning it must do one multiplication at a time, from start to the end. By having restrict, the compiler is free to optimize this code by using the vector instructions.

维基百科有一个关于 restrict 的条目,还有一个例子,这里.

Wikipedia has an entry on restrict, with another example, here.

这篇关于C99 'restrict' 关键字的实际用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆