gpt4 book ai didi

c - 了解限制关键字

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:35 24 4
gpt4 key购买 nike

为了理解严格别名和 restrict 关键字的用法,我正在尝试下面显示的程序。在这种情况下,相同的内存位置由两个指针引用。因此,在没有用户明确告知的情况下,编译器无法进行任何优化(即不使用 restrict 关键字)。因此,我的理解是,如果没有 restrict 关键字,程序的输出将为 40,而带有“restrict”的输出将为 30(因为“a”不需要在“*b += *a”之后从内存中读取)。然而,即使有限制,输出也是 40。为什么优化没有发生?

我正在关注“What is the strict aliasing rule?”以了解情况。

#include <stdio.h>

void merge_two_ints(int * restrict a, int * restrict b) {
*b += *a;
*a += *b;
}

int
main(void)
{
int x = 10;
int *a = &x;
int *b = &x;
merge_two_ints(a, b);
printf("%d\n", x);
return 0;
}

bash-3.2$ gcc -Wall -O3 -fstrict-aliasing -std=c99 strict_alias2.c

bash-3.2$ ./a.out40

最佳答案

你观察到:

In this case, same memory location is referenced by two pointers. [...] my understanding was that without restrict keyword, output of the program will be 40 and with 'restrict' output will be 30 (as 'a' does not need to be read from memory after "*b += *a").

但是你的期望直接违背了C标准,它规定:

The intended use of the restrict qualifier [...] is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).

( C2011 6.7.3/8 ; 已强调)

此外,6.7.3/8 还说,

An object that is accessed through a restrict-qualified pointer has a special association with that pointer. This association, defined in 6.7.3.1 below, requires that all accesses to that object use, directly or indirectly, the value of that particular pointer.

在不深入细节的情况下,6.7.3.1 明确规定,当给定程序不满足其规定时,行为是未定义的。您的程序触发了此规定,并且您正在预期由此产生的未定义行为的特定表现形式。 C 语言中没有任何内容可以证明这一点。

However even with restrict, output is 40. why the optimization is not happening?

C 语言从不要求进行一般优化或执行任何特定优化。

关于c - 了解限制关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48289616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com