Printf% s const char *

printf % The conversion specifier expects a pointer to a char array. Note the lack of const . I see the reasons for this in C, and since C ++ includes the C99 standard, this will not change. However, if I write 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; 

Will this have any unintended semantics (note: I am not asking about undefined behavior, because such an implementation will not match anyway)?

+7
c ++ c ++ 11
source share
1 answer

Standard C (ISO / IEC 9899: 2011 (E)) indicates the value of the conversion specifier %s to 7.21.6.1/8:

If a modifier of length l is absent, the argument should be a pointer to the starting element of the character type array.

This statement is clearly not specific enough to determine if the character type is const or not const . It does not even indicate whether char , signed char or unsigned char . I do not think that an array of characters is defined as a term in the C standard.

Put it differently: using char const* for the type specified by the conversion specifier %s is fine.

+1
source share

All Articles