what is the value of a,b,c,d after increment operation?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SanjeevSaraswat
    New Member
    • Sep 2014
    • 1

    what is the value of a,b,c,d after increment operation?

    void main()
    {
    int a=1,c=1,d;
    int b=++a + ++a + ++a;
    d=++c + ++c + ++c;
    printf("%d%d%d% d",a,b,c,d);
    }
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    The C standard does not specify the order in which the operands (suh as ++a) of an operator (such as the + in ++a + ++a) are evaluated and there is no guarantee when an affected variable will change its value.

    consider
    Code:
    int a=1,c=1,d;
    int b=++a + ++a + ++a;
    however, when are the ++a operands evaluated?
    1. the ++a operands of (++a + ++a) evaluated and the result added then the final ++a evaluated and added? the result is a=4 and b=10
    2. all the ++a operands evaluated and the then the + operations executed giving a=4 and b=12
    running the above code Visual C++ gives b=12 and gcc gives b=10 (both give a=4)

    the advice is do not use a variable more than once in an expression if one (or more) of the references has one of ++ or -- operators attached to it.

    Comment

    • carbon
      New Member
      • Mar 2014
      • 9

      #3
      Well correct me if I'm wrong. But I think it's a undefined behavior.

      Between two sequence points a variable must not be modified more than once.

      To understand what's going on you have to learn about undefined-behavior and sequence-points.
      Checkout this question on stackoverflow.c om.

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        yes, in the case of the the expression
        Code:
        int b=++a + ++a + ++a;
        the sequence point is the ; at the end of the statement when "it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed", i.e when are ++a operands evaluated? you don't know they are all evaluated until the sequence point and different compilers etc give different results

        Comment

        Working...