Can you use struct initializer to re-initialize a struct var?

Viewed 58

I am watching a talk about modern C - this is timed link - the presenter showed the following C struct initializer:

typedef struct v2 
{ 
  float x, y; 
} v2;

v2 v = { .x = 1.0f };

v = (v2) { .y = 1.0f };

But when I compile this code, I got the following warn and error:

$>gcc test.c
test.c:6:1: warning: data definition has no type or storage class
    6 | v = (v2) { .y = 1.0f };
      | ^
test.c:6:1: warning: type defaults to ‘int’ in declaration of ‘v’ [-Wimplicit-int]
test.c:6:1: error: conflicting types for ‘v’
test.c:4:4: note: previous definition of ‘v’ was here
    4 | v2 v = { .x = 1.0f };
      |    ^
test.c:6:5: error: incompatible types when initializing type ‘int’ using type ‘v2’ {aka ‘struct v2’}
    6 | v = (v2) { .y = 1.0f };
      |     ^

So is the presenter wrong? I am using gcc v9.4.0, the default at Ubuntu 20.

1 Answers

You simply need to put code in function. Try this:

typedef struct v2 
{ 
  float x, y; 
} v2;

// define and initialise global variable v
v2 v = { .x = 1.0f }; // y defaults to 0

int main(void) {
    // assign a new value to global variable v,
    // using _compound literal_ syntax
    v = (v2) { .y = 1.0f }; // x defaults to 0
    return 0;
}
Related