0
What's Wrong w/ my Code
I just started learning C++ and I feel really dum right now #include <iostream> using namespace std; int main() { int a; cin>>a; switch (a){ case (a>=0 && a<=59): cout<<"F\n"; break; case (a>=60 && a<=69): cout<<"D\n"; break; case (a>=70 && a<=79): cout<<"C\n"; break; case (a>=80 && a<=89): cout<<"B\n"; break; case (a>=90 && a<=100): cout<<"A\n"; break; default: cout<<"That is not a possible test score\n"; } It then keeps outputting: ..\Playground\:9:22: error: the value of 'a' is not usable in a constant expression case (a>=0 && a<=59): ^ ..\Playground\:6:7: note: 'int a' is not const int a; ^ for every case
4 ответов
+ 4
missing semicolon after "a"...
Additionaly const means value cannot be modified, so you wont be able to let user initialise it. const variable has to be initialised right after it's declared. So e.g. const int size =10;
+ 3
I work with code for years and know many people who work on codes for decades... You'll NEVER stop having issues like that. I can't even tell how many hours (days and weeks combined) i've spent on searching where that f**** semicolon was missing...
;-) Keep it up
+ 2
You have at least twice problems on the first line of your main() function:
- forget of ending line with semi colon ( this is the cause of the compiler error on the next line )
- const declaration: you can't use a constant because a const var must be intialized during the declaration ( else "const" didn't make sense ^^ )
+ 1
It has nothing to do with int a being a constant; because it isn't.
You cannot do conditional checks in a switch statement (greater than, less than, not, or, and etc.), you can only have switch cases with constant values (hence the mention of constants in the compile error), as in, you can only have cases lile case 1, case 50, case 7 etc.
TL;DR. You cannot do conditional checks with switch statements. Use if-else for that.