Thread: Incrementation

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    30

    Incrementation

    Hello,

    In this code, I got that dgets 0 value but one point Im in trouble. Even a and c is incremented, why wasnt b incremented like them?

    Code:
    #include <stdio.h>int main (void) {
    	
    	int a=0, b=0, c=0, d;
    	d = a++ && b++ || c++;
    	printf("%d%d%d%d", a, b, c, d);
    }
    
    
    
    
    output is 1010.

  2. #2
    Registered User
    Join Date
    Feb 2015
    Posts
    33
    Line 4 doesn't make sense, I think what you're trying to do is
    Code:
    a++;
    b++;
    c++;
    if(something)
        d = (a+b);
    else
        d = c;
    In line 4 you're basically saying

    Code:
    d = (a++) AND (b++) OR (c++)
    Also I find it easier to separate #include <stdio.h> and int main() with newlines, i think it's a convention in C

  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
    First let's put the implied parentheses of operator precedence in
    d = ( a++ && b++ ) || c++;

    The next thing you need to understand is the short-circuit evaluation of the boolean operators && and ||
    Recall that for &&, if the left hand side is false, the right hand side is NOT evaluated.

    So in a++ && b++, a is 0 (false), but the side effect of a++ happens (making a=1)
    However, since the left hand side of the && is false, b++ doesn't happen.

    So now we have ( false ) || c++

    The same logic applies to || as well, the right hand side of || is only evaluated if the left hand side is false (which it is).
    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. Incrementation Questions
    By Zachary May in forum C Programming
    Replies: 10
    Last Post: 03-22-2013, 01:33 AM
  2. Incrementation in conditionals
    By Niels_M in forum C Programming
    Replies: 2
    Last Post: 07-20-2010, 11:19 AM
  3. Pointer incrementation
    By newbie30 in forum C Programming
    Replies: 6
    Last Post: 08-14-2009, 09:51 PM
  4. string::size_type incrementation
    By cunnus88 in forum C++ Programming
    Replies: 2
    Last Post: 05-01-2007, 10:59 PM