Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression is not an integer constant expression in iOS objective c

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 research 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 this methods since long time . Now my variable value will change in run time so I need to define in others way and i didn't want to use if else so is there any way of declaration variable others way

I have had study following

Why can I not use my constant in the switch - case statement in Objective-C ? [error = Expression is not an integer constant expression]

Objective C switch statements and named integer constants

Objective C global constants with case/switch

integer constant does 'not reduce to an integer'

like image 507
Nischal Hada Avatar asked Jun 29 '15 15:06

Nischal Hada


2 Answers

The error expression is not an integer constant expression means just what it says: in a case, the value must be constant, as in, not a variable.

You could change the declarations above the switch to be constants:

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

Or you could use an enumeration. Or a #define. But you can't use non-constant variables there.

like image 108
Tom Harrington Avatar answered Nov 15 '22 12:11

Tom Harrington


If you want to have labeled cases, you need a 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;
  }
}
like image 22
vadian Avatar answered Nov 15 '22 12:11

vadian