Re: [Dev-C++] Question about increment..
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Reid T. <Rei...@at...> - 2012-09-20 20:25:08
|
On Thu, 2012-09-20 at 12:54 -0400, Mani wrote: > Hi, > > I recently to try some toy things in DevC++ (version I am using is 4.9.9.2) > > The code I had was this: > > int a = 1, b = 2; > int c = a++ + b++ + a + b; > > cout << "a = " << a << endl; > cout << "b = " << b << endl; > cout << "c = " << c << endl; > > I expected the c value to be 8 (by operator precedence, ++ has higher > precedence than +, so do in order: > a++, then b++ > then do (a++ + b++) > then add the previous result and a > then add the previous result and b > > but the answer I got was 6.. > > what might be the reason for this..?? > > thanks, murali > > ------------------------------------------------------------------------------ > Everyone hates slow websites. So do we. > Make your web apps faster with AppDynamics > Download AppDynamics Lite for free today: > http://ad.doubleclick.net/clk;258768047;13503038;j? > http://info.appdynamics.com/FreeJavaPerformanceDownload.html > _______________________________________________ > Dev-cpp-users mailing list > Dev...@li... > TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm > https://lists.sourceforge.net/lists/listinfo/dev-cpp-users [16:06:54][94s] rthompso@raker2> ~ $ cat helloworld.c #include <stdio.h> #include <stdlib.h> int main(void) { int a = 1, b = 2; int c = a++ + b++ + a + b; printf("c is %d\n", c); a = 1; b = 2; c = ++a + ++b + a + b; printf("c is %d\n", c); return 0; } [16:07:01][0s] rthompso@raker2> ~ $ cat Hello.cs using System; class Program { static void Main() { int a = 1, b = 2; int c = a++ + b++ + a + b; Console.WriteLine(c); Console.WriteLine("Hello world!"); a = 1; b = 2; c = ++a + ++b + a + b; Console.WriteLine(c); Console.WriteLine("Hello world!"); a = 1; b = 2; c = a++ + b++; int d = c + a + b; Console.WriteLine(d); } } [16:07:26][0s] rthompso@raker2> ~ $ ./a.out c is 6 c is 10 [16:07:30][0s] rthompso@raker2> ~ $ mono Hello.exe 8 Hello world! 10 Hello world! 8 gcc C n++ -> increment after use > int a = 1, b = 2; > int c = a++ + b++ + a + b; c = 1 + 2 + 1 + 2 c = 6 ++n -> increment before use > int a = 1, b = 2; > int c = ++a + ++b + a + b; c = 2 + 3 + 2 + 3 c = 10 mcs csharp evidently creates an incremented copy and uses it with the original value > int a = 1, b = 2; > int c = a++ + b++ + a + b; c = 2 + 3 + 1 + 2 c = 8 ++n -> increment before use > int a = 1, b = 2; > int c = ++a + ++b + a + b; c = 2 + 3 + 2 + 3 c = 10 a = 1; b = 2; c = a++ + b++; int d = c + a + b; c = 5 d = 5 + 1 + 2 d = 8 |