简体   繁体   中英

Why does printf give me the following output?

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).

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.

because for second %d there is no matching argument as c=(b=7) is a single expression

Your code is not well-formed: you have only one parameter for printf when you should have two.

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM