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

标签 c arrays gcc struct unused-variables

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

根据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/47053565/

相关文章:

javascript - 如何将对象转换为嵌套对象

arrays - 在Mathematica中使用数组和表函数。什么时候最好

c - 海湾合作委员会错误 : expected expression before 'else'

c程序中的cmake和readline库

c++ - 写入多个文件描述符

c - 使用段寄存器 FS 进行调试

c - loadrunner 中参数的最大长度是多少?

c - 如何引用嵌套结构中的指针?

objective-c - NSLog iPhone中Objective-C的方法名

android - 如何从android中的数组排序中跳过第0个位置值?