• Home
  • 1.19 Character and String Format Specifiers

1.19 Character and String Format Specifiers

View Categories

1.19 Character and String Format Specifiers

< 1 min read

The %c and %s conversion specifiers are used by printf() to display character and string data. %c displays a single character, while %s displays a null-terminated string.

#include <stdio.h>

int main()
{
    char letter = 'A';
    char name[] = "Edcret";

    printf("Character: %c\n", letter);
    printf("String: %s\n", name);

    return 0;
}

Example Output #

Character: A
String: Edcret

Explanation #

The %c conversion specifier displays a single character:

printf("%c\n", letter);

The argument corresponding to %c is expected to have type int. A char argument is automatically promoted to int when passed to printf().

The %s conversion specifier displays characters starting at the address supplied by the argument until a null character '\0' is encountered:

printf("%s\n", name);

The array:

char name[] = "Edcret";

contains the characters followed by a terminating null character.

Character and String Format Specifiers #

Specifier Expected argument type Purpose
%c int Displays a single character
%s char * Displays a null-terminated string

For %s, the supplied pointer must point to a valid null-terminated character sequence. Otherwise, printf() may access memory beyond the intended string, resulting in undefined behavior.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *