Post and Pre increment Associativity example

This is a discussion on Post and Pre increment Associativity example within the C++ Programming forums, part of the General Programming Boards category; Hi all, I wrote the following code n c++ Code: #include <stdio.h> #include <iostream> #include <conio.h> using namespace std; int ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    1

    Post and Pre increment Associativity example

    Hi all,
    I wrote the following code n c++

    Code:
    #include <stdio.h>
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    int main (){
            int x,y;
            x=5;
            y=++x*++x;
            printf ("\ny=%d %d",y,x);
            x=5;
            y=x++*++x;
           printf ("\ny=%d %d", y,x);
            x=5;
            y=x++*x++;
            printf ("\ny=%d %d", y,x);
            cin.get();
            return 0;
            
    
    }
    and got the following output:
    49 7
    36 7
    25 7

    going by the right to left operator associativity of the preincrement and the fact that the post increment effects take place after the expression is calculated the last two results are understandable.
    But in the first result it can only be possible if the multiplication was 7*7. I think this should not be happening and the result must be 42 (7*6).
    In fact when I ran the program for ++x*++x*++x , I got 392 (8*7*7) and so on for any more extensions.
    Am I missing something here?
    Any help would be appreciated

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,760
    This is undefined behavior.
    Within a single expression without a sequence point, you are allowed to modify an object only once.


    Jim

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,754
    Read Stroustrup's answer to the FAQ What's the value of i++ + i++?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lost on Queues - Help GREATLY appreciated.
    By TetsuoShima in forum C Programming
    Replies: 3
    Last Post: 07-13-2010, 05:35 AM
  2. pre & post increment need help
    By zing_foru in forum C Programming
    Replies: 6
    Last Post: 10-09-2009, 12:14 PM
  3. New compiler - Weird errors -,-.
    By Blackroot in forum C++ Programming
    Replies: 8
    Last Post: 08-27-2006, 07:23 AM
  4. post vs pre increment
    By xddxogm3 in forum C Programming
    Replies: 13
    Last Post: 03-19-2004, 04:07 PM
  5. Post increment and pre increment help
    By noob2c in forum C++ Programming
    Replies: 5
    Last Post: 08-05-2003, 03:03 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21