restrict关键字与memcpy/memmove

restrict关键字用于指示编译器,指定的指针是访问特定内存区域的唯一途径,从而可能允许编译器进行更高效的优化。程序员需确保不通过其他方式修改该内存,否则可能导致未定义行为。文中提供了实例来说明restrict的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

restrict

https://baike.baidu.com/item/restrict/7384270?fr=aladdin
关键字restrict:

  1. 告诉编译器所有修改该指针所指向内存中内容的操作都会通过该指针来修改,而不会通过其它途径(其它变量或指针)来修改,方便编译器做出优化;
  2. 然而,编译器不会检查您是否遵循了这一限制,所以必须由程序员自己来遵循规范

实例1:

//~/C++/restrict/restrict_1.c
//编译命令:gcc restrict_1.c -o restrict -std=c99
//以下代码能够编译通过,说明编译器不会检查您是否遵循了这一限制
#include <stdio.h>
void m_restrict(int *restrict a, int *restrict b)
{
	*a = 5;
	*b = 6;
	printf("restrict\n");
}
int main()
{
	int num1 = 10;
	int *a = &num1;
	int *b = a;
	m_restrict(a, b);
}

实例2:

#include <stdio.h>
void m_restrict(int *restrict a, int *b)
{
	*a += 5;
	*b += 5;
	*a += 3;
	*b += 3;
	//对于a, 由于是用restrict修饰,所以编译器认为只有a可以修改其指向的内存,因此将两个语句合并优化成*a += 8;
	//对于b, 由于编译器无法确定在两条"*b+="语句之间是否会有其他的语句修改b指向的内存,
	//所以它不能直接将两条语句优化合并成*b += 8
}
int main()
{
	int num1 = 0, num2 = 0;
	int *a = &num1;
	int *b = &num2;
	m_restrict(a, b);
	return 0;
}

实例3

void * memcpy(void * restrict s1, const void * restrict s2, size_t n); //实现时应该不会考虑重叠
void * memmove(void * s1, const void * s2, size_t n);				   //实现时需要考虑重叠

//考虑重叠的复制
void m_copy(void*dst,void*src,int n)
{
	if(dst == nullptr || src == nullptr)
		return;
	if(n <= 0)
		return;
	char* cdst = (char*)dst;
	char* csrc = (char*)src;
	if(cdst > csrc)
	{
		for(int i = n - 1;i >=0;i--)
			cdst = csrc;
	}
	else
	{
		for(int i = 0; i < n;i++)
			cdst = csrc;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值