简体   繁体   English

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

[英]Can a bit field structure be instantiated as an immediate?

Suppose I have the following (made up) definition: 假设我有以下(组成)定义:

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

I know I can use this to initialize a variable that gets passed to a function, such as : 我知道我可以使用它来初始化传递给函数的变量,例如:

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

... but in standard C, is it possible to instantiate a color_t as an immediate for passing as an argument without assigning it first to a variable? ...但是在标准C语言中,是否可以将color_t实例化为作为参数传递的立即数,而无需先将其赋给变量?

[I discovered that yes, it's possible, so I'm answering my own question. [我发现是的,有可能,所以我在回答自己的问题。 But I cannot promise that this is portable C.] 但是我不能保证这是可移植的C。]

Yes, it's possible. 是的,有可能。 And the syntax more or less what you'd expect. 语法或多或少是您期望的。 Here's a complete example: 这是一个完整的示例:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM