Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2007

Tip: Looking for answers? Try searching our database.

The working of a++ in C

Thread view: 
Joyrup - 09 Apr 2007 11:34 GMT
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.
Mark Holland - 09 Apr 2007 11:42 GMT
> Can anyone explain the output of the following piece of code in C:
>
[quoted text clipped - 8 lines]
>
> 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
Patricia Shanahan - 09 Apr 2007 11:47 GMT
> Can anyone explain the output of the following piece of code in C:
>
[quoted text clipped - 8 lines]
>
> 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.