Thread: How does compiler solve this expression

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    18

    How does compiler solve this expression

    The expressions and their output as seen on Codeblocks 12.11 are -

    int i = 1, x;
    x = i++ + i++ + ++i ++i
    output : x = 7 and i = 5;

    But for the following -

    int i = 1, x;
    x = ++i ++i + i++ + i++
    output : x = 12 and i = 5;

    Can anyone be kind enough to help me know how to solve these types of expressions correctly ?
    Thanks in advance.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    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

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > Can anyone be kind enough to help me know how to solve these types of expressions correctly ?
    Yes, you rewrite them so they no longer exhibit undefined behaviour.

    And read this -> Post and Pre Increment
    Learn that such code has no value because there is no way to figure out what any given compiler is going to do with it (because it's UNDEFINED BEHAVIOUR).

    If your tutor has trouble with this, just send them over here for some re-education.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. initializer expression list treated as compound expression
    By karthikeyanvisu in forum C Programming
    Replies: 7
    Last Post: 02-26-2011, 05:19 PM
  2. Replies: 2
    Last Post: 11-25-2009, 07:38 AM
  3. Replies: 2
    Last Post: 02-04-2008, 02:34 AM
  4. Expected Constant Expression in one compiler
    By jimmyjamesii in forum C++ Programming
    Replies: 3
    Last Post: 12-07-2005, 01:47 AM
  5. Compiler Error: Unsigned vs Signed Integer Expression
    By ChristianTool in forum C++ Programming
    Replies: 6
    Last Post: 05-05-2005, 04:57 PM