Yíu
Yíu

Reputation: 383

Function name for returning a struct

I want to make a function in which I change an already existing struct. So the return value of that function should be a struct. If I want an int as return value I call the function "int example()" ... How do I call the function if I want to return a struct? Since "struct" is already taken — I already take "struct whatever" to create one.

Upvotes: 0

Views: 480

Answers (2)

user3629249
user3629249

Reputation: 16540

passing a struct by value will cause the compiler to establish 1 or more reserved areas in memory that can only be used for that function.

Each of those memory areas are manipulated by the compiler inserting calls to memcpy().

Much better to pass a pointer to the struct, then return a simple indication of success/failure of the struct update operation.

Upvotes: 0

nneonneo
nneonneo

Reputation: 179422

If you want the function to modify an existing struct, you should pass the struct in by pointer:

void modify_thing(struct whatever *thing);

If you want to return a modified copy of the struct, you can return the struct by value:

struct whatever edit_thing(const struct whatever *input);

Note that it is usually more efficient to pass struct variables by pointer, rather than by value.

Upvotes: 7

Related Questions