views:

92

answers:

3

I have a variable which holds a score for a game.

My variable is accessible and correct outside of an if statement but not inside as shown below

score is declared at the top of the main.cpp and calculated in the display function which also contains the code below

cout << score << endl; //works
    if(!justFinished){
        cout << score << endl; // doesn't work prints a large negative number
        endTime = time(NULL);
        ifstream highscoreFile;
        highscoreFile.open("highscores.txt");
        if(highscoreFile.good()){

            highscoreFile.close();
        }else{
            std::ofstream outfile ("highscores.txt");
            cout << score << endl;
            outfile << score << std::endl;

            outfile.close();
        }

        justFinished = true;
    }
    cout << score << endl;//works

EDIT: have realised my problem, when I was printing out it looped through many times so I did not see that all of them for the first loop didn't work, hence I thought the others were working when in fact they were not for the first iteration.

+1  A: 

This is not a problem relating to the scope of the variable.

It could be several things:

  • Memory corruption somewhere
  • Multi threading relating problem
  • Something else...

Are you sure you are looking at the same iteration where the score value works before and after but not inside? Maybe put some more detailed logging instead of simply outputting the score itself.

Brian R. Bondy
A: 

With the amount of code you have attached there is nothing to indicate there is a problem in the code. As Brian says it is something else

Can you try this in your debugger and see what happens ? The idea is to simplify the problem as much as possible and try to get the minimal amount of code that replicates the problem.

What does this do ?

cout << score << endl; //works
if(!justFinished)
{
    cout << score << endl; // doesn't work prints a large negative number
}
cout << score << endl; //works
Romain Hippeau
+1  A: 

Try printing cout << score << "@" << &score << endl; each place you currently print score. This will let you check if you're actually looking at the same variable.

If the addresses are different, you're accidentally shadowing your score variable somewhere - gcc has -Wshadow to catch that.

If the addresses are the same then the variable is getting corrupted somehow. Most debuggers have a memory breakpoint feature, so you can set the debugger to break when the memory in score changes and find the culprit.

Mark B