cpp Case value is not a constant expression
#include <iostream>
using namespace std;
int main() {
int caseVal = 2;
switch (caseVal) {
case 1:
cout << "Case 1" << endl;
break;
case caseVal + 1:
cout << "Case 3" << endl;
break;
default:
cout << "Default case" << endl;
break;
}
return 0;
}
Explanation:
- Include necessary header files (
iostream
in this case) for input/output operations. - Define the
main()
function, the entry point of the program. - Declare an integer variable
caseVal
and assign it the value2
. - Use a
switch
statement to check the value ofcaseVal
. - In the
switch
statement: - There's a
case
labeled1
that prints"Case 1"
ifcaseVal
is1
. However, this case will be skipped ascaseVal
is2
. - There's another
case
labeledcaseVal + 1
which would evaluate to3
in this instance (2 + 1 = 3
). This case will execute and print"Case 3"
. - The
default
case is included for any value that doesn't match the defined cases. In this scenario, it won't be executed as one of the defined cases will match. - The program ends with a
return 0;
, indicating successful completion. ```