Vince
Vince

Reputation: 4439

C++ : global structure

In the same way than using global variable,

const double GRAVITY = 9.81;

int main(){}

I would like to use global structure

typedef struct {
    double gravity;
} WorldConfig;

WorldConfig WC;
WC.gravity = 9.81;

int main(){}

but this does not compile ("WC" does not name a type).

Is there a way to do this or alternatively, a good reason why using a global struct would be a super bad idea ?

thx

Upvotes: 0

Views: 6483

Answers (4)

Michael Wild
Michael Wild

Reputation: 26381

In C++ you don't need the typedef, this is not C. Also, you need to set the gravity member in the initializer:

struct WorldConfig {
    double gravity;
} WC = {9.81};

However, for such constants, you probably want them to be really constant, so you could do:

struct WorldConfig
{
    static constexpr double gravity = 9.81; // requires C++11
};

Upvotes: 2

CashCow
CashCow

Reputation: 31445

Even if you put it into the scope of a class or struct, if it's static it is still a global.

Putting it within a struct would be useful in a meta-programming world, i.e.

struct Earth
{
   static const double gravity;
};

struct Mars
{
   static const double gravity;
};

// pseudo code
template< typename PLANET >
someFuncOrClass
{
     using PLANET::gravity;
}

This gets resolved at compile time (compared to making Planet a class that has a gravity attribute).

The obvious alternative scoping option though is a namespace.

namespace WC
{
     static double gravity;
}

Upvotes: 1

Thomas Moulard
Thomas Moulard

Reputation: 5542

Another solution is:

In your header:

struct WC
{
   static const double g;
};

In your source file:

const double WC::g = 9.81;

Please note that anonymous struc and typedef use is C-style, not C++.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477620

Yes, initialize the global variable:

struct WorldConfig
{
    double gravity;
};

WorldConfig WC = { 9.82 };

int main() { }

Upvotes: 3

Related Questions