C++ Tip – Shorthand Struct

March 22nd, 2010 by Tim Jones Leave a reply »

Here’s a quick helpful tip that people often overlook. You can quickly initialize the values of a struct using shorthand notation:

struct SEntity {
    int X;
    int Y;
};

SEntity Player = {0, 0}; //Coordinates X , Y

Please note you can only do this when you create your struct object. This will not work:

struct SEntity {
    int X;
    int Y;
};
 
SEntity Player = {0, 0}; //Coordinates X , Y
 
Player = {10, 10}; //Error!

You can even nest:

struct SCoords {
    int X;
    int Y;
};
 
struct SEntity {
    SCoords Pos;
 
    int Speed;
};
 
SEntity Player = {{0, 0}, 0}; //Coordinates X , Y, and Speed
Share and Enjoy:
  • Digg
  • del.icio.us
  • DZone
  • MisterWong
  • Reddit
  • StumbleUpon
  • Technorati
  • Slashdot
  • LinkedIn
  • MySpace
  • Yahoo! Buzz

Did you like this tutorial/blog post? Feel free to donate to keep more comin', and have more contests.

Advertisement

1 comment

  1. Jonny D says:

    For those interested, the upcoming standard of C++, tentatively called C++0x, extends this idea. Currently, you can only do this for POD (Plain Old Data) structs and classes. For instance, you can’t have a std::string in your class. In C++0x, the functionality is bound to std::initializer_list, which allows you to write a constructor which accepts the same syntax but can do everything you normally can in a constructor.

Leave a Reply