Public Group

# Help with making a struct please?

This topic is 2102 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi Guys,

It has been ages since I used structs and I am drawing a blank.

This code isn't compiling for me. Could you please let me know where I am going wrong?

struct color
{
int r;
int g;
int b;
};

struct color c_aqua;
// OK to this point, but fails at the following lines.
c_aqua.r=0;
c_aqua.g=255;
c_aqua.b=255;

##### Share on other sites

I don't think you need the second 'struct ' ( in the declaration).

##### Share on other sites

Hmmm, turns out that it doesn't like me initialising the struct outside of the main function.

Oh, well. All good now :)

Thanks guys.

Edited by lonewolff

##### Share on other sites

Hmmm, turns out that it doesn't like me initialising the struct outside of the main function.

Oh, well. All good now

Thanks guys.

You can do it, you need to initialize it with an initializing syntax:

struct color
{
int r;
int g;
int b;
};
struct color c_aqua = {0, 255, 255};
// or if you use c99:
struct color c_yellow = {.r=255, .g=255, .b=0};

int main(void){
return 0;
}


Nice one! Thanks also :)

##### Share on other sites

Assuming you mean the 'struct color c_aqua' bit, this is absolutely required in C (though not in C++).  The usual trick in C to avoid the need to retype the 'struct' keyword is to use a typedef:

I think thats a common C++ thing as well using typedef, I've seen a lot of people using it alot.

It's quite pointless in C++ and not common at all in idiomatic code.

In C, struct and enum have their own "namespaces" (no relation to the C++ concept of that name), hence the need to prefix their use.  Typedefs go into the enclosing scope/namespace which is why the typedef removes the need to use the prefix.  In C++, structs, classes, and enums are all automatically imported into the enclosing namespace though the prefixed use is still allowed for backwards compatibility reasons (and a few esoteric corner cases).

Maybe you've just seen lots of old C code that was ported to C++?  Or you might be thinking of uses in templates to disambiguate dependent types, though that should always be spelled 'typename' in C++03 or later code.  Or some other use of typedef.

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 16
• 11
• 23
• 42
• 75