gpt4 book ai didi

c - 海湾合作委员会 : Static array index in function argument doesn't trigger any warning

转载 作者:太空狗 更新时间:2023-10-29 15:17:22 27 4
gpt4 key购买 nike

我试图理解在 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

[...]

  1. 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/

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