I'm creating a modified printf implementation, and I'm not sure about the answers to these questions.
Does zero work as a null string? (Is printf("%s", 0) allowed?)
I'm guessing no, because 0 is an int. But then this prompts this question:
Does NULL work as a null string? (Is printf("%s", NULL) allowed?)
Logically, I think it should be yes, because NULL implies a pointer; but a lot of implementations seem to have #define NULL 0, so I feel in practice it might be no. Which is correct?
Does the pointer type have to point to char? (Is printf("%s", (void const *)"") allowed?)
My guess is that the type doesn't matter, but I'm not sure.
Case 1 is undefined behavior because the type of the argument (int) does not match the type required by the format specifier (char *).
Case 2 is undefined behavior for the same reason. NULL is allowed to be defined as any integer constant expression with value 0, or such an expression cast to (void *). None of these types are char *, so the behavior is undefined.
Case 3 is undefined behavior for the same reason. "" yields a valid pointer to a null-terminated character array (string), but when you cast it to const void *, it no longer has the right type to match the format string. Thus the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With