Thread: Post and Pre increment Associativity example

  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
    4,632
    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
    28,413
    Read Stroustrup's answer to the FAQ What's the value of i++ + i++?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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, 05: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