Jump to content
  • Advertisement
Sign in to follow this  
DividedByZero

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.

If you intended to correct an error in the post then please contact us.

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;

 

Thanks in advance :)

Share this post


Link to post
Share on other sites
Advertisement

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 this post


Link to post
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 smile.png

 

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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!