precedence problem

This is a discussion on precedence problem within the C Programming forums, part of the General Programming Boards category; Code: # 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 ...

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    2

    Question precedence problem

    Code:
    # 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
    Location
    Singapore
    Posts
    23,826
    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
    Location
    Long Beach, CA
    Posts
    5,784
    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
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,664
    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, 10:37 PM
  2. need some help for precedence
    By timhxf in forum C Programming
    Replies: 2
    Last Post: 12-15-2006, 05:19 PM
  3. precedence problem
    By timhxf in forum C Programming
    Replies: 3
    Last Post: 12-13-2006, 08: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, 11:05 AM

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