[英]Can a bit field structure be instantiated as an immediate?
假設我有以下(組成)定義:
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。]
是的,有可能。 語法或多或少是您期望的。 這是一個完整的示例:
#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.