In your example, both are inserted into the list of printf parameter variables as int values. This can cause problems with the format flags in the printf() format printf() , which do not match the base type. Refer to this post for reasons that undefined behavior might occur.
How disgusting, one way to find out that you can get what you are looking for in this printf is to do this:
#include <stdio.h> #include <stdlib.h> #define LOWER 0 #define UPPER 300 int main() { printf("%d %f", (int)LOWER, (float)UPPER); return 0; }
In both cases, these are preprocessor macros that are replaced before compilation. Note that if UPPER cannot be promoted to float , you will get a compiler error, which is good. if it can be, it will be, and printf() will find the bytes that need to be printed, what it wants. The same is true for int and LOWER respectively. The above printf will degenerate this after preprocessing:
printf("%d %f", (int)0, (float)300);
Now imagine that your macros were declared as such:
#define LOWER 100.0 #define UPPER 300.0
The original printf() will be represented this way after preprocessing:
printf("%d %f", 100.0, 300.0);
which may seem correct, but is it that a 100.0 float will actually be correctly cut out by a %d format string handler in printf() ? Make sure. Performing what we did before:
printf("%d %f", (int)LOWER, (float)UPPER);
now preprocesses:
printf("%d %f", (int)100.0, (float)300.0);
You may receive a compiler warning in the float-to-int application, perhaps you cannot. If you donβt want to roll bones that what you are passing matches the byte size expected by things like printf() , you need to be sure that everything will fit. This can be very frustrating when the format specifier expects one thing, something else is being transmitted, and yet it seems that everything is working fine, but only mysteriously on some platforms:
printf("%ld\n", UPPER);
This may work, but if it is, then only because long int and int are the same size on your platform. Move this code to a platform where long int and int are different bit widths and its UB is completely.
Bottom line: if you pass preprocessor macros to variable parameter lists for things like printf() that have size expectations for the data that was clicked (as indicated, for example, in the format string), you must make sure that you what is expected.