Thread: Preincrement and Logical Operator

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    8

    Preincrement and Logical Operator

    Hi,

    I have the following code snippet:

    Code:
    #include<stdio.h>
    int main()
    {
    int x,y,z;
    x=y=z=1;
    z= ++x||++y&&++z;
    printf("x=%d y=%d z=%d\n", x,y,z);
    return 0;
    }
    And the output is :
    x=2 y=1 z=1

    I cannot understand why y is 1, even if it is pre incremented?
    Can any one help?

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    z= ++x||++y&&++z;
    In the red part of this line of code, you're assigning an incremented x to z. So that part of the line evaluates to TRUE or 1.

    So the blue part, is never executed.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,403
    By the way, if x has the value of -1 and y does not have the value of -1, that statement actually results in undefined behaviour since you would be incrementing z and assigning the result to z, with no sequence point in between.
    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

Popular pages Recent additions subscribe to a feed