是否可以在没有预先定义的情况下将结构变量作为函数参数传递? [英] Is it possible to pass a structure variable as a function argument without previously defining it?
问题描述
我有两个这样定义的结构(在color.h
中):
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 rgb2hsv(rgb color);
rgb hsv2rgb(hsv color);
然后我在main.c
中具有以下功能:
I then have the following in main.c
which works:
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);
我希望能够仅在hsv2rgb
的参数内创建变量hsvCol
,而不必创建变量并将其作为参数传递.
I want to be able to just create the variable hsvCol
inside the parameters for hsv2rgb
without having to create the variable and passing it as a parameter.
我已经尝试了以下每一项(代替上面的两行),可惜的是它们都没有编译:(
I've tried the each of the following (in place of the two lines above), sadly none of which compile :(
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});
我的问题是:
-
我可以完全做我想做的事情吗(但显然以另一种方式)?
Can I do what I was trying to do at all (but obviously in a different way)?
如果为1,我该怎么做?
If 1, how do I go about doing so?
推荐答案
您可以使用复合文字.
引用C11
,第6.5.2.5节,第3段,
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.
以及第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);
可以改写为
rgb col = hsv2rgb( ( hsv ) {i/255.0, 1, 1} );
^^^^ ^^^^^^^^^^^^^
| |
| -- brace enclosed list of initializers
-- parenthesized type name
这篇关于是否可以在没有预先定义的情况下将结构变量作为函数参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!