Anirudh _k
Anirudh _k

Reputation: 1

C warning : enumerated type mixed with another type

I have an enum defined like this -

typedef enum 
{
    emp1 = 0u,
    emp2,
    emp3
}employid;

C throws me warnings for following operations

Problem 1:

unsigned int var; // 32 bit in my compiler

typedef struct
{
   employid e;
}mystruct;

mystruct s;
s.e = var; // **getting warning enumerated type mixed with another type**

Problem 2:

somefun(var); // **getting warning enumerated type mixed with another type**

function definition is somefun(employ e);

I don't understand that even though my enum values are positive since 1st element is 0u why is C compiler shouting at me for assigning it to a unsigned int?

Upvotes: 0

Views: 2632

Answers (1)

Lundin
Lundin

Reputation: 214265

Your code is fine as far as C language rules go. These are just extra diagnostics telling you that the code is fishy.

An unsigned int may hold values not matching any valid enumeration constant, in which case you will end up with s.e holding an invalid value. That is: most of the time, it doesn't really make any sense to mix plain integers with enums. If you find yourself doing so, the root problem is likely on the program design level.

In case you are sure that var holds an ok value, you could do an explicit cast s.e = (employid)var;. But more likely, var should have been declared as employid to begin with.

Upvotes: 1

Related Questions