Is it possible to pass a structural variable as an argument to a function without first defining it?

I have two structures defined like this (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); 

Then I have the following in main.c that works:

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

I want to be able to simply create the hsvCol variable inside the parameters for hsv2rgb without creating a variable and passing it as a parameter.

I tried each of the following (instead of the two lines above), unfortunately, none of them compiles :(

 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}); 

My question is:

  • Can I do what I tried to do at all (but obviously in a different way)?

  • If 1, how do I do this?

+5
source share
2 answers

You can use a composite literal .

Citation C11 , chapter ยง6.5.2.5, paragraph 3,

A postfix expression consisting of a type name in brackets followed by a bracket. The list of initializers is a composite literal. It provides an unnamed object whose value is specified in the list of initializers.

and, paragraph 5,

The value of a composite literal is the name of an unnamed object that is initialized with a list of initializers. [...]

So in your case code like

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

can be rewritten as

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

As BLUEPIXY said in the comments, all I had to do was put (hsv) in front of my value as a translation.

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

Source: https://habr.com/ru/post/1264463/


All Articles