Here is the explanation of what it means 6.7.6.3/7:
If the keyword
staticalso 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.
It is not quite clear what it means. I ran the following example:
main.c
#include "func.h"
int main(void){
char test[4] = "123";
printf("%c\n", test_func(2, test));
}
And 2 different implementations of the test_func:
- static version
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];
}
- non-static version
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];
}
I checked the assembly code compiled with gcc 7.4.0 -O3 of the function in both of the cases and it turned out to be completely identical:
Disassembly of the functions
(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
Can you give an example where the static keyword gives some benefits (or any differences at all) comparing to non-static counterpart?
test[3]... except it doesn't. Maybe the compiler is not required to provide diagnostic or justgccdoesn't.clangdoes give awarning: array argument is too small; contains 3 elements, callee requires at least 4 [-Warray-bounds]PS: has nothing to do with assembly, it's a compilation time thing.-Warray-boundsto the compiler options does not give any warning. Maybe this is a gcc bug... ?clangis only providing a warning.statickeyword is useless anyway: Thestatickeyword allows the compiler to assume that the array has at least as many elements as indicated, but if you access an index, the compiler may also assume the index is valid, because accessing out of bounds would be undefined behavior. To construct a case where the feature could be useful, the access would have to be to a known index, but conditional on some run-time predicate. However, the feature is apparently not used much, sogccdoesn't make use of the freedom it offers.