Machinarius
Machinarius

Reputation: 3731

Do variables on namespaces always have default values?

Here's the code in question:

#ifndef _ALTERFPS_H
#define _ALTERFPS_H

#include "HUDLuaFunctions.h"
#include "AlterFPSNodes.h"

namespace AlterFPS
{
    namespace Globals
    {
        static bool teamAwareness;
        static int teams[] = {0, 0};

        static bool getAwareness() {
            return teamAwareness;    
        }

        static void setAwareness(bool aware) {
            teamAwareness = aware;
        }
    }
}

#endif

The problem is teamAwareness is always false.

I breakpoint the getter and the setter (I have them there for debug purposes, i know this isn't Java) and find that the setter does set the variable to true but a subsequent call to getAwareness shows that teamAwareness is false (No setAwareness calls in between)... How can this be possible? How do i fix it?

Upvotes: 0

Views: 853

Answers (1)

rodrigo
rodrigo

Reputation: 98526

Variables with static lifetime are always zero-initialized. Those include:

  • Namespace variables (including the global namespace), be it static or not.
  • Local static variables.
  • Member static variables.

Zero-initialization, making it simple, means:

  • If it is of numeric type: 0
  • If it is bool: false
  • If it is pointer: NULL
  • If it is enum: 0 cast to the enum type
  • If it is of class type: default constructed.

But your problem is not related to that, it is because your variable is declared static and it is in a header file, so each compilation unit (.cpp file) that includes it actually sees it's own instance of the variable. If you change it from one .cpp file you will not see the change from another.

What you want to do is declare the variable extern in the .h file and then define it normally (without modifier) in any .cpp file:

//.h file
namespace Globals
{
    extern bool teamAwareness; 

    inline void setAwareness(bool aware) {
        teamAwareness = aware;
    }
}

//.cpp file
namespace Globals
{
    bool teamAwareness; 
}

BTW, the function is better declared inline.

Upvotes: 3

Related Questions