constants inside switch

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

  1. MrFusion macrumors 6502a

    Jun 8, 2005
    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:

    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


    Nov 25, 2005
    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

    Sep 3, 2005
    Cramlington, UK
    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