printf
's %
conversion specifier expects a pointer to a char
array. Note the lack of const
. I can see the reasons for this in C, and since C++ incorporates the C99 standard, this wouldn't change. However, if I'm writing my own printf
, can I safely convert the argument to const char*
instead?:
case 's' :
ptr = va_arg(va, const char*);
_puts(ptr, strlen(ptr));
break;
Would this have any unintended semantics (note: I'm not asking about undefined behavior, because such an implementation would not be conforming anyway)?
const char*const* argv means "pointer to constant pointer to constant char ".
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
The C standard (ISO/IEC 9899:2011 (E)) specifies the meaning of the %s
conversion specifier in 7.21.6.1/8:
If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.
This formulation clearly not specific enough to tell whether the character type is const
or non-const
. It doesn't even state whether char
, signed char
, or unsigned char
is used. I don't think character array is defined as a term in the C standard.
Put differently: using char const*
for the type specified by a %s
conversion specifier is fine.
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