Why does C's printf format string have both

前端 未结 11 640
孤城傲影
孤城傲影 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:34

    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
        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.

提交回复
热议问题