Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf %s const char*

Tags:

c++

c++11

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

like image 970
user5477599 Avatar asked Oct 22 '15 21:10

user5477599


People also ask

What does const char * means?

const char*const* argv means "pointer to constant pointer to constant char ".

What is const char * const *?

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.

Can a char * be passed as const * argument?

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 ...


1 Answers

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.

like image 55
Dietmar Kühl Avatar answered Oct 04 '22 04:10

Dietmar Kühl