0

I have a bit shifting enum:

typdef enum:{
    TypeA = 1 << 0,
    TypeB = 1 << 1,
    TypeC = 1 << 2,
    TypeD = 1 << 3
} my_type_t

And I was trying to determine the highest level it's in of a value, for example, 7 would be equivalent to TypeC, using a switch statement. For example:

NSString* stringType(NSUInteger value){
    switch (value){
        case (TypeA):{
            return @"TypeA";
        }
        case (TypeA | TypeB):{
            return @"TypeB";
        }
        case (TypeA | TypeB | TypeC):{
            return @"TypeC";
        }
        case (TypeA | TypeB | TypeC | TypeD):{
            return @"TypeD";
        }
        default:
            return @"Unknown"
    }
}

but I always got Unknown value, any idea why and how to fix this?

tstanisl
  • 13,520
  • 2
  • 25
  • 40
Ryan
  • 67
  • 6
  • 1
    `@"xxx"` is not C, please remove the `c` tag or change the code – tstanisl May 19 '21 at 15:11
  • 1
    It's a mix of C and ObjC. – Ryan May 19 '21 at 15:16
  • you cannot "mix" languages. It's objC, not C. Please change the tag – tstanisl May 19 '21 at 15:19
  • 1
    Yes you can, `NSString* stringType(NSUInteger value)` is C mixed with ObjC, the function declaration is C, the returned type is ObjC. If that rule applied, most of questions here are wrongly tagged. Example: https://stackoverflow.com/a/828943/14298873 – Ryan May 19 '21 at 15:31
  • What if `value` is 4? – Willeke May 19 '21 at 18:57
  • This code is not a valid C code. It would not be accepted by compliant C compiler. The link refers to *calling* C functions from from ObjC code what is a completely different topic. – tstanisl May 19 '21 at 21:24

1 Answers1

0

Try specifying the type of your typedef (i.e. NSUInteger):

typedef enum : NSUInteger {
    TypeA = 1 << 0,
    TypeB = 1 << 1,
    TypeC = 1 << 2,
    TypeD = 1 << 3
} my_type_t;

With that in place, stringType(7) returns TypeC for me.

R4N
  • 2,455
  • 1
  • 7
  • 9