I have started to learn C89, and am diving into structs. My question is best explained through an example.
Imagine this snippet of code:
typedef struct {
int x, y, r;
} Circle;
Circle createCircle(int x, int y, int r){
Circle create = {x, y, r};
return create;
}
int main(void){
Circle coords = createCircle(3, 2, 1);
return 0;
}
As you can see, I'm creating a variable create
in the function createCircle before returning it to the main function. I was wondering whether some form of shorthand existed to omit this middle step, for example like this:
Circle createCircle(int x, int y, int r){
return Circle {x, y, r};
}
Naturally, the above doesn't work, but it should give you an idea of what I'm looking to achieve. Is this possible, or am I better off creating a variable first?
Thanks!
The construct you're looking for is called a compound literal, and the syntax is actually almost identical to your demonstration. Just add parens around the type:
return (Circle){x, y, r};
This is a C99 feature to create literals for aggregates like structs and arrays (although it can be used to create scalars too, somewhat counter-intuitively,) analogous to integer and other scalar literals. Other than the parenthesized type name in front, the syntax is just as when initializing an instance of the type.
Unlike other literals which generally exist in the data segment, compound literals are constructed and reside in automatic storage in the scope they are created (or static if they are in global scope.) In other words, using a temporary named Circle is effectively the same at the machine code level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With