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
    22,306
    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.
    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

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,676
    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,657
    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, 12:37 PM
  5. precedence
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 03-17-2002, 12:05 PM

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