Compiler error "...does not name a type"

When I tried compiling this

struct Hitbox
{
  int x;
  int y;
  int w;
  int h;
};

Hitbox exampleHitbox;
//this is how we can adress the values
exampleHitbox.x = 10;
exampleHitbox.y = 10;
exampleHitbox.w = 4;
exampleHitbox.h = 8;

I got the following error message(s):

 error: 'exampleHitbox' does not name a type

 exampleHitbox.x = 10;

 ^

'exampleHitbox' does not name a type

 exampleHitbox.y = 10;

 ^
does not name a type

 exampleHitbox.w = 4;

 ^

'exampleHitbox' does not name a type

 exampleHitbox.h = 8;

 ^

'exampleHitbox2' does not name a type

 exampleHitbox2.x = 20;

 ^

exit status 1
'exampleHitbox' does not name a type

I'm very confused about this as according to this I did nothing wrong, though i obviously did something wrong, but what?

Unless you initialize when you declare, assignments must be made from within a function.

1 Like

For completeness, you could have said:

struct Hitbox exampleHitbox = {10, 10, 4, 8};

Don't forget the struct in front, unless you use typedef, you could say:

typedef struct
{
  int x;
  int y;
  int w;
  int h;
} Hitbox;

and then,

Hitbox exampleHitbox = {10, 10, 4, 8};

(deleted)

So if I do it like this

struct Hitbox
{
  int x;
  int y;
  int w;
  int h;
};

void test()
{
  Hitbox exampleHitbox;
  exampleHitbox.x = 10;
  exampleHitbox.y = 10;
  exampleHitbox.w = 4;
  exampleHitbox.h = 8;
  Hitbox exampleHitbox2 = {10, 10, 4, 8};
  exampleHitbox2.x = 20;
}

it should work, right? .... . .. ... That works, thank you very much!

No.

If you read my post, I mean really read it, what did I say about nor forgetting the struct in front?

You don't need the extra 'struct' or the 'typedef' in C++. But the assignment code must be in a function. This compiles:

struct Hitbox
{
  int x;
  int y;
  int w;
  int h;
};

Hitbox exampleHitbox;

void setup() {
  //this is how we can adress the values
  exampleHitbox.x = 10;
  exampleHitbox.y = 10;
  exampleHitbox.w = 4;
  exampleHitbox.h = 8;
}

void loop() {}

spycatcher2k: What has this to do with Arduino?

Well, that seems pretty self-evident to me. It's an attempt to write C++ code. The Arduino IDE attempts to compile (a specialized version of) C++ code. Not sure what confused you.

The Arduino IDE attempts to compile (a specialized version of) C++ code.

There is NOTHING "specialized" about the "version of" C++ that the compiler understands. It understands C++ code. Period.

(deleted)