Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `\` affecting the return value of printf? [duplicate]

Tags:

c

printf

With reference to the answer given here, what output one must expect from the following code:

#include<stdio.h>

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

It gives the output:

65
4

But to me it would seem that it should give this:

65
3

Why is the output 65 4?

like image 953
beta_me me_beta Avatar asked Dec 08 '22 10:12

beta_me me_beta


1 Answers

You are printing 4 characters <tab>, \n, 6, and 5, so the result you're getting makes total sense.

Notice that the \ at the end of this printf("%d\n",printf("%d\ line, will include all of the indentation of the next line into the formatting string. This indentation was originally a <tab> character when you ran your file.

The reason why some people are reporting the ouput of 65 7 is that StackOverflow changes all tabs in the pasted code into 4 spaces, so the code they copied from your question was not the same code you ran on your machine.

See this demo, which shows the existance of the <tab> in the output (online version):

#include<stdio.h>

int main()
{
    int a=65;
    printf("%d\n",printf("%d\
    <--tab here\n",a));
    return 0;
}

Output:

65 <--tab here
15

If you remove the weird, totally unnecessary, and obviously error prone line continuation, it will print the expected output just fine:

#include<stdio.h>

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

Output:

65
3
like image 146
ruohola Avatar answered Dec 26 '22 20:12

ruohola