cprintfc-stringsconversion-specifier

Does s conversion specifier specify direction / order in which characters are written?


Does s conversion specifier specify direction / order in which characters are written?

N3220 working draft, 7.23.6p8 (emphasis added):

s If no l length modifier is present, the argument shall be a pointer to storage of character type.326) Characters from the storage are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the storage, the storage shall contain a null character.

Does it mean that the following program:

#include <stdio.h>

int main(void)
{
    char s[] = {'x', '\0', 'y'};
    printf("%s", s);
}

is allowed to print y?

Despite that the writing direction / order is perhaps obvious, is it specified?


Solution

  • is allowed to print y?

    No, not with that code.

    Given, char s[] = { various};, with printf("%s", s);, the array s is converted to the address of the the first array element. So printf() receives a pointer and has no idea of the size of array s.

    "Characters from the storage are written up to ..." implies that the pointer is incremented for subsequent characters.

    The number of characters continues until a null character is encountered (that null character is not printed). Characters in s[] after the null character are not printed nor are they accessed.


    If a precision specifier is use, the termination of printings stops when a null character is encountered or the specifier count of characters has printed.

    Thus code can print the 'y' even though it lacks a following null character.

    char s[] = { char s[] = {'x', '\0', 'y' };
    printf("%.*s", 1, s + 2);
    // or
    printf("%.1s", s + 2);
    

    Despite that the writing direction / order is perhaps obvious, is it specified?

    The writing direction on the screen (left-to-right, right-to-left, etc.) is a function of the terminal interface. Overwhelmingly, it is left-to-right. This and other terminal characteristics like font size, typeface, color are terminal specific. Text output on such devices, especially multilingual, ones allow for R-to-L as well. Such I/O details are not part of C.

    The order of processing characters, from lowest address to highest, is specified by C.