Expression is not integer constant expression in iOS c object

I want to use the following expression

-(void)SwitchCondn{
    int expression;
    int match1=0;
    int match2=1;

    switch (expression)

    {
        case match1:

            //statements

            break;

        case match2:

            //statements

            break;

        default:

           // statements

            break;

    }

      

But I got

enter image description here

When I researched I found

In order to work in Objective-C, you should define your constant either like this:
#define TXT_NAME 1
Or even better, like this:
enum {TXT_NAME = 1};

      

I have been using these methods for a long time. Now my variable value will change at runtime, so I need to define it in a different way, and I didn't want to use if else, so there is some way to declare the variable in a different way.

I had research after

Why can't I use my constant in a switch-case statement in Objective-C? [error = Expression is not a constant constant expression]

Objective C switch operators and integer constant names

Objective C global constants with case / switch

integer constant is not convertible to integer

+3


source to share


2 answers


The error expression is not an integer constant expression

only means what it says: the case

value must be constant, not variable.

You can change the declarations above switch

as constants:



const int match1=0;
const int match2=1;

      

Or you can use an enum. Or a #define

. But you cannot use volatile variables there.

+10


source


If you want to have tagged cases you need the ENUM type



typedef NS_ENUM(int, MyEnum) {
  match1 = 0,
  match2 = 1
};

- (void)switchCondn:(MyEnum)expression {

  switch (expression)
  {
    case match1:
      //statements
      break;

    case match2:
      //statements
      break;

    default:
      // statements
      break;
  }
}

      

+6


source







All Articles