如何在C结构中命名未命名的字段?

now*_*wox 6 c structure naming-conventions

让我们考虑一下这个结构:

struct {
    int a;
    int _reserved_000_[2];
    int b;
    int _reserved_001_[12];
    int c;    
};
Run Code Online (Sandbox Code Playgroud)

永远不应该读取或写入保留字段.我的结构代表了一个描述FPGA的描述符,其中我有很多reserved字段.我最终将它们命名为随机命名,因为多年来最初的升序编号不再具有任何意义.

我现在有:

struct {
    int a;
    int _reserved_3hjdds1_[2];
    int b;
    int _reserved_40iuljk_[12];
    int c;    
};
Run Code Online (Sandbox Code Playgroud)

只改为空字段会更方便:

struct {
    int a;
    int;
    int b;
    int;
    int c;    
};
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

还有什么其他选择可以避免找到reserved字段的唯一名称?

Lun*_*din 5

通过一些宏观魔法应该可以实现你想要的:

#include <stdint.h>

#define CONCAT(x, y) x ## y
#define EXPAND(x, y) CONCAT(x, y)
#define RESERVED EXPAND(reserved, __LINE__)

struct
{
  uint32_t x;
  uint32_t RESERVED;
  uint16_t y;
  uint64_t RESERVED[10];
} s;
Run Code Online (Sandbox Code Playgroud)

这为您提供了诸如reserved11,之类的标识符reserved13,但名称显然并不重要。

  • @nowox 这是一个很好的功能,是吗?为什么要在同一行声明多个结构成员? (2认同)