是否可以在不事先定义的情况下将结构变量作为函数参数传递?
Is it possible to pass a structure variable as a function argument without previously defining it?
我定义了两个结构(在 color.h
中):
typedef struct rgb {
uint8_t r, g, b;
} rgb;
typedef struct hsv {
float h, s, v;
} hsv;
hsv rgb2hsv(rgb color);
rgb hsv2rgb(hsv color);
然后我在 main.c
中有以下内容有效:
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);
我希望能够在 hsv2rgb
的参数内创建变量 hsvCol
,而不必创建变量并将其作为参数传递。
我已经尝试了以下每一个(代替上面的两行),遗憾的是 none 其中编译 :(
rgb col = hsv2rgb({i/255.0, 1, 1});
rgb col = hsv2rgb(hsv {i/255.0, 1, 1});
rgb col = hsv2rgb(hsv hsvCol {i/255.0, 1, 1})
rgb col = hsv2rgb(struct hsv {i/255.0, 1, 1});
我的问题是:
我能做我想做的事情吗(但显然是以不同的方式)?
如果是 1,我该怎么做?
您可以使用 compound literal。
引用 C11
,章节 §6.5.2.5,第 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.
以及第 5 段,
The value of the compound literal is that of an unnamed object initialized by the
initializer list. [...]
因此,在您的情况下,代码类似于
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);
可以re-written为
rgb col = hsv2rgb( ( hsv ) {i/255.0, 1, 1} );
^^^^ ^^^^^^^^^^^^^
| |
| -- brace enclosed list of initializers
-- parenthesized type name
我定义了两个结构(在 color.h
中):
typedef struct rgb {
uint8_t r, g, b;
} rgb;
typedef struct hsv {
float h, s, v;
} hsv;
hsv rgb2hsv(rgb color);
rgb hsv2rgb(hsv color);
然后我在 main.c
中有以下内容有效:
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);
我希望能够在 hsv2rgb
的参数内创建变量 hsvCol
,而不必创建变量并将其作为参数传递。
我已经尝试了以下每一个(代替上面的两行),遗憾的是 none 其中编译 :(
rgb col = hsv2rgb({i/255.0, 1, 1});
rgb col = hsv2rgb(hsv {i/255.0, 1, 1});
rgb col = hsv2rgb(hsv hsvCol {i/255.0, 1, 1})
rgb col = hsv2rgb(struct hsv {i/255.0, 1, 1});
我的问题是:
我能做我想做的事情吗(但显然是以不同的方式)?
如果是 1,我该怎么做?
您可以使用 compound literal。
引用 C11
,章节 §6.5.2.5,第 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.
以及第 5 段,
The value of the compound literal is that of an unnamed object initialized by the initializer list. [...]
因此,在您的情况下,代码类似于
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);
可以re-written为
rgb col = hsv2rgb( ( hsv ) {i/255.0, 1, 1} );
^^^^ ^^^^^^^^^^^^^
| |
| -- brace enclosed list of initializers
-- parenthesized type name