cant understand this code

Discussion in 'C Programming' started by ravindradivekar, Feb 24, 2014.

  1. Hi everyone,
    can someone explain this code to me?

    a=1, b=1, c=1;

    c = --a&&b++;

    After this statement b=2 according to me, but the result is b=1;

    ravindradivekar, Feb 24, 2014
    1. Advertisements

  2. ravindradivekar

    Ike Naar Guest

    The && operator does not evaluate its right operand if the left
    operand equals zero.
    Ike Naar, Feb 24, 2014
    1. Advertisements

  3. ravindradivekar

    Kaz Kylheku Guest

    The right hand side of the && operator is only evaluated if the left hand side
    yields true (nonzero).

    The left hand side is --a . This means "decrement a and yield the new value".
    The new value is zero.

    Since the value left of && is zero, the right hand side is not evaluated.
    And so the action b++ never happens.
    Kaz Kylheku, Feb 24, 2014
  4. ravindradivekar

    James Kuyper Guest

    That very compact statement is equivalent to the following expanded version:

    a = a - 1;
    if(a != 0)
    if(b != 0)
    c = 1;
    c = 0;
    b = b + 1;
    c = 0;

    Do you understand why that results in b==1? Do you understand why this
    expanded version is equivalent to your more compact code?
    James Kuyper, Feb 24, 2014
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.