I am trying to print an integer and its formatting should be %d decimal unless its of value FFFF in which case it should be printed as 0xFFFF. I am unable to do so without unnecessary if and else statements. Would it be possible to do this in a single printf statement? Maybe use a macro? Any pointers?
int d;
if(d==0xFFFF) {
printf("%X",d);
} else {
printf("%d",d);
}
Code:
Results:
You'll recognise the conditional testing the value of the variable. The truth value (0 or 1) is shifted left 2 places, effectively multiplying it by 4. This value (0 or 4) is added to the address of the hacky and custom format string that is actually two C strings in one. Either
"%d\n\0"or"%X\n\0"will be used byprintf()to print the next parameter.Now, go read the man page for
printf()and work out how to print the hex value with a leading0x. (Hint: changing"..\0%X.."to"..\00X%x.."will NOT work. Why not?)Don't write code like this. It's definitely a hack...