Not getting the expected output in this program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AmberJain
    Recognized Expert Contributor
    • Jan 2008
    • 922

    #1

    Not getting the expected output in this program

    Hello everyone,
    Newbie here, PLZ HELP.......

    This is what I coded (it's very very simple, still I'm facing problem with this code) --------->
    _______________ _______________ _______________ _______________ _____
    [code=c]#include<conio. h>
    #include<stdio. h>
    int main()
    {
    int i=0;
    int j=1;
    clrscr();
    printf("\n %d",i++ && ++j);
    printf("\n %d %d",i,j);
    getch();
    return(0);
    }[/code]
    _______________ _______________ _______________ _______________ _____
    **************
    **OUTPUT**
    **************
    0
    1 1
    _______________ _______________ _______________ _______________ _____
    I'm using Borland Turbo C++ 3.0.
    I expect the code
    printf("\n %d",i++ && ++ j);
    to increment j by 1 and output 0 and then increment i by 1.

    Now i becomes 1 and j becomes 2.
    Now when the code below is executed
    printf("\n %d %d",i,j);
    I expect now that the code to print value of i and j as 1 and 2, but I get output as
    1 1.

    Where am I wrong, Please guide me.
    _______________ _______________ _______________ _______________ _____
    THANKS TO EVERYONE IN ADVANCE........ .......
    Last edited by sicarie; Mar 3 '08, 02:51 PM. Reason: Code tags are [code=c] and after your code [/code]. Please use them. They want to be used. They like to be used.
  • scruggsy
    New Member
    • Mar 2007
    • 147

    #2
    Originally posted by ambrnewlearner
    Hello everyone,
    Newbie here, PLZ HELP.......

    This is what I coded (it's very very simple, still I'm facing problem with this code) --------->
    _______________ _______________ _______________ _______________ _____
    #include<conio. h>
    #include<stdio. h>
    int main()
    {
    int i=0;
    int j=1;
    clrscr();
    printf("\n %d",i++ && ++j);
    printf("\n %d %d",i,j);
    getch();
    return(0);
    }
    _______________ _______________ _______________ _______________ _____
    **************
    **OUTPUT**
    **************
    0
    1 1
    _______________ _______________ _______________ _______________ _____
    I'm using Borland Turbo C++ 3.0.
    I expect the code
    printf("\n %d",i++ && ++ j);
    to increment j by 1 and output 0 and then increment i by 1.

    Now i becomes 1 and j becomes 2.
    Now when the code below is executed
    printf("\n %d %d",i,j);
    I expect now that the code to print value of i and j as 1 and 2, but I get output as
    1 1.

    Where am I wrong, Please guide me.
    _______________ _______________ _______________ _______________ _____
    THANKS TO EVERYONE IN ADVANCE........ .......
    Short-circuit evaluation causes the problem. Short-circuit evaluation means as soon as the result of an expression is known, the rest of the expression is not evaluated.
    In any condition a && b, if a is false then the expression cannot be true regardless of the value of b. So the rest of the expression is skipped because we know the answer already.
    When you do i++ && ++j, i starts at zero and because you used the postfix increment operator, i is not incremented until the semicolon. 0 = false, thus the rest of the statement incrementing j is never executed.

    There's your explanation, but what's more important to realize is that:
    - mixing boolean expressions inside function calls is generally a bad idea, and
    - using unary operators within more complex statements is also generally a bad idea.
    Both will often lead to unexpected results and hard-to-read code.

    Comment

    • AmberJain
      Recognized Expert Contributor
      • Jan 2008
      • 922

      #3
      Originally posted by scruggsy
      Short-circuit evaluation causes the problem. Short-circuit evaluation means as soon as the result of an expression is known, the rest of the expression is not evaluated.
      In any condition a && b, if a is false then the expression cannot be true regardless of the value of b. So the rest of the expression is skipped because we know the answer already.
      When you do i++ && ++j, i starts at zero and because you used the postfix increment operator, i is not incremented until the semicolon. 0 = false, thus the rest of the statement incrementing j is never executed.

      There's your explanation, but what's more important to realize is that:
      - mixing boolean expressions inside function calls is generally a bad idea, and
      - using unary operators within more complex statements is also generally a bad idea.
      Both will often lead to unexpected results and hard-to-read code.
      THANKS
      That's what I was lokking for..........
      I knew about SHORT-CIRCUIT evaluation, but I didn't knew that I will face it here.
      Please tell me one more thing. Does the term "SHORT-CIRCUIT evaluation" is technical terminology in C or it's just some random name for this phenomenon?

      ONCE AGAIN, THANK YOU VERY MUCH......

      Comment

      • AmberJain
        Recognized Expert Contributor
        • Jan 2008
        • 922

        #4
        Originally posted by scruggsy
        Short-circuit evaluation causes the problem. Short-circuit evaluation means as soon as the result of an expression is known, the rest of the expression is not evaluated.
        In any condition a && b, if a is false then the expression cannot be true regardless of the value of b. So the rest of the expression is skipped because we know the answer already.
        When you do i++ && ++j, i starts at zero and because you used the postfix increment operator, i is not incremented until the semicolon. 0 = false, thus the rest of the statement incrementing j is never executed.

        There's your explanation, but what's more important to realize is that:
        - mixing boolean expressions inside function calls is generally a bad idea, and
        - using unary operators within more complex statements is also generally a bad idea.
        Both will often lead to unexpected results and hard-to-read code.
        _______________ _______________ _______________ _______________ _____
        HELP, newbie here--------->

        Still I am confused......
        As you said, the operand on the right side of logical operator (&&) is not evaluated if left operand evaluates to FALSE. But according to priority rules of C language, UNARY operators (for example ++ in this question) have a higher priority then binary operators.
        Therefore regardless of value of expression on left of operator &&, first of all i++ and ++j must be evaluated separately as they have a higher priority than && operator.

        I know I'm wrong somewhere (in basic concept), so please guide me.........

        THANKS TO EVERYONE IN ADVANCE........ .
        _______________ _______________ _______________ _______________ _____

        Comment

        • AmberJain
          Recognized Expert Contributor
          • Jan 2008
          • 922

          #5
          Originally posted by ambrnewlearner
          _______________ _______________ _______________ _______________ _____
          HELP, newbie here--------->

          Still I am confused......
          As you said, the operand on the right side of logical operator (&&) is not evaluated if left operand evaluates to FALSE. But according to priority rules of C language, UNARY operators (for example ++ in this question) have a higher priority then binary operators.
          Therefore regardless of value of expression on left of operator &&, first of all i++ and ++j must be evaluated separately as they have a higher priority than && operator.

          I know I'm wrong somewhere (in basic concept), so please guide me.........

          THANKS TO EVERYONE IN ADVANCE........ .
          _______________ _______________ _______________ _______________ _____
          Somebody PLZ HELP IN THIS MATTER......... ..............

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            I expect your compiler is evaluating i++, which makes i 1 but used 0 for the expression and then does the && and sees that the expression can never be true and stops evaluating.

            That means you do not put calculations in an expression such that unless the expression is completely evaluated you get the wrong answer.

            In this case, do the incrementing before you get to the expression.

            This is a classic C pitfall.

            Comment

            • AmberJain
              Recognized Expert Contributor
              • Jan 2008
              • 922

              #7
              Originally posted by weaknessforcats
              I expect your compiler is evaluating i++, which makes i 1 but used 0 for the expression and then does the && and sees that the expression can never be true and stops evaluating.

              That means you do not put calculations in an expression such that unless the expression is completely evaluated you get the wrong answer.

              In this case, do the incrementing before you get to the expression.

              This is a classic C pitfall.
              OK, I got what you meant to tell.

              But, I am stucked now at the point that increment/decrement (post or pre) operators have a higher priority than logical operators.
              Furthermore, both type of operators have a Left to Right associativity (as far as I know).
              Therefore before compiler goes to execute &&, it must first execute POST and PRE ++ operators due to their higher priority. But the compiler is responding differently. So please guide me.


              I may be wrong somewhere in above statement of mine. If so, then please forgive me and guide me.

              THANKS......... .........

              Comment

              • weaknessforcats
                Recognized Expert Expert
                • Mar 2007
                • 9214

                #8
                The compiler did that. It evaluated the i++ first.

                Then it associated the left (i) in the && evulation and found that with i 0, the expression could never be true. No point in going any further. Wastes time.

                You are assuming that all of the operands in the expression have to be evaluated before the expression itself can be evaluated. This is not required to happen. Some compilers may do as you think while others do not.

                Comment

                • MACKTEK
                  New Member
                  • Mar 2008
                  • 40

                  #9
                  You know it makes sense that it "should" increment, but it does not.
                  I can "guess" as to why -- "compiler optimization"
                  Here is a link for rules of precendence:
                  After the table (in link) it says
                  In some circumstances, the order in which things happen is not defined.
                  In otherwords, if a certain behavior is not MANDATED then the compiler will have ambiguous behavior.

                  In your case:
                  The compiler is trying to optimize for speed.

                  It sees: i++ && ++j
                  Using the rules of precedence it should evaluate i++ FIRST.
                  Now think about that. Its saying do i++ First, but its pretty clear, the actual Post-Increment only adds AFTER the ";" has been reached.

                  So, anyway in the case of i++ && ++j
                  The compiler sees &&... it knows that that to optimize for speed, all it has to do is find 1 case where ANYTHING on the left evaluates to zero... if that occurs it ignores the rest of the expression and returns a 0.

                  This is called Short Circuit Evaluation:

                  Should it occur if the compiler was "really following precedence rules", probably not.

                  But its omptimizing for speed, and ignoring the precedence.

                  Now that you know these things can occur. It is best not to have any operations that alter variables during the evaluation of logical operators especially where such ops can be cut short by compiler optimizations.

                  Comment

                  • AmberJain
                    Recognized Expert Contributor
                    • Jan 2008
                    • 922

                    #10
                    Originally posted by weaknessforcats
                    The compiler did that. It evaluated the i++ first.

                    Then it associated the left (i) in the && evulation and found that with i 0, the expression could never be true. No point in going any further. Wastes time.

                    You are assuming that all of the operands in the expression have to be evaluated before the expression itself can be evaluated. This is not required to happen. Some compilers may do as you think while others do not.
                    Thank you WEAKNESSFORCATS ....

                    Comment

                    • AmberJain
                      Recognized Expert Contributor
                      • Jan 2008
                      • 922

                      #11
                      Originally posted by MACKTEK
                      You know it makes sense that it "should" increment, but it does not.
                      I can "guess" as to why -- "compiler optimization"
                      Here is a link for rules of precendence:
                      After the table (in link) it says
                      In otherwords, if a certain behavior is not MANDATED then the compiler will have ambiguous behavior.

                      In your case:
                      The compiler is trying to optimize for speed.

                      It sees: i++ && ++j
                      Using the rules of precedence it should evaluate i++ FIRST.
                      Now think about that. Its saying do i++ First, but its pretty clear, the actual Post-Increment only adds AFTER the ";" has been reached.

                      So, anyway in the case of i++ && ++j
                      The compiler sees &&... it knows that that to optimize for speed, all it has to do is find 1 case where ANYTHING on the left evaluates to zero... if that occurs it ignores the rest of the expression and returns a 0.

                      This is called Short Circuit Evaluation:

                      Should it occur if the compiler was "really following precedence rules", probably not.

                      But its omptimizing for speed, and ignoring the precedence.

                      Now that you know these things can occur. It is best not to have any operations that alter variables during the evaluation of logical operators especially where such ops can be cut short by compiler optimizations.
                      THANK YOU VERY MUCH........... .
                      This is what I was searching for. It is really a nice explanation for my problem.
                      THANK YOU AGAIN FOR HELPING ME OUT.

                      Comment

                      • MACKTEK
                        New Member
                        • Mar 2008
                        • 40

                        #12
                        Your are welcome. Scrugsy actually explained it all, I just interpreted!

                        Comment

                        Working...