- 1

SWITCH STATEMENT C++

Can I use a range in a switch statement in C++ e.g In a program where a student gets a grade assigned to their score, is it correct to do this: int score; cin >> score; switch (score) case (score>=90) cout << 'A'; break; case (score >=80) cout << 'B'; break; case ..... and so forth till F

15th Sep 2022, 12:38 PM
zighetamara
4 Antworten
+ 1
Not as standard, rather as an extension in gcc compilers. https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html
15th Sep 2022, 1:21 PM
Ipang
0
Why Not ?
15th Sep 2022, 12:59 PM
SoloProg
SoloProg - avatar
15th Sep 2022, 1:17 PM
SoloProg
SoloProg - avatar
0
Your code has a problem. switch uses a variable inside it's (), then it will execute the whole code in it's curly brackets. To run switch, You'll need a variable inside (), a couple of curly brackets({}), then you will do the case command inside the curly brackets. A code for example: #include <iostream> using namespace std; int main() { cout << "Type 1 to start the game and type 2 to leave the game!" << endl; cin >> option switch(option) { case 1: cout << "You entered the game!"; break; case 2: cout << "You left the game!:C" << endl; return 0; } }
15th Sep 2022, 2:27 PM
Dragon RB
Dragon RB - avatar