constants inside switch

Discussion in 'Mac Programming' started by MrFusion, Sep 18, 2007.

  1. MrFusion macrumors 6502a

    Joined:
    Jun 8, 2005
    Location:
    West-Europe
    #1
    I thought to be smart and define a sets of constants, just like Apple.
    e.g. NSTableViewNoColumnAutoresizing

    .h file:
    extern int const myConstant;
    .m file:
    int const myConstant = 9;

    So I figured I could use these in a switch

    swith ([delegate mySwitch]) {
    case myConstant:
    break;
    }

    But this gives a compile error. Is this normal and I can not do things in this manner, or did I do something wrong?

    error: case label does not reduce to integer constant
     
  2. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    It's normal. You are using Objective-C, which is based on C, not on C++. In the C language, const variables are still variables and don't count as "constant expressions".

    Usually your best choice is to use an "enum" to define a number of related constants; slightly less good is to use a series of #define preprocessor statements.
     
  3. lazydog macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #3
    I don't think this would work even in C++ in general anyway. It works if the .m file containing the switch can see the value of myConstant but if it only sees the .h file, ie myConstant really is an extern, then the compiler would throw a similar error. I think you're much better off using enums or #defines like gnasher729 suggests.

    b e n
     

Share This Page