explain this nested printf statement - c

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

Related

How does the following code works printf("%c")?

I wanted to know how the following program is working?
#include <stdio.h>
int main(void) {
while(1){
if(printf("%d",printf("%c")))
break;
else
continue;
}
return 0;
}
I did not know how the part printf("%c") is working and therefore the whole program.I am aware of writing something like printf("%c", 'a'); like that but how is it working without providing the character to be printed? My question is what does the following program prints and how does it prints so?
I have tried to run the program, sometimes it prints nothing, but sometimes it is printing some random character followed by 1. I am not able to get how it is working, can someone please explain what is going behind the code and how it is printing that random characters, and why there is one at the end?
Here are some output I am getting
Welcome to Undefined Behavior. You fail to have sufficient number of arguments for the format you specify, e.g.
C11 Standard - 7.21.6.1 The fprintf function(p2) "If there are insufficient arguments for the format, the behavior is undefined." 7.21.6.1(p9) "If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."
A cool wrong program you have.
printf("%c") attempts to print a single character that is supposed to be the second parameter. However, since you have never passed the second parameter, the function prints whatever is in the register that was supposed to have the second parameter. In other words, some random character. However, it prints one character and returns 1: the number of characters printed.
That 1 is in turn printed by printf("%d",printf("%c")). Now you have a random character followed by 1, and since the outer printf also prints one character, it returns 1.
Finally, if(printf("%d",printf("%c"))) interprets that later 1 as true and breaks the loop.
This is about format bugs.
Look at this code, when execute printf("%d", 123), the program will push number 123 onto the stack, and then push string "%d", when printf meets "%d", it will read the value on the top of the stack, so printf find the number 123.
Now look at this code, printf("%c"), program will push string "%c" onto the stack, and try to read value on the top of the stack, you haven't push a value for printf, so printf will still find value, but the value is random, so you might get a random value.

How do I explain the output of this simple C code?

#include<stdio.h>
int main()
{
int i=10;
printf("%d",printf("%d",i));
return(0);
}
Output in Turbo C
102
I am a beginner. So can you explain how this code works?
The documentation for printf states that it will return an integer that represents the number of characters written to the output stream.
That means you can use the return value of printf to satisfy a %d format specifier in another call to printf, and the second (outer) call will print out the number of characters written in the first call.
i is equal to 10, so the first call to printf outputs the number 10 and returns 2 (number of characters in the string "10"), which is passed to the second call to printf, which prints 2, giving you the final output 102.
Let's take apart the top level statement that produces the output:
printf("%d",printf("%d",i));
We have a function call of printf at the top level, passing two arguments to the function
The first argument of the top-level printf is the format string "%d"
The second argument of the top-level printf is the result of invoking printf("%d",i)
The argument of top-level printf, i.e. printf("%d",i), needs to be evaluated prior to making the call. The expression has a value, and a side effect. The side effect is printing "10" to the output, and the value is the number of characters printed, i.e. 2.
Since the arguments are evaluated prior to making a call, the printf("%d",i) is invoked first, producing the output 10. Now the top-level printf is invoked, and it produces the output 2, completing the "102" sequence that you see.
printf() is a C function. It returns an int value equal to the number of bytes it prints.
In your case, the INNER printf printed "10", so it wrote 2 bytes and will return 2.
The OUTER printf will therefore print "2".
Final result: "102" ("10" of the INNER followed by "2" of the OUTER).
Quoting C11, chapter ยง7.21.6.1
The fprintf function returns the number of characters transmitted, or a negative value
if an output or encoding error occurred.
In your case, the inner printf() call is the argument to the outer printf(), so the inner function call will be executed, as per the rule of function parameter evaluation.
So, in your case, first the inner printf() executes, printing the value of i, i.e., 10 (2 characters) and the return value of the printf() call is used as the argument to the %d format specifier in outer printf(), printing 2.
As there is no visual separator present, you see the outputs adjacent to each other, appearing as 102.

Why is printf() printing out in this code?

This simple code is puzzling me - I am deliberately printing out more integers than I passed to printf. I expected an error. I got weird numbers - where are they coming from?
#include <stdio.h>
/* learn arrays */
void main(){
int pout;
pout = 6;
printf("%i %i %i\n%i %i %i\n%i %i %i\n", pout);
}
One example of the output:
6 608728840 0
-885621664 -885543392 608728816
0 0 -889304251
The single digits do not change with repeated runs, but the large integers do.
It's one of printf string format vulnerability. You are trying to call more argument than there actually are, so printf takes whatever he can on the stack.
It was (and still is) very used to exploit programs into exploring stacks to access hidden information or bypass authentication for example.
Viewing the stack
printf ("%08x %08x %08x %08x %08x\n");
This
instructs the printf-function to retrieve five parameters from the
stack and display them as 8-digit padded hexadecimal numbers. So a
possible output may look like:
40012980 080628c4 bffff7a4 00000005 08059c04
See this for a more complete explanation.
Because it's undefined behavior. If the number of specifiers is larger than the number of matching parameters or their types are incompatible, the behavior is undefined.
This qoute is from the c11 standard draft
7.21.6.1 The fprintf function
The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fprintf function returns when the end of the format string is encountered.
If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
I highlighted the relevant parts making them bold.
The int reserves some RAM but you didn't wrote anything in so it shows you what numbers are random somewhere in your RAM

Unexpected output on using puts() and printf() function

I'm trying to run a basic code on my Dev C++ IDE, but it gives an expected output-
printf("%d", printf("stackoverflow1"));
printf("%d", puts("stackoverflow2"));
puts(printf("stackoverflow3"));
the expected output should be:
stackoverflow114stackoverflow2
14stackoverflow314
but the output I'm getting is:
stackoverflow114stackoverflow2
0stackoverflow3
Can someone explain the inconsistency in the output ? I know that puts return a non negative number but why I'm getting a '0' everytime. Also in the last statement why is puts not printing the no of characters printed by printf ?
puts(), as you mentioned, only has to return a non-negative number on success. This means the compiler you are using gets to decide what is returned, as long as it follows this. Your compiler appears to have chosen 0.
as 2501 mentioned, passing puts(const char * p ) an int is illegal, your compiler should have complained about it. puts() is supposed to print starting from p until it reaches a '\0' char, so the input has to be a pointer to a '\0' terminated string
You have undefined behavior. puts() takes a const char* argument yet you pass it an int.
puts(printf("stackoverflow3"));
Enable warnings on your compiler and your code won't even compile.
printf("%d", printf("stackoverflow1"));
Printf returns an int (how much chars are printed = 14). Because the arguments of the outer printf have to be evaluated before the outer one can be evaluated, the string printed will bee "stackoverflow114"
printf("%d", puts("stackoverflow2"));
puts returns a "nonnegative value" (this is the only guarantee, the standard gives to you). In your case the nonnegative value is the int 14. The string "stackoverflow2\n" is printed by puts and the 14 is printed by printf.
puts(printf("stackoverflow3"));
puts takes an const char* as an argument and printf returns the number of chars printed (which is 14, again). Since puts takes a pointer, it may interpret the memory at address 14 as a string and output it (it might cancel compilation, too - most compilers will be 'glad' and cast this for you, along with a warning). This string seems to be empty (this might be sort of random). This line thus only prints "stackoverflow3" (in your case) and the outer puts only prints a random string (in your case "").

printf related Query

Here is a simple one line program using printf :
void main()
{
printf("%d%d",printf("Cis"),printf("good"));
}
Output :
goodCis34
How can this output be explained ??
The reason why good and Cis are printed first is because the parameters need to be evaluated before the top-level printf() can be called.
Then the return values are printed out.
Note that C does not specify the order of evaluation of the parameters. There are no sequence points within the statement. Therefore the order is undefined. And the result can appear in any order. (hence why they appear to be evaluated out-of-order in this case)
Printf returns the number of characters printed. "Cis" is 3 characters, "good" is 4.
It also writes the output to the stream.
So "Cis" is printed, and returns 3, "good" is printed, and returns 4. The order of the execution of these is not guaranteed, so it is undefined as to whether you will get "Cisgood" or "goodCis".
Then the outer printf string is evaluated, and the output "34" is returned.
printf("%d%d",printf("Cis"),printf("good"));
At first, the arguments are evaluated.
printf("good") is evaluated first. "good" is printed and 4 (number of chars written) returned. Then, printf("Cis") is evaluated. "Cis" is printed and 3 is returned. after evaluation, the function becomes like this:
printf("%d%d", 3, 4);
So, 34 is printed.
It's evaluating right to left, meaning good is printed first. Then it evaluates the second part, Cis.
Finally, when doing the left-most operation, it is using the respective lengths of both of those strings to fill in the %d replacements.
printf and its family return the number of characters printed. In your case, it's just the length of the strings. However, the order in with the arguments are evaluated is unspecified. In your case, the second argument to the outer printf happens first. It could be completely different.

Resources