Reputation: 87
I'm working through The C Programming Language book and understand that if I had a line of code like:
int c;
printf("%d", c = 5);
I will get an output of 5, because (c = 5) has the value of the RHS value of the assignment.
In a similar way:
int c;
printf("%d", c = getchar(c));
will give me the integer value of the first char in the stdin buffer, because (c = getchar()) has the value of the RHS which is just the getchar() function.
I was playing around with it and used the following using VS Code:
#include <stdio.h>
int main()
{
int c, b;
printf("%d\t%d", c = (b = 7));
}
The output I get is:
7 6422376.
and not
7 7
Why is this? The second output is the same value (6422376) no matter whatever value I use for b, eg (b = 3).
Upvotes: 1
Views: 118
Reputation: 1
#include <stdio.h>
int main()
{
int c, b;
printf("%d\t%d", c = (b = 7),b);
}
you can try these code to print the value of b. There is only one parameter in your printf function, and 2 format specifier, so compiler assumes any garbage value for another %d.
Upvotes: -1
Reputation: 11
because for second %d there is no matching argument as c=(b=7) is a single expression
Upvotes: 1
Reputation: 1112
Your code is not well-formed : you have only one parameter for printf when you should have two.
Upvotes: 0
Reputation: 409136
The expression c = (b = 7)
is a single expression, and as such a single argument passed to the printf
function.
The second %d
format specifier leads to undefined behavior as there is no second argument matching it.
Upvotes: 5