0
int main()
{   
    int a, b, c;
    a = 10;
    b = 20;
    c = printf("%d", a) + ++b;
    printf("\n%d", c);
}

The output of the above program is 23 it seems but i dont know how it is obtained. Can anyone have an idea about it?

0

3 Answers 3

4

printf has a return value, which is the total number of characters it prints.

The statement printf("%d",a) will print 10, which means the return value of printf here is 2.

The rest is easy:

c=printf("%d",a)+ ++b;

c will have a value of 2 + 20 + 1, which is 23.

Sign up to request clarification or add additional context in comments.

3 Comments

Excellent explanation. It's also worth pointing out that b is 21 at the end of this function. It got incremented on this line: c=printf("%d",a)+ ++b;
@user814064 Right, that's the side effect. Your answer is correct but it seems that you have deleted it.
You were first by a few seconds -- instead I voted up your post.
1

Here the output will be two different integers,for two different printf statements . For the first printf statement the code prints 10, then when this printf statement participate in some assignment statement , it is treated as the number of characters it is printing i.e. 2 here. Then it is added to ++b i.e. 21 (PRE-INCREMENTED) . So the output is 23(2 + 21) . The whole output looks like this :

10
23

Comments

0

printf returns the number of characters printed as an integer. So as you are printing 10 it will return 2. So now

c=printf("%d",a)+ ++b; will become

c=2+ ++b;

since b with a value of 20 is pre-incremented this will become

c=2+21 Therefore c=23

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.