Mike S
Mike S

Reputation: 1613

C++: Uninitialized Variable Output Is 0 in Xcode

I'm in a very rudimentary beginner's programming course, focusing on C++. We're currently being taught about member variables vs local variables. To that end, I've written this very simple program, to see what the output would be when a local variable is declared but uninitialized and given the same name as a member variable that has been initialized.

class myclass
{
    public:
        void getvalues();
        myclass();
    private:
        int count;
};

myclass::myclass()
{
    count = 100;
}

void myclass::getvalues()
{
    int count;
    std::cout << count << std::endl;
}

int main()
{
    myclass foo;
    foo.getvalues();

    return 0;
}

My expectation is that I would get some garbage output of some very large random number. Instead, the output is 0. Any particular reason why this is? I'm using Xcode, if this makes a difference.

Upvotes: 1

Views: 148

Answers (1)

TinyTheBrontosaurus
TinyTheBrontosaurus

Reputation: 4810

Officially this is undefined behavior. But some environments will zero out memory. While other will leave it uninitialized. One thing you can count on is this not behaving the same in all environments (e.g., visual studio, gcc, etc.)

Upvotes: 3

Related Questions