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??
printfreturns the number of character writtenputsreturns a non-negative value in case of success
As a result :
- In the first code,
printfreturns a positive value which evaluates totrue, theelsebranch is never executed, thus printingABConly - In the second code,
putsmost likely succeeds and returns 0 which evaluates tofalse, theelsebranch gets executed, thus printing bothABCandXYZ
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.
加载中,请稍侯......
精彩评论