This happens because the ?:
ternary operator is being handled by the compiler, not by the preprocessor.
When type the following code,
int var2 = 1;
cout << getDateFromVar(2) << endl;
what it appears you think will happen is this:
cout << '0' << var2 << endl;
If things worked this way, you'd end up with your output correctly padded as you'd hoped. However, what the preprocessor actually does is first substitute the macro arguments and then basically insert the entire body of the macro into the source file. This results in something like this:
cout << ( (var2<10) ? ('0' << var2) : (var2 ) ) << endl;
At this point, the preprocessor's job is done and the C++ compiler takes over. Everything inside the parenthesis is evaluated first, and if the first option of the conditional is chosen, the two arguments to the <<
operator are integral types ('0'
and var2
), so it performs it's traditional function of a left shift, shifting the ASCII value of '0'
(48) one place to the left, resulting in the 96 you are observing.
I don't really think that there's a good way to achieve this using the processor. You might think that getting rid of some or all of the parenthesis may help out, but this will cause you to run into operator precedence issues, since the <<
operator gets higher precedence than the <
operator.
If you're looking for a more conventional way to use std::cout
to get output padded with zeros, I'd suggest checking out this post; if you were just looking to learn something about the preprocessor, I hope I've helped!