``````main()
{

int a=5;
a=++a + ++a;
printf("%d",a);
}``````

the output is 14..how come?

## All 8 Replies

The value of a is used after it is incremented twice ie 7.

but such expression behaviours are not defined by standards.

ok..then
c=++a + ++a + ++a
should give the output c=24
but its c=22.
???

ok..then
c=++a + ++a + ++a
should give the output c=24
but its c=22.
???

Undefined behavior is the Schrödinger's cat of programming. The result of an undefined expression could be anything until you actually run it, and the result you get in practice depends on too many factors to be predictable. Results that aren't predictable and can't be controlled are undesirable, right?

ok i get it. thanks a lot

You are all wrong -- except for deceptikon. The value cannot be determined with any surety. See this

thanks a lot

``````main()
{

int a=5;
a=++a + ++a;
printf("%d",a);
}``````

the output is 14..how come?

The explanation is only weird for the first time. i.e. ++a + ++a = 14
But if you debug and see the value of a, it will be 7 and after that if u add another ++a to it the answer is 22 and the final value of a is 8 and it increments by 1 for everytime you add ++a

i.e.
++a + ++a = 14 final value of a=7
++a + ++a + ++a = 22 final value of a=8
++a + ++a + ++a + ++a = 31 final value of a=9
++a + ++a + ++a + ++a + ++a = 41 final value of a=10 and so on....

So lets say you add one ++a to to the first expression and you get the result 22 i.e. 14+8=22 and it continues like this.

The reason for making ++a + ++a = 14 is:
Lets say you want to print the value of a and since there are 2 values of a so the makers of 'C' decided to give both the a's the final value i.e. 7 in this case and added them to give 14.

I hope I am able to give some justification to it.

commented: Completely wrong and misleading! -4

The explanation is only weird for the first time. i.e. ++a + ++a = 14

So lets say you add one ...

Lets say you want to print the value of a ...

I hope I am able to give some justification to it.

No, you gave no justification for anything. You didn't bother to learn anything from the rest of the thread, specifically:

...but such expression behaviours are not defined by standards.
http://c-faq.com/expr/ieqiplusplus.html

The result of an undefined expression could be anything until you actually run it, and the result you get in practice depends on too many factors to be predictable. Results that aren't predictable and can't be controlled are undesirable, right?

The value cannot be determined with any surety. See this

What part of these posts did you not understand?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.