Does printf(“%x”,1) invoke undefined behavior?

I believe it is technically undefined, because the “correct type” for %x is specified as unsigned int – and as you point out, there is no exception for signed/unsigned mismatch here.

The rules for printf are for a more specific case and thus override the rules for the general case (for another example of the specific overriding the general, it’s allowable in general to pass NULL to a function expecting a const char * argument, but it’s undefined behaviour to pass NULL to strlen()).

I say “technically”, because I believe an implementation would need to be intentionally perverse to cause a problem for this case, given the other restrictions in the standard.

Leave a Comment