user5477599
user5477599

Reputation: 71

printf %s const char*

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)?

Upvotes: 7

Views: 3505

Answers (1)

Dietmar Kühl
Dietmar Kühl

Reputation: 153830

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.

Upvotes: 1

Related Questions