0

While learning about structs, I came across this question: Initialize/reset struct to zero/null. I then wondered if using a function that returned a struct would work for changing a struct. The following code is a working example I've tested:

#include <stdio.h>

struct location {
    int x, y;
};

struct location move1(struct location);
void move2(struct location *);

int main(void)
{
    struct location loc1 = {0};
    struct location loc2 = {0};

    /* first method */
    printf("x %d, y %d\n", loc1.x, loc1.y);
    loc1 = move1(loc1);
    printf("x %d, y %d\n", loc1.x, loc1.y);

    /* second method */
    printf("x %d, y %d\n", loc2.x, loc2.y);
    move2(&loc2);
    printf("x %d, y %d\n", loc2.x, loc2.y);

    return 0;
}

struct location move1(struct location loc)
{
    loc.x = 2;
    loc.y = 3;
    return loc;
}

void move2(struct location *loc)
{
    loc->x = 4;
    loc->y = 5;
}

My specific question is this: Is there anything wrong with the first method? And if not, is there any reason to prefer one method over the other?

Also note, I am adhering to C90. I have not yet learned about compound literals, etc.

rsarson
  • 95
  • 2
  • 7
  • 3
    Both your functions are fine. But for the first function there's really no need to pass the location structure as an argument, it could create a brand new structure object and return it: `struct location move1(void) { struct location loc = { 2, 3 }; return loc; }` – Some programmer dude Sep 01 '23 at 18:06
  • As for which one to pick and use, it depends on your personal preference, company style guides, and use-case. So it's mostly subjective. – Some programmer dude Sep 01 '23 at 18:07
  • 1
    I think the method in `move2` is more common, because passing a pointer is less overhead than passing and returning a large structure. It also works with opaque structures, since the caller doesn't need the complete structure type declaration (an example is how `FILE*` is used in stdio). – Barmar Sep 01 '23 at 18:30
  • 1
    'move' was a bad choice for name. Neither one of the functions moves a thing. – arfneto Sep 01 '23 at 20:01

0 Answers0