Nischal Hada
Nischal Hada

Reputation: 3288

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'

Upvotes: 5

Views: 13244

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70976

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.

Upvotes: 12

vadian
vadian

Reputation: 285200

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;
  }
}

Upvotes: 6

Related Questions