Why does C's printf format string have both

前端 未结 11 641
孤城傲影
孤城傲影 2020-12-02 15:17

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

I know that %c represents a single character and %s repre

11条回答
  •  孤城傲影
    2020-12-02 15:52

    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.

提交回复
热议问题