开发者

puts vs printf in the following code?

#include "stdio.h"
#include "conio.h"

int main(void)
{

        if(printf("ABC"))
        {

        }
        else
        {
            printf("XYZ");
        }
        _getch();
        return 0;
}

output : ABC

----------------------------------------------------------------------------------------

#include "stdio.h"
#include "conio.h"

int main(void)
{

        if(puts("ABC"))
        {

        }
        else
        {
            printf("XYZ");
        }
        _getch();
        return 0;
}

output : ABC XYZ 

(IDE : MSVC++) what is the difference between printf and puts in if statement in 开发者_开发问答above 2 programs??


  • printf returns the number of character written
  • puts returns a non-negative value in case of success

As a result :

  • In the first code, printf returns a positive value which evaluates to true, the else branch is never executed, thus printing ABC only
  • In the second code, puts most likely succeeds and returns 0 which evaluates to false, the else branch gets executed, thus printing both ABC and XYZ

As pointed out by others, puts will also append a newline while printf won't.


puts() appends a newline and returns a different value (non-negative [which could include 0] on success, -1 on failure).


printf returns the number of characters printed (so when successfully printing a non-empty strong, the return value is not 0 and thus true in a boolean context), while puts simply returns a non-negative number to indicate success (which might very well be 0 aka false).


printf on success returns the number of characters written which in your case is 3.

puts on success returns a non-negative number which could also be 0. Looks like it returned a 0 in your case making the else part to execute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜