Search code examples
c++identifier

Variable declared outside of a loop is unidentified inside C++


I have a C++ program writen in Microsoft Visual Studio (I've just started learning). Here's my code:

else
    // time is in seconds
    int time = 0;
    double speed = 0.0;
    while (height >= 0)
    {
        cout << "At " << int time << " secs the ball is at height: " << height << " metres.\n";
        time++;
        height -= distanceTravelled(speed);
        speed += gravity;
    }

    // If height dropped from positive to negative in one second, the final fraction of a 
    // second before it hits the ground isn't displayed - so the if statement
    if (height <= 0)
        cout << "At " << time << " secs the ball is at height: " << height << " metres.\n";

When I'm trying to build it I am getting an error

"time" is an undeclared identifier.

But I've declared it outside of the while loop. So why can't it be found?


Solution

  • There are two problems in the code you've posted. One is a spurious int on the output line. It should be just this:

    cout << "At " << time << " secs the ball is at height: " << height << " metres.\n";
    

    The second problem is that your else is missing braces. This means that only the declaration of time is inside the else branch, and everything else is on the same level as the condition (indentation does not count in C++). So it should look like this:

    else
    {
        // time is in seconds
        int time = 0;
        double speed = 0.0;
        while (height >= 0)
        {
            cout << "At " << time << " secs the ball is at height: " << height << " metres.\n";
            time++;
            height -= distanceTravelled(speed);
            speed += gravity;
        }
    
        // If height dropped from positive to negative in one second, the final fraction of a 
        // second before it hits the ground isn't displayed - so the if statement
        if (height <= 0)
            cout << "At " << time << " secs the ball is at height: " << height << " metres.\n";
    }