简体   繁体   中英

How do I determine why my program is outputing an unexpected value?

Why does this program output "41"?

#include <stdio.h>

int main(){
    int a = 0;
    a = printf("4");
    printf("%d", a);
    return 0;
}

The function printf returns the number of outputted characters.

From the C Standard (7.21.6.3 The printf function)

3 The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

So at first in this statement

a = printf("4");

there is outputted the character '4' stored in the string literal "4" and a is assigned with the value 1 because only one character was transmitted and then in the next call

printf("%d", a);

there is outputted the integer 1 stored in the variable a in the preceding statement.

You could get the same result using one statement the following way

printf( "%d", printf( "4" ) );

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