The working of a++ in C

J

Joyrup

Can anyone explain the output of the following piece of code in C:

void main( )
{int a=1, b;
b=(++a)+(++a);
printf("a=%d, b=%d", a, b);
}

Output:
a=3, b=6

Can anyone explain why b=6 here and NOT 5 as expected.
 
M

Mark Holland

Joyrup said:
Can anyone explain the output of the following piece of code in C:

void main( )
{int a=1, b;
b=(++a)+(++a);
printf("a=%d, b=%d", a, b);
}

Output:
a=3, b=6

Can anyone explain why b=6 here and NOT 5 as expected.

You are modifying the value of a variable (in this case a) twice
between sequence points. According to the C++ standard this is
undefined behaviour, meaning anything can happen. (i.e. Your program
is invalid). Hence you get those "unexpected" results.
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15

However, one does wonder why you are posting to a Java newsgroup with
this topic? Are you trying to contrast this behaviour with Java? In
which case it is worth noting that this behaviour is indeed specified
in Java and produces the expected value of 5.

Mark
 
P

Patricia Shanahan

Joyrup said:
Can anyone explain the output of the following piece of code in C:

void main( )
{int a=1, b;
b=(++a)+(++a);
printf("a=%d, b=%d", a, b);
}

Output:
a=3, b=6

Can anyone explain why b=6 here and NOT 5 as expected.

If I were writing in a C newsgroup, I don't think would not have any
particular expectation for the result of b=(++a)+(++a).

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top