I am trying to assign -1 to an enum variable as shown below:
typedef enum test {
        first,
        second,
}soc_ctr_type_t 
soc_ctr_type_t ctype;
...
switch(type){
   case 1:
       ctype = first;
   break;
   case 2:
      ctype = second;
   break;
   default:
      ctype = -1;
}
If type is the default case, ctype should become -1, but it's not.
When I use printf to debug, ctype is 255.
Why does ctype become 255 instead of -1?
Define a enumerator with that value in the enumerator list and the result will be correct:
typedef enum test {
        minus_one = -1 ,
        first,
        second,
} soc_ctr_type_t;
The reason you're seeing 255 is because the compiler chose a narrower unsigned type for this enumerator, because all it can see it first, second, which have the values 0, 1. Thus the type chosen is unsigned char because it can represent those two values.
This type will wrap to 255 from -1.
Enumerators in C aren't a special type, they're represented by an integer type, so you can assign a value to an enumerator that isn't present in the enumerator list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With