Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using const int variable in switch statement

Tags:

c++

gcc

c++11

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?

like image 653
iCodeSometime Avatar asked Apr 30 '13 22:04

iCodeSometime


People also ask

Can we use constants in switch case?

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.

How is an integer constant used in the switch case structure?

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.

Can you declare variables 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.

What is const int used for?

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.


2 Answers

Non-static class members aren't constant expressions. Try this:

static constexpr int January = 1;
like image 187
Kerrek SB Avatar answered Oct 23 '22 23:10

Kerrek SB


try this:

enum {
 January = 1,
 February = 2
 ...
};
like image 21
Jean-Bernard Pellerin Avatar answered Oct 24 '22 00:10

Jean-Bernard Pellerin