I am using gcc with the -std=c++11 flag. In my class definition I have the following:
private:
const int January = 1,
February = 2,
March = 3,
...
In my implementation I have a switch statement.
switch (currentMonth)
{
case January:
returnString = "January";
break;
case February:
returnString = "February";
break;
case March:
returnString = "March";
break;
...
This seems like it should work since the months are constant; however, gcc gives me
calendar.cpp:116:12: error: ‘this’ is not a constant expression
on each case of the switch statement..Why is this wrong?
The value for a case must be of the same data type as the variable in the switch. The value for a case must be constant or literal. Variables are not allowed.
The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement.
You can still declare variables in switch statements, you just have to put curly brackets around the code after the case label. Compare the two examples below. The first one generates an error. The second lets you compile and move on.
const valuesThe const keyword can also be used in pointer declarations. A pointer to a variable declared as const can be assigned only to a pointer that is also declared as const . You can use pointers to constant data as function parameters to prevent the function from modifying a parameter passed through a pointer.
Non-static class members aren't constant expressions. Try this:
static constexpr int January = 1;
try this:
enum {
January = 1,
February = 2
...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With