Why does C's printf format string have both

前端 未结 11 631
孤城傲影
孤城傲影 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条回答
  •  Happy的楠姐
    2020-12-02 15:49

    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.

提交回复
热议问题