假设我具有以下(组成)定义:
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实例化为作为参数传递的立即数,而无需先将其分配给变量?
答案 0 :(得分: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;
}