This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Confusion about the output..
#include<stdio.h>
void main()
{
int i=1,j=-1;
if(printf("%d",i)<printf("%d",j))
printf("%d",i);
else
printf("%d",j);
}
here in this program what is the output & how ?
printf returns the total number of characters written. "-1" is longer than "1". So…
The program invokes undefined behaviour because main has to be defined at least as int main() and return either an int or exit has to be called. Especially the output might not be flushed and thus empty.
Supposing the full output appears, the exact output is undefined because the operands of the < can be evaluated in either order. The rest looks trivial.
The if statement needs to be evaluated to take the branch. For this both of the printf calls (made in if statement) will be executed in either order. This will cause 1 and -1 to be printed in o/p buffer but not guaranteed in which datum will be printed first.
Now once value of if condition is known (false), the printf call inside else branch will be executed. It will print 1 in the buffer. At the end as part of exit handler, the o/p buffer will be flushed. This will cause 1-11 or -111 to be printed on the stdout.
answer is <<< 1 -1 1 >>>. Because printf statement returns int value ie number of character successfully written on screen{In if condition, first printf returns 1 and second printf return 2}. So that if condition becomes 1 < 2. This condition is true. So, execute the true block.
Related
This question already has an answer here:
Is an if statement guaranteed to not be evaluated more than necessary? [duplicate]
(1 answer)
Closed 3 years ago.
Consider the following C code, according to what I have learnt the OR statement should evaluate both the printf. But in actual output I see only "XX". Why is this happening?
#include<stdio.h>
int main() {
int a;
a = (printf("XX")||printf("YY"));
printf("%d\n",a);
a = (printf("XX")&&printf("YY"));
printf("%d\n",a);
}
Output -
XX1
XXYY1
OR operator output is true even if one condition is true. And in this case first printf statement returns true. So there is no need to evaluate the second operand of OR operator.
|| operator evaluates to true if any of the operands is true. So if first operand evaluates to true it doesn't check the second. It only checks second operand if first operand was false.
&& operator evaluates to true only when both the operands are true. It would check the second operand iff the first one is not false.
As stated in the manpage:
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. (See also below under NOTES.)
Say you have a code like:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%d", printf(""));
return 0;
}
This would print 0 just as explained in the manpage.
If your statement is:
printf("") && printf("XX");
It won't print anything because first operand evaluated to 0.
Whereas,
printf("") || printf("YY");
Would print YY.
In your case,
a = (printf("XX")||printf("YY"));
would evaluate printf("YY") only when the first operand failed to print anything.
a = (printf("XX")&&printf("YY"));
Would print XXYY when both printf were successful.
Say you're trying to answer this question "Is it raining or is it after 7 PM?". Once you see that it's raining, you know the answer is "yes". You have no need to check if it's after 7 PM or not.
a = (printf("XX")||printf("YY"));
You asked it an "OR" question. Once it evaluates the first printf, it knows that the answer to your question is yes, so it has no need to evaluate the second part.
The || or OR operator doesn't evaluate its right part if the left part has been determined to be true. Because it does not need to: TRUE || something is "always" true. Even if a potential crash hides on the right. The left part is always checked first.
The return value of printf is not "false" in case of error: it return -1. The "false" value is 0, which would occur if you are trying to print an empty format string, or put a '\0' at the beginning of it. Any value that is not 0 is evaluated as "true" in the general case.
I can't understand why the following code outputs 10.
What I understand is that !printf("0") means !0, which is TRUE. So why doesn't the code print "Sachin"
#include <stdio.h>
int main() {
for (printf("1"); !printf("0"); printf("2"))
printf("Sachin");
return 0;
}
Output
10
let's analyze this side-effect loop statement:
for(printf("1"); !printf("0"); printf("2"))
The first statement is executed, always (init condition), yieiding 1
Then the condition is tested: !printf("0") prints 0, then since printf returns 1 because it just prints 1 character, the negation returns 0 and the loop is never entered because the condition is false right from the start. So neither 2 or Sachin are printed.
Of course, this code isn't practical, almost unreadable. So don't ever do things like this (puts("10"); is a good alternative for instance).
more on the return value of printf (that is often ignored):
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
(from https://linux.die.net/man/3/printf)
If you look at the man printf reference on google, you'll see that this function returns the number of written bytes.
Here your condition is !printf("0"), in other words : "as long as the return of printf is not existing (or equal 0), do something. But you print the character '0' so printf actually return 1 so your condition is false.
Now WHY it prints 10 :
The first printf("1") prints 1.
Your condition is tested at least once, so the second printf("0") occurs one time (it prints 0)
printf("1")
prints 1 and it return number of characters which is 1
printf("0")
prints 0 and it return number of characters which is 1
!1 means !(true) = false so execution will stop and you will see 10 as output.
I know the output of the following code will be 1000 4 but why 1000 4 not 4 1000 ?
int a=1000;
printf("%d",printf("%d",a));
I think you forget, that the printf as argument get's first printed and then the return value gets used as parameter for the outer printf statement! That's why you get:
10004
printf("%d", printf("%d",a));
//^^^^ //^^^^^^ 1. prints 1000
//| //| 2. return value get's used for the outer printf statement
//| 3. prints the return value of the inner printf statement 4
The printf function writes a formatted string to the stdout, and returns the number of characters written. In the beginning it writes the value of a which is 1000; after that 4 is returned, and passed to the outer printf invocation that prints 4, thus the output 10004.
In other words, the arguments must be evaluated before the function call is made; the result of printf("%s", a) is given as an argument to the other printf, thus its value must be evaluated before the outer printf can be called.
The arguments to a function are evaluated before a function is called.
printf("%d",a) is executed first, outputting 1000 then printf("%d",4) is called, outputing 4
printf, on success, returns an int equal to the number of characters written. The internal printf gets called first, printing 1000, and then the return of printf (i.e. 4) gets printed.
You're looking at those 'printfs' as they're laid out in the code.
But when actually printing to the console, what matters is order of execution.
And the order is:
first print 1000,
then print value returned from first call to printf.
Hence 10004.
If you wanted to see 41000 as a result you'd have to know value returned from printf before it was called, and that's just, well...
int a = 5;
#include <stdio.h>
int main() {
printf("%d", printf("hi!") * printf("bye"));
return 0;
}
Output:
hi!bye9
I would like to know how the order in which the output has occurred. Does this mean printf function returns a value?
What is the reason behind inner printf statements being executed first?
This program exhibits unspecified behavior since the order of evaluation of sub expressions is unspecified except where it is specifically defined:
printf("%d",printf("hi!")*printf("bye"));
^ ^
1 2
So either 1 or 2 could be evaluated first and you can not determine which. We can see this from the C99 draft standard section 6.5 Expressions paragraph 3 which says (emphasis mine going forward):
The grouping of operators and operands is indicated by the syntax.74) Except as specified
later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
Yes, printf does have a return value, which is the number of character printed or -1 if there is an error, in this case assuming no error the return value will be 3 for both the inner printfs
The arguments to a function are evaluated before the function is called which is why the inner printfs are executed first, this is covered in section 6.5.2.2 Function calls paragraph 4:
An argument may be an expression of any object type. In preparing for the call to a
function, the arguments are evaluated, and each parameter is assigned the value of the
corresponding argument.81)
The order of the internal printfs is unspecified. Another implementation, the same implementation with different compiler settings, or the same implementation with the same code in a different place might produce byehi!9.
The 9 comes because printf returns the number of characters printed, so the two internal printfs return 3 and the * is the familiar multiplication operator, giving 9.
printf like other IO functions returns the number of bytes printed.
This is done so that you can check if IO went as expected, since file / stream IO errors can happen and sometimes the only way to know that is to check that the right number of bytes got printed.
printf returns the number of bytes written. So the "hi!" and "bye" return 3 each. 3*3 is 9 and that's what is printed
printf() returns the number of characters (bytes) it printed successfully. Please read the man page of printf().
You get hi!bye9 because printf returns the number of bytes output or a negative number if there is an error.
From http://www.cplusplus.com/reference/cstdio/printf/:
On success, the total number of characters written is returned.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
So with:
printf("%d",printf("hi!")*printf("bye"));
First of all the two inner printf calls output hi! followed by bye. Then the return values from those two get interpreted similar to the below (they get multiplied together and output by the outer printf):
printf("%d", 3 * 3);
Note that
printf is function of standard library and most of library functions return something.
It returns the length of what you want to write inside the " ".
If you have a space inside the printf function it will be add it in the length.
Example
#include<stdio.h>
void main()
{
int x;
x=printf("xyz \n");
printf("%d",x);
getch();
}
Here, the first printf statement executes then it returns the value of the
first printf which is 4. Then we store this value in variable x and print the variable. So output will be:
xyz
4
Here value is 4 because we used a space
This is my C code, compiled with gcc.
#include<stdio.h>
int main()
{
int a=1;
switch(a)
{
int x=10;
case 1:
printf("%d\n",printf("%d\b",x));
break;
default:
printf("%d\n",printf("%d\b",x));
}
return 0;
}
printf() is supposed to return the number of elements it printed successfully.
printf("%d\b", x) should have printed 10 by itself(since the \b takes the printing pointer one step behind (to the digit 0 in 10) and there is nothing to print after that.
So it should have just printed 10. That is 2 characters. Now the outer printf would display 2.
The output should have been 102.
The output I actually see is 2.
And in case of nested printfs is the printing pointer position remembered? I mean, if there is a \b in the inside printf , it would take the printing pointer one step behind. And when the control now goes to the outer printf, is that changed position remembered? Will it overwrite over that last character?
printf("%d\b",x)
prints the characters '1', '0' (because x==10) and \b. The \b is a backspace character; if you print to a terminal, it will print 10 and then move the cursor back one column.
A call to printf returns the number of characters it printed; in this case, the result is 3 (yes, '\b' counts as a character).
printf("%d\n",printf("%d\b",x));
The inner printf call works as I explained above, and returns 3. The outer printf call prints "3\n".
So the entire statement will print:
10\b3\n
The '\b' causes the 3 to be replace the 0 on the screen, so the final displayed result (when I run the program on my system) is:
13
If I pipe the output through cat -v, I get:
10^H3
where ^H represents the backspace character.
EDIT :
The question was just edited, and the modified program's behavior is quite different. The switch statement causes control to jump past the declaration int x = 10;, but into the scope in which x is declared. As a result, x is uninitialized when printf is called. This causes undefined behavior, and most likely garbage output (I just got -1217572876^H12). If x happens to be 0, I suppose you'd get 0^H2, which would look like 2.
Whatever you're trying to do, please find a better way to do it.