Search code examples
c++c++11printfinteger-promotion

enum class - printf prints wrong value


I have this enum class:

enum class myEnum : u8{
    LEVEL_ERROR = 0,
    LEVEL_WARN = 50,
    LEVEL_DEBUG = 150,
  };

and at some point I making use of it (not exactly this way, but simply this is what happens):

myEnum instance = 42;
printf("My enum is now: %u", instance);

EDIT: Of course it is used this way: myEnum instance = (myEnum)42;

And printed value is sometimes 298 sometimes 126657066 but never 42. So what I noticed is that all of this "random" numbers are my value but padded with 3 bytes of whatever (stack ?) - 42 = 0x2A, 298 = 0x12A and 126657066 = 0x78CA22A. I understand that my type is getting promoted to int but it should be padded with 3 bytes of "0" in case of unsigned variable type. So why is is padded with garbage ?


Solution

  • Your type is not getting promoted to int. Integer promotions are applied to variable argument list arguments of enumeration type if they are subject to integer promotions [expr.call]/12. The problem is that integer promotions only apply to unscoped enumerations [conv.prom]. Your enum class is a scoped enumeration. Therefore, the value will not be promoted and your call to printf has undefined behavior due to mismatch between the argument type and the type specified in the format string (as also explained in the comments above). You will have to either explicitly cast the value to the integer type you want or change your enum class to an unscoped enumeration…