71

Why does C's printf format string have both %c and %s?

I know that %c represents a single character and %s represents a null-terminated string of characters, but wouldn't the string representation alone be enough?

6
  • 50
    Probably to distinguish between null terminated string and a character. If they just had %s, then every single character must also be null terminated. char c = 'a';, in this case c must be null terminated. This is my assumption though :)
    – Mahesh
    Jun 1, 2012 at 7:18
  • 23
    @Mahesh: Why not put that as an answer, Especially, when It is the answer
    – Alok Save
    Jun 1, 2012 at 7:20
  • 4
    Huh? What if you just want to put a single character, why should you need to append a NUL to it? Or did I not get something in this question? Jun 1, 2012 at 7:21
  • 2
    @Mahesh your assumption is the answer to this question I believe Jun 1, 2012 at 7:21
  • 2
    %c expects a datum of char type - a value primitive. %s expects a datum of char * type, a pointer. The difference between these is enormous in C, in spite of the fact that they both apply to text. Jun 1, 2012 at 19:02

11 Answers 11

99

Probably to distinguish between null terminated string and a character. If they just had %s, then every single character must also be null terminated.

char c = 'a';

In the above case, c must be null terminated. This is my assumption though :)

13
  • 13
    Not a real answer because that could be avoided by %.1s Jun 1, 2012 at 7:35
  • 3
    @Merlin I didn't say that. Probably, my sentence formation might be confusing. As you might know, the format string for the format specifier %s must be null-terminated. If there is no %c in the language, then in my above example, identifier c must be null terminated to be able to use with the format specifier %s.
    – Mahesh
    Jun 1, 2012 at 14:24
  • 7
    @mahesh Confusing an answer is worse than giving a wrong answer ... I can't believe you are arguing about it.
    – Moog
    Jun 1, 2012 at 14:50
  • 42
    -1 this is a poor answer... The reason that printf("%s", c) would not work is not because of null-termination, but because printf expects %s to point to a memory location, while c is a character-value. Null-termination is the reason printf("%s", &c) wouldn't work, but even if it did, having a %c identifier would still make sense, because requiring &c is inconsistent with the way every other variable-type is printed. So just saying "it's because of null termination" is incorrect. Jun 1, 2012 at 17:37
  • 9
    I don't see how 74 people thought this was the correct answers since it doesn't mention that you would have to pass a char* to even get the one character to print with %s. Just reiterating what BlueRaja said Jun 2, 2012 at 9:00
74

%s prints out chars until it reaches a 0 (or '\0', same thing).

If you just have a char x;, printing it with printf("%s", &x); - you'd have to provide the address, since %s expects a char* - would yield unexpected results, as &x + 1 might not be 0.

So you couldn't just print a single character unless it was null-terminated (very inefficent).

EDIT: As other have pointed out, the two expect different things in the var args parameters - one a pointer, the other a single char. But that difference is somewhat clear.

3
  • 8
    you should mention that %s takes a pointer while %c takes a character itself.
    – Matt
    Jun 1, 2012 at 7:21
  • And what is more important you only could print a character if its address can be taken. That would exclude printing the returns from functions, e.g, and also register variable. Jun 1, 2012 at 7:27
  • 1
    You could avoid the issue of the null termination by providing a precision. Jun 1, 2012 at 7:30
38

The issue that is mentioned by others that a single character would have to be null terminated isn't a real one. This could be dealt with by providing a precision to the format %.1s would do the trick.

What is more important in my view is that for %s in any of its forms you'd have to provide a pointer to one or several characters. That would mean that you wouldn't be able to print rvalues (computed expressions, function returns etc) or register variables.

Edit: I am really pissed off by the reaction to this answer, so I will probably delete this, this is really not worth it. It seems that people react on this without even having read the question or knowing how to appreciate the technicality of the question.

To make that clear: I don't say that you should prefer %.1s over %c. I only say that reasons why %c cannot be replaced by that are different than the other answer pretend to tell. These other answers are just technically wrong. Null termination is not an issue with %s.

15
  • 5
    @LuchianGrigore: No, I don't say that anybody should prefer that, in the contrary. I say that %.1s would have the functionality of printing just one character that musn't even be null terminated, so the null termination is not a valid objection to "introduce" %c. Jun 1, 2012 at 7:38
  • 4
    @Als Would %.1s be expecting a char or a char*? Jun 1, 2012 at 7:48
  • 2
    @LuchianGrigore, nobody says that. My answer simply states that null termination is not the right argument, but that taking the address of the object is an argument. Jun 1, 2012 at 8:12
  • 3
    @JoshuaDrake, did you read my answer. I find downvoting for that really excessive. I don't say that anybody should use %.1s for printing a character. This was not the question. The question was whether %c was strictly necessary. And I give an affirmative answer to that, just stating that the reasons are different that the ones given in the other answers. Jun 1, 2012 at 17:40
  • 3
    @JoshuaDrake: -1 for not reading the answer. The question asks Why does X exist in C, and this answer clearly explains that X MUST exist in order to work with rvalues. Without consideration for rvalues, the language/library designers probably would (and just as probably SHOULD) have left it at %.1s as it makes the printf cleaner (adn thus more readable). Without c, printing the result of a function that returned a single character could end up being quite complex (particularly if calling multiple functions with side effects and which are order dependent).
    – jmoreno
    Jun 1, 2012 at 18:17
28

The printf function is a variadic function, meaning that it has variable number of arguments. Arguments are pushed on the stack before the function (printf) is called. In order for the function printf to use the stack, it needs to know information about what is in the stack, the format string is used for that purpose.

e.g.

printf( "%c", ch );    tells the function the argument 'ch' 
                       is to be interpreted as a character and sizeof(char)

whereas

printf( "%s", s );   tells the function the argument 's' is a pointer 
                     to a null terminated string sizeof(char*)

it is not possible inside the printf function to otherwise determine stack contents e.g. distinguishing between 'ch' and 's' because in C there is no type checking during runtime.

3
  • 9
    but you are completely wrong with your sizeof specifications. First, ch is promoted to an int (or on some platforms to an unsigned) and printf interprets that int as a character. So the size of that parameter "on the stack" is sizeof(int). For the second you are wrong again, it is sizeof(char*) and nothing else. sizeof(int) can (and nowadays often is) different from that. Third, there is not necessary something like a "stack" involved. How these parameters are passed is to the discretion of the platform ABI , and everything may well happen in registers. Jun 1, 2012 at 8:21
  • 2
    @AndersK: "technically" Jens is entirely right. In fact, you might as well drop the word "technically"; he's just plain right. Jun 3, 2012 at 5:24
  • 1
    "A little inaccuracy sometimes saves a ton of explanation" -- Hector Hugh Munro
    – AndersK
    Jun 7, 2012 at 5:43
14

%s says print all the characters until you find a null (treat the variable as a pointer).

%c says print just one character (treat the variable as a character code)

Using %s for a character doesn't work because the character is going to be treated like a pointer, then it's going to try to print all the characters following that place in memory until it finds a null

Stealing from the other answers to explain it in a different way.

If you wanted to print a character using %s, you could use the following to properly pass it an address of a char and to keep it from writing garbage on the screen until finding a null.

char c = 'c';
printf('%.1s', &c);
7
  • 1
    This is not entirely true. using %s for a character can do completely unexpected things since it interprets a character as a pointer to a character, which likely points to an invalid location.
    – Matt
    Jun 1, 2012 at 7:22
  • Just to be clear (since a lot of people confuse these concepts), a string is terminated by a null character, not to be confused with a null pointer. Jun 3, 2012 at 5:21
  • @KeithThompson Just to confuse people: null character '\0' and null pointer are both represented internally as 0 :) Jun 7, 2012 at 0:20
  • 2
    @JuanMendes: No, they can both be represented in source code as 0. Their internal representations can be quite different; a null character is typically 8 bits, while a null pointer is typically 32 or 64 bits. Furthermore, a null pointer's internal representation is not necessarily all-bits-zero (though it very commonly is). Jun 7, 2012 at 5:05
  • 1
    @Keith The language in question is C, and I've never heard of the internal representation being anything other than a 0. That is why you can use any of the following. if (pointer) or if (pointer != 0 ) or if(pointer != NULL ) Also, I think 0s using 8, 16, 32 bits aren't very different. bytes.com/topic/c/answers/213647-null-c Jun 7, 2012 at 18:04
7

For %s, we need provide the address of string, not its value.

For %c, we provide the value of characters.

If we used the %s instead of %c, how would we provide a '\0' after the characters?

4

Id like to add another point of perspective to this fun question.

Really this comes down to data typing. I have seen answers on here that state that you could provide a pointer to the char, and provide a

"%.1s"

This could indeed be true. But the answer lies in the C designer's trying to provide flexibility to the programmer, and indeed a (albeit small) way of decreasing footprint of your application.

Sometimes a programmer might like to run a series of if-else statements or a switch-case, where the need is to simply output a character based upon the state. For this, hard coding the the characters could indeed take less actual space in memory as the single characters are 8 bits versus the pointer which is 32 or 64 bits (for 64 bit computers). A pointer will take up more space in memory.

If you would like to decrease the size through using actual chars versus pointers to chars, then there are two ways one could think to do this within printf types of operators. One would be to key off of the .1s, but how is the routine supposed to know for certain that you are truly providing a char type versus a pointer to a char or pointer to a string (array of chars)? This is why they went with the "%c", as it is different.

Fun Question :-)

2

C has the %c and %s format specifiers because they handle different types.

A char and a string are about as different as night and 1.

1
  • As you mention %s and %c are totally different then pls tell me why the scanf(%s, &ch) and scanf(%c, &ch) statements returns same result.Consider ch is a char like char ch; Feb 22, 2016 at 16:32
2

%c expects a char, which is an integer value and prints it according to encoding rules.

%s expects a pointer to a location of memory that contains char values, and prints the characters in that location according to encoding rules until it finds a 0 (null) character.

So you see, under the hood, the two cases while they look alike they have not much in common, as one works with values and the other with pointers. One is instructions for interpreting a specific integer value as an ascii char, and the other is iterating the contents of a memory location char by char and interpreting them until a zero value is encountered.

2

I have done a experiment with printf("%.1s", &c) and printf("%c", c). I used the code below to test, and the bash's time utility the get the runing time.

    #include<stdio.h>
    int main(){
        char c = 'a';
        int i;
        for(i = 0; i < 40000000; i++){
            //printf("%.1s", &c); get a result of 4.3s
            //printf("%c", c); get a result of 0.67s
        }
        return 0;
    }

The result says that using %c is 10 times faster than %.1s. So, althought %s can do the job of %c, %c is still needed for performance.

1

Since no one has provided an answer with ANY reference whatsoever, here is a printf specification from pubs.opengroup.com which is similar to the format definition from IBM

%c

The int argument shall be converted to an unsigned char, and the resulting byte shall be written.

%s

The argument shall be a pointer to an array of char. Bytes from the array shall be written up to (but not including) any terminating null byte. If the precision is specified, no more than that many bytes shall be written. If the precision is not specified or is greater than the size of the array, the application shall ensure that the array contains a null byte.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.