gpt4 book ai didi

c - 为什么 "unused attribute"为结构数组生成警告?

转载 作者:行者123 更新时间:2023-11-30 16:25:37 28 4
gpt4 key购买 nike

此处使用了具有结构的未使用属性。

根据GCC文档:

unused :

This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.

但是,在下面的代码中,结构数组生成了警告。

#include <stdio.h>

struct __attribute__ ((unused)) St
{
int x;
};

void func1()
{
struct St s; // no warning, ok
}

void func2()
{
struct St s[1]; // Why warning???
}

int main() {
func1();
func2();
return 0;
}

为什么 GCC 对结构数组生成警告?

最佳答案

您不是将属性附加到变量,而是将其附加到类型。在这种情况下,适用不同的规则:

When attached to a type (including a union or a struct), this [unused] attribute means that variables of that type are meant to appear possibly unused. GCC will not produce a warning for any variables of that type, even if the variable appears to do nothing.

这正是 func1 内部发生的情况:变量 struct St s 的类型为 struct St,因此不会生成警告。

但是func2不同,因为St s[1]的类型不是struct St,而是一个数组>结构圣。该数组类型没有附加特殊属性,因此会生成警告。

您可以使用 typedef 将属性添加到特定大小的数组类型:

typedef __attribute__ ((unused)) struct St ArrayOneSt[1];
...
void func2() {
ArrayOneSt s; // No warning
}

Demo.

关于c - 为什么 "unused attribute"为结构数组生成警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53331987/

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