简体   繁体   中英

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?

[I discovered that yes, it's possible, so I'm answering my own question. But I cannot promise that this is portable 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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