作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我试图理解在 C 函数声明中使用“static”关键字作为数组索引。
看完this article ,我试图声明这样一个函数,并故意将一个太短的数组传递给它:
#include <stdio.h>
#include <stdlib.h>
void print_string10(char string10[static 10]) {
// Should trigger a warning if the argument is NULL or an array of less than 10 elements
printf("%s\n",string10);
}
int main(void) {
char short_string[] = "test";
print_string10(short_string); // should trigger a warning as the string is 5 long
return EXIT_SUCCESS;
}
在文章中使用 clang
编译会触发警告,但 gcc -Wall -Werror
不会,它编译并运行良好。
我找不到解释,这是 GCC 忽略此警告的正常行为吗?
最佳答案
为什么它不需要触发警告是因为它出现在标准的部分 - 6.7.6.3p7 :
Semantics
[...]
- A declaration of a parameter as ''array of type'' shall be adjusted to ''qualified pointer to type'', where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. 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.
它出现在语义部分。仅需要一个符合规范的实现来诊断出现在约束中的那些。即使它没有在这里诊断出违规,它也可以使用 static
关键字的知识来推断参数不为空,并且循环展开和其他优化可能期望一个数组最少那么多元素。
另请注意,example 5那里说
void f(double (* restrict a)[5]);
void f(double a[restrict][5]);
void f(double a[restrict 3][5]);
void f(double a[restrict static 3][5]);
都是兼容的,即即使一个具有static
维度,您也可以在函数指针赋值中混合和匹配它们而无需强制转换!
如果通过函数指针实现调用,clang 似乎(也许是正确的)失去了诊断任何东西的能力:
void (*f)(double a[restrict static 3]);
int main(void) {
double a[1] = {0};
f(a);
}
(在 Clang 7.0 中没有诊断 - 删除 *
你会得到它们)。
关于c - 海湾合作委员会 : Static array index in function argument doesn't trigger any warning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53959862/
我是一名优秀的程序员,十分优秀!