gpt4 book ai didi

c - 数组函数参数声明中的静态关键字

转载 作者:太空狗 更新时间:2023-10-29 17:16:03 25 4
gpt4 key购买 nike

这里解释6.7.6.3/7是什么意思:

If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.

不是很清楚是什么意思。我运行了以下示例:

main.c

#include "func.h"

int main(void){
char test[4] = "123";
printf("%c\n", test_func(2, test));
}

test_func 的 2 种不同实现方式:

  1. 静态版本

func.h

char test_func(size_t idx, const char[const static 4]);

func.c

char test_func(size_t idx, const char arr[const static 4]){
return arr[idx];
}
  1. 非静态版本

func.h

char test_func(size_t idx, const char[const 4]);

func.c

char test_func(size_t idx, const char arr[const 4]){
return arr[idx];
}

我检查了两种情况下函数的gcc 7.4.0 -O3编译的汇编代码,结果完全相同:

函数反汇编

(gdb) disas main
sub rsp,0x18
mov edi,0x2
lea rsi,[rsp+0x4]
mov DWORD PTR [rsp+0x4],0x333231
mov rax,QWORD PTR fs:0x28
mov QWORD PTR [rsp+0x8],rax
xor eax,eax
call 0x740 <test_func>
[...]

(gdb) disas test_func
movzx eax,BYTE PTR [rsi+rdi*1]
ret

您能否举例说明 static 关键字与非静态关键字相比有一些好处(或任何差异)?

最佳答案

这是一个示例,其中 static 实际上有所作为:

unsigned foo(unsigned a[2])
{
return a[0] ? a[0] * a[1] : 0;
}

clang(对于 x86-64,带有 -O3)将其编译为

foo:
mov eax, dword ptr [rdi]
test eax, eax
je .LBB0_1
imul eax, dword ptr [rdi + 4]
ret
.LBB0_1:
xor eax, eax
ret

但是将函数参数替换为unsigned a[static 2]后,结果就很简单了

foo:
mov eax, dword ptr [rdi + 4]
imul eax, dword ptr [rdi]
ret

条件分支不是必需的,因为无论 a[0] 是否为零,a[0] * a[1] 都会计算出正确的结果。但是如果没有 static 关键字,编译器就不能假设 a[1] 可以访问,因此必须检查 a[0]。

目前只有clang做这个优化; ICC 和 gcc 在这两种情况下生成相同的代码。

关于c - 数组函数参数声明中的静态关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56669886/

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