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 writtenputs
returns a non-negative value in case of success
As a result :
- In the first code,
printf
returns a positive value which evaluates totrue
, theelse
branch is never executed, thus printingABC
only - In the second code,
puts
most likely succeeds and returns 0 which evaluates tofalse
, theelse
branch gets executed, thus printing bothABC
andXYZ
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.
精彩评论