Thread: precedence problem

  1. #1
    Registered User
    Join Date
    Jun 2011

    Question precedence problem

    # include <stdio.h>
    int main()
    int i=-3,j=2,k=0,m;
    m=++i || (++j && ++k) ;
    printf("%d %d %d %d\n",i,j,k,m);
    return 0 ; 
    Output: -2 2 0 1

    why not expression (++j && ++k) is executing.Precedence of ( ) is higher than || (even though left hand side of OR is TRUE).

    Please clear my doubt.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Recall the short circuit evaluation of the || and && operators.

    Also, note that precedence is about grouping, not order of evaluation, even though they are sometimes related.
    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
    Registered User
    Join Date
    Nov 2010
    Long Beach, CA
    What laserlight said. Also, logical || and && operators introduce a sequence point: Sequence point - Wikipedia, the free encyclopedia. Due to this, the left side is always fully evaluated and all side effects settled out before the right side is touched.

  4. #4
    Join Date
    Dec 2007
    And anyone that would use code like that in a production environment would be shot at dawn.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Operator Precedence Problem
    By bthomson900 in forum C Programming
    Replies: 3
    Last Post: 11-10-2010, 11:37 PM
  2. need some help for precedence
    By timhxf in forum C Programming
    Replies: 2
    Last Post: 12-15-2006, 06:19 PM
  3. precedence problem
    By timhxf in forum C Programming
    Replies: 3
    Last Post: 12-13-2006, 09:10 AM
  4. precedence
    By modec in forum C Programming
    Replies: 3
    Last Post: 05-22-2003, 11:37 AM
  5. precedence
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 03-17-2002, 12:05 PM