c - 是否可以在不事先定义的情况下将结构变量作为函数参数传递?

标签 c structure compound-literals

我定义了两个结构(在 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,而不必创建变量并将其作为参数传递。

我已经尝试了以下每一个(代替上面的两行),遗憾的是没有一个编译:(

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. 我能做我想做的事吗(但显然是以不同的方式)?

  2. 如果是 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);

可以重写为

rgb col = hsv2rgb( ( hsv ) {i/255.0, 1, 1} );
                    ^^^^    ^^^^^^^^^^^^^
                    |             |
                    |              -- brace enclosed list of initializers
                    -- parenthesized type name

关于c - 是否可以在不事先定义的情况下将结构变量作为函数参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42350203/

相关文章:

C结构体使用前要初始化吗?

能否请您说明为什么存储了变量值,但结构的大小仍然是 0 字节?

c - 嵌套结构,读取字符串 C 的字符时出错

复合文字和指针

arrays - 将数组分配给 int 指针时出现警告 : initialization of 'int *' from ' int' makes pointer from integer without a cast,

c - OpenCL 在 code::blocks 中包括 cl.h on Windows

c - Clock() 函数内部如何工作?

C - 对具有可变长度元素的大二进制文件进行排序

c - C 中数组中的元素数量,不带 sizeof

c - 如何将结构体指针数组传递给函数?