C, C++ and Java Expression same but results different

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anwar7517525
    New Member
    • Dec 2007
    • 3

    C, C++ and Java Expression same but results different

    In Turbo C 3.0
    #include<conio. h>
    #include<stdio. h>
    void main(void)
    {
    int x=-250;
    x = --x + --x + --x;
    printf("%d",x);
    getch();
    }//it gives: -259

    In Visual C++ 6.0
    #include<iostre am>
    using namespace std;
    void main(void)
    {
    int x=-250;
    x = --x + --x + --x;
    cout <<x;
    }//it gives: -257

    In Java
    class Test
    {
    public static void main(String abc[])
    {
    int x=-250;
    x = --x + --x + --x;
    System.out.prin t(x);
    }//it gives: -256
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    Cool.

    Next time you post, please be sure to follow the Posting Guidelines which ask that you do things like use code tags, etc...

    Comment

    • mschenkelberg
      New Member
      • Jun 2007
      • 44

      #3
      Originally posted by anwar7517525
      In Turbo C 3.0
      #include<conio. h>
      #include<stdio. h>
      void main(void)
      {
      int x=-250;
      x = --x + --x + --x;
      printf("%d",x);
      getch();
      }//it gives: -259

      In Visual C++ 6.0
      #include<iostre am>
      using namespace std;
      void main(void)
      {
      int x=-250;
      x = --x + --x + --x;
      cout <<x;
      }//it gives: -257

      In Java
      class Test
      {
      public static void main(String abc[])
      {
      int x=-250;
      x = --x + --x + --x;
      System.out.prin t(x);
      }//it gives: -256


      I think you mean they give 75* not 25* but anyway

      It is based on the order of operations specific to compilers

      If Turbo does give 759 and not 259 then it will always perform the decrement operation first on before doing anything resulting in -253 + -253 + -253

      In Visual C++ they do the same thing but only look at 2 items at a time so it will take the last items, do the decrements then add them together so you have -250 decremented, then -251 decremented resulting in -252 + -252 giving -504. -504 is then added to x decremented which is -504 + -253 giving -757

      Java decrements then adds so x is decremented to -251 and added to that decremented -252 which is added to that decremented -253 resulting in -756

      Parenthesis would help resolve how you want it evaluated

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by Anwar7517525
        x = --x + --x + --x;
        Your results are indeterminate.

        Variables can be modified only once in a statement. More than that and your results are unpredictable.

        Comment

        Working...