Search code examples
c++scopeswitch-statementdeclaration

variable not defined in a switch case statement


Here is my switch case statement. The compiler keeps stating totalShare is not defined even though it's defined in case 1. I'm a beginner with C++ and just started to learn about stack.

switch (option)
{
    case 1:
    {
        string newStock;
        double share;
        double price;

        cout << "Enter a new stock: " ;
        cin >> newStock;

        cout << "Enter a number of shares: " ;
        cin >> share;

        cout << "Enter price [for that number of shares]:  " ;
        cin >> price;

        //share x price
        double sharePrice = share * price;

        //add to stack
        newStockStack.push(sharePrice);

        //total share
        double totalShare;
        totalShare += share;
        break;
    }

    case 2:
    {
        //calculate stacks
        double theTotal;
        while (!newStockStack.empty())
        {
            theTotal += newStockStack.top();
            newStockStack.pop();
            return theTotal;
        }
        // FORMULA
        //((every share x price)+ (every share x price)) / total number of shares

        double LifoPrice;
        LifoPrice = (theTotal / totalShare);
        cout << "The Lifo price for the stock is: " << LifoPrice << endl;
        break;
    }

Solution

  • double totalShare; is present inside the "case 1" block

    That means, totalShare is local to that block i.e. its scope is within case 1 only and it is not visible outside that block.

    But then you have LifoPrice = (theTotal / totalShare); inside the "case 2" block. That is why, your compiler complains that totalShare is not defined (within the case 2 block).

    Solution:

    Define that variable inside such a scope that would allow its usage wherever you want. In this case, since you need that variable within multiple case blocks, consider declaring that variable outside the switch statement. Because it is a good practice to limit the scope of the variables, if you need that variable only inside the switch statement then you can declare it inside the switch statement but before all the case blocks that need totalShare.