Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C : assign negative value to enum?

Tags:

c

enums

Background

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.

Question

Why does ctype become 255 instead of -1?

like image 916
henry4343 Avatar asked Jun 24 '16 09:06

henry4343


1 Answers

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.

like image 135
2501 Avatar answered Nov 03 '22 00:11

2501