Error message: expected initializer before 'switch'

225 Views Asked by At
#include <iostream>
using namespace std;
int main()

switch(age)
{
case 1:
case 2:
case 3:
case 4:
cout<< "Tricycle"<<endl;
break;
case 5:
.
.
case 15:
if (15 >= age >= 5)
cout<< "Bicycle"<<endl;
break;
case 16:
case 17:
cout<<"Motorcycle"<<endl;
break;
default:
cout<< "Motor car"<<endl;

return 0;
}

Error message:

Expected initializer before switch

I tried declaring age as an integer...but still I get an error message.

1

There are 1 best solutions below

0
Remy Lebeau On

There are several mistakes in your code:

int main()

You are missing an opening { after main().

switch(age)

You did not declare age, or give it a value, before trying to use it.

.
.

Simply not value code. So I assume you did this only for demonstration purposes here, and in your real code you are actually spelling out each case individually.

if (15 >= age >= 5)

This simply does not do what you think it does. C++ comparisons do not work this way. You need separate expressions to compare age to each value individually.

Not to mention, if you have individual case statements for 5..15, then this if is completely redundant anyway.

return 0;
}

You are missing a closing } on the switch block before return.

With that said, try the following instead:

#include <iostream>
using namespace std;

int main() {

    int age;

    cout << "Enter an age: ";
    if ( (!(cin >> age)) || (age <= 0) ) {
        cout << "Invalid input!" << endl;
        return 1;
    }

    switch (age)
    {
    case 1:
    case 2:
    case 3:
    case 4:
        cout << "Tricycle" << endl;
        break;
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
        cout << "Bicycle" << endl;
        break;
    case 16:
    case 17:
        cout << "Motorcycle" << endl;
        break;
    default:
        cout << "Motor car" << endl;
        break;
    }

    return 0;
}

Alternatively, using if instead of switch:

#include <iostream>
using namespace std;

int main() {

    int age;

    cout << "Enter an age: ";
    if ( (!(cin >> age)) || (age <= 0) ) {
        cout << "Invalid input!" << endl;
        return 1;
    }

    if ( /*age >= 1 &&*/ age <= 4) { // age >= 1 is always true here!
        cout << "Tricycle" << endl;
    }
    else if ( /*age >= 5 &&*/ age <= 15) { // age >= 5 is always true here!
        cout << "Bicycle" << endl;
    }
    else if ( /*age >= 16 &&*/ age <= 17) { // age >= 16 is always true here!
        cout << "Motorcycle" << endl;
    }
    else {
        cout << "Motor car" << endl;
    }

    return 0;
}