可以将一点字段结构实例化为立即数吗?

问题描述 投票:0回答:1

假设我有以下(组成)定义:

typedef union {
  struct {
    unsigned int red: 3;
    unsigned int grn: 3;
    unsigned int blu: 2;
  } bits;
  uint8_t reg;
} color_t;

我知道我可以用它来初始化一个传递给函数的变量,例如:

color_t white = {.red = 0x7, .grn = 0x7, .blu = 0x3};
printf("color is %x\n", white.reg);

...但是在标准C中,是否可以将color_t实例化为立即作为参数传递而不首先将其赋值给变量?

c struct unions bit-fields
1个回答
1
投票

[我发现是的,这是可能的,所以我正在回答我自己的问题。但我不能保证这是便携式C.]

是的,这是可能的。而且语法或多或少都是你所期望的。这是一个完整的例子:

#include <stdio.h>
#include <stdint.h>


typedef union {
  struct {
    unsigned int red: 3;
    unsigned int grn: 3;
    unsigned int blu: 2;
  } bits;
  uint8_t reg;
} color_t;

int main() {
  // initializing a variable
  color_t white = {.bits={.red=0x7, .grn=0x7, .blu=0x3}};
  printf("color1 is %x\n", white.reg);

  // passing as an immediate argument
  printf("color2 is %x\n", (color_t){.bits={.red=0x7, .grn=0x7, .blu=0x3}}.reg);

  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.