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;
};
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!
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
int X;
int Y;
};
struct SEntity {
SCoords Pos;
int Speed;
};
SEntity Player = {{0, 0}, 0}; //Coordinates X , Y, and Speed
Did you like this tutorial/blog post? Feel free to donate to keep more comin', and have more contests.
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.