【c语言】结构体初始化4中方法

今天在6轴传感器的驱动代码源文件中看到结构体没见过的写法:

typedef struct {
  uint8_t xlda                     : 1;
  uint8_t gda                      : 1;
  uint8_t tda                      : 1;
  uint8_t not_used_01              : 5;
} lsm6ds3tr_c_status_reg_t;

于是搜了博客,特此转载。以作记录。

定义

struct InitMember
{
    int first;
    double second;
    char* third;
    float four;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

方法一:定义时赋值

struct InitMember test = {-10,3.141590,"method one",0.25};
  • 1

需要注意对应的顺序,不能错位。

方法二:定义后逐个赋值

struct InitMember test;

test.first = -10;
test.second = 3.141590;
test.third = "method two";
test.four = 0.25;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

因为是逐个确定的赋值,无所谓顺序啦。

方法三:定义时乱序赋值(C风格)

这种方法类似于第一种方法和第二种方法的结合体,既能初始化时赋值,也可以不考虑顺序;

struct InitMember test = {
    .second = 3.141590,
    .third = "method three",
    .first = -10,
    .four = 0.25
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这种方法在Linux内核(kernel)中经常使用,在音视频编解码库FFmpeg中也大量频繁使用,还是很不错的一种方式。

方法四:定义时乱序赋值(C++风格)

这种方法和前一种类似,网上称之为C++风格,类似于key-value键值对的方式,同样不考虑顺序。

struct InitMember test = {
    second:3.141590,
    third:"method three",
    first:-10,
    four:0.25
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

写在后面

其实问题的引出是在分析FFmpeg源代码时,发现大量的结构体乱序赋值初始化的方式,以前在C语言教材上没有发现这种用法,于是学习总结一下,放到这里存档。

猜你喜欢

转载自blog.csdn.net/zDavid_2018/article/details/108224497