在C 编程语言(99 标准之后)中,引入了一个新的关键字,称为restrict 。
输出:
- restrict 关键字主要用于指针声明中,作为指针的类型限定符。
- 它没有添加任何新功能。这只是程序员告知编译器可以进行的优化的一种方式。
- 当我们对指针 ptr 使用 restrict 时,它告诉编译器 ptr 是访问它所指向的对象的唯一方法,换句话说,没有其他指针指向同一个对象,即,restrict 关键字指定特定的指针参数确实不为其他任何别名,编译器不需要添加任何额外的检查。
- 如果程序员使用restrict 关键字并违反上述条件,则结果是未定义的行为。
- C++ 不支持restrict 。它是 C 唯一的关键字。
// C program to use restrict keyword.
#include <stdio.h>
// Note that the purpose of restrict is to
// show only syntax. It doesn't change anything
// in output (or logic). It is just a way for
// programmer to tell compiler about an
// optimization
void use(int* a, int* b, int* restrict c)
{
*a += *c;
// Since c is restrict, compiler will
// not reload value at address c in
// its assembly code. Therefore generated
// assembly code is optimized
*b += *c;
}
int main(void)
{
int a = 50, b = 60, c = 70;
use(&a, &b, &c);
printf("%d %d %d", a, b, c);
return 0;
}
120 130 70