Is the following code correct?
char mychar = 200;
printf("%x", mychar);
According to http://www.cplusplus.com/reference/clibrary/cstdio/printf/ %x expects an integer (4 bytes with my compiler) and I only pass 1 byte here. Since printf makes use of varargs, my fear is that this only works because of byte alignment on the stack (i.e. a char always uses 4 bytes when pushed on the stack).
I think it would be better to write:
char mychar = 200;
printf("%x", static_cast<int>(mychar));
Do you think the first code is safe anyway? If not, do you think I could get a different output if I switch to a bigendian architecture?
In your example, the argument is actually of type
int.mycharis promoted tointdue to the default argument promotions.and (emphasis mine):
Note that technically the
xconversion specifier requires anunsigned intargument butintandunsigned inttypes are guaranteed to have the same representation.