dimanche 19 juillet 2020

Do I need to wrap the body of case in switch statement with curly braces in C++?

I am writing a simple program in C++ that asks a user to enter an operation they want to perform on collection of elements (vector). In here I'm using the switch statements in order to recognize the operation key the user entered. In my case 'm' or 'M' I am getting an error error C2360: initialization of 'sum' is skipped by 'case' label. The error disappears when I wrap the case with curly braces. As I know it is not obligatory to wrap each case body with curly braces so I am wondering why am I getting such an error when the body of this case is without curly braces. Any idea?

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector <int> vec{};
    char choice{};

    do
    {
        cout << "\nP - Print numbers in list" << endl;
        cout << "A - Add a number to the list" << endl;
        cout << "M - Display mean of the numbers" << endl;
        cout << "S - Display the smallest number in the list" << endl;
        cout << "L - Display the largest number in the list" << endl;
        cout << "Q - Quit" << endl;

        cout << "Enter your choice: ";
        cin >> choice;
        cout << "\nYour choice: " << choice << endl;

        switch (choice)
        {
        case 'p':
        case 'P':
        
            if (vec.size() == 0)
            {
                cout << "[] - empty list" << endl;
            }
            else
            {
                cout << "[ ";
                for (auto i : vec)
                {
                    cout << i << " ";
                }
                cout << "]" << endl;
            }
            break;
        

        case 'a':
        case 'A':
        
            int num;
            cout << "\nEnter a number: ";
            cin >> num;
            vec.push_back(num);
            cout << num << " added to the list" << endl;
            break;
        

        case 'm':
        case 'M':
        
            double average;
            double sum{};
            for (auto i : vec)
            {
                sum += i;
            }
            average = sum / vec.size();
            cout << "\Average is: " << average << endl;
            break;
        

        case 's':
        case 'S':
        
            int min_val = vec[0];

            for (int i = 0; i < vec.size(); i++)
            {
                if (min_val > vec[i])
                    min_val = vec[i];
            }

            cout << "MIN is: " << min_val << endl;
            break;
            }
        

    } while (choice != 'q' && choice != 'Q');
}

Aucun commentaire:

Enregistrer un commentaire