I have a function that will always return a struct with known values. What is the syntax?
struct MyStruct Function(void)
{
return (struct MyStruct){1,2,3};
}
I am getting a compiler error on the return line:
Error: syntax error
Any ideas? I'm using a cross-compiler to an embedded target, so it could be my compiler.
Edit
It's my compiler. As cnicutar commented, it's valid C99 code.
Some people pointed out that I could create a variable. My goal was to avoid creating a variable just to return it.
In C, a compound literal designates an unnamed object with static or automatic storage duration. In C++, a compound literal designates a temporary object that only lives until the end of its full-expression.
One of them asked if you could return a struct from a function, to which I replied: "No! You'd return pointers to dynamically malloc ed struct s instead."
Now, functions in C can return the struct similar to the built-in data types. In the following example code, we implemented a clearMyStruct function that takes a pointer to the MyStruct object and returns the same object by value.
In C++, a compound literal designates a temporary object, which only lives until the end of its full-expression. As a result, well-defined C code that takes the address of a subobject of a compound literal can be undefined in C++, so the C++ compiler rejects the conversion of a temporary array to a pointer.
Looks like you're trying to cast a initializer as a struct :-)
This is not valid syntax. Try something like:
struct MyStruct Function(void)
{
struct MyStruct s = {1,2,3};
return s;
}
But it would be better to show how exactly MyStruct
is declared, just in case.
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