-2
$void main()
{
int a=10,c;
c= ++a + ++a;
printf("%d",c);
}

this program Actualy Print Value Of c=24 but By Calculation we can say it should be c=23 ,how it possible?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

Your program has a bug -- you modify the same variable twice without an intervening sequence point. Fix the bug and the mystery will go away.

A very deep understanding of not just how the language works but how compilers work is required to understand why buggy code happens to do what it happens to do. I would just suggest not writing buggy code and, when you find a bug, simply fix it instead of trying to understand precisely why and how it broke.

My advice to you is to stop. You learned the right lesson -- code that triggers undefined behavior is unpredictable and frequently doesn't do what you might expect it to do. That's all you need to know about UB until you're an expert at using the language correctly.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • This code for sure need to be fixed in production, but as long as one is still asking this kind of question, he's no where close to writting code in production. it's good to figure it out as brain exercise and understand language featuers – miushock Mar 21 '14 at 06:08
  • 1
    Honestly, I don't think so. I've seen it cause people to think that they can expect this kind of code to behave in a particular way and then cause them more problems when it doesn't. There are a lot of ground rules you have to understand before the answers to these kinds of questions will do you more good than harm. – David Schwartz Mar 21 '14 at 06:09
  • I'm sorry for people think they can actually code like this in real life, I'm 100% agree you on that. I still feel it's fine for first/second year colleague students, new to c, to figure out what's going on here tho. – miushock Mar 21 '14 at 06:11
  • 1
    So long as someone carefully explains the ground rules to them and probably repeats it several times. But certainly someone who doesn't even understand that this code's behavior is unpredictable is nowhere near ready to try to understand why it happens to do what it happens to do under various different conditions. – David Schwartz Mar 21 '14 at 06:13
  • 1
    You're right, I withdraw what I said – miushock Mar 21 '14 at 06:27
0
'++' > '+'

Here post increment operation is done before.Since you gave it two times if does post increment two times so the value of 'a' becomes 12 and adds it up (12+12).So the final value is 24.

RKC
  • 1,834
  • 13
  • 13