Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a compound literal struct

Tags:

c

struct

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.

like image 966
Robert Avatar asked Oct 18 '11 17:10

Robert


People also ask

What is a compound literal in C?

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.

Can a struct be a return type?

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."

Can you return structs in C?

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.

Does C++ have compound literals?

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.


1 Answers

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.

like image 151
sidyll Avatar answered Sep 21 '22 18:09

sidyll