Is it possible to pass a structure variable as a function argument without previously defining it?

前端 未结 1 654
遥遥无期
遥遥无期 2021-01-18 23:48

I have two structs defined as so (in color.h):

typedef struct rgb {
  uint8_t r, g, b;
} rgb;

typedef struct hsv {
  float h, s, v;
} hsv;

hsv         


        
相关标签:
1条回答
  • 2021-01-19 00:05

    You can make use of a compound literal.

    Quoting C11, chapter §6.5.2.5, paragraph 3,

    A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

    and, paragraph 5,

    The value of the compound literal is that of an unnamed object initialized by the initializer list. [...]

    So, in your case, the code like

    hsv hsvCol = {i/255.0, 1, 1};
    rgb col = hsv2rgb(hsvCol);
    

    can be re-written as

    rgb col = hsv2rgb( ( hsv ) {i/255.0, 1, 1} );
                        ^^^^    ^^^^^^^^^^^^^
                        |             |
                        |              -- brace enclosed list of initializers
                        -- parenthesized type name
    
    0 讨论(0)
提交回复
热议问题