CrazyEngineers
  • piyushh
    piyushh

    MemberSep 22, 2011

    doubt in operators in C

    #include
    #include
    void main()
    {
    int a=1,b=1,c=1;
    int p;
    clrscr();
    p= a++ + b++ || c++ + ++a ;
    printf("a=%d\n,p=%d",a,p);
    getch();
    }


    Actual output : a = 2
    p = 1
    according to my knowledge it should give: a=3 and p=1;
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • simplycoder

    MemberSep 22, 2011

    @piyushh, see there is a difference in pre-increment and post-increment.
    The pre-increment operator 'tells' compiler that increment the value first and then use it.
    The post increment operator 'tells' compiler that use the same value through out and then use it.

    So I am assuming that you derived that answer using following technique.
    value of a is 1,b is 1,c is 1
    p= a++ + b++ || c++ + ++a ;
    p = a++ + b++ || c++ + ++a
    p = 1 + 1 || 1 + 2
    p = 2 || 3
    p = 1.
    Now post increment value of a, so now a is 3.
    But then this way of analyzing will lead to an incorrect answer as there is a boolean operator || (Logical OR). Logical operator is a short circuit operator.
    It means that it will check for the first condition, if its true then it will not bother to check the other condition, if its false, then only it will check the other condition.
    So in this case,c++ + ++a will never be executed.

    Now let us analyze the code again.
    p = a++ + b++ || c++ + ++a
    p = 1 + 1 ||
    p= 2||(this is not 0, hence overall statement is true or 1.)
    therefore p=1.

    Now post increment the value of a, now a=2.

    Thus we get p=1 and a=2.
    Are you sure? This action cannot be undone.
    Cancel
  • piyushh

    MemberSep 24, 2011

    p = a++ + b++ || c++ + ++a
    p = 1 + 1 || 1 + 2
    p = 2 || 3
    p = 1.

    Are you sure the value below a++ will be processed as 1?
    Are you sure? This action cannot be undone.
    Cancel
  • simplycoder

    MemberSep 24, 2011

    @Piyush: a++ means use the value first throughout the statement and then increment.
    so a++ will be 1 as it would be used first throughout the statment and then incremented.
    so once p = a++ + b++ || c++ + ++a is executed, then a will be incremented to 2.
    Are you sure? This action cannot be undone.
    Cancel
  • piyushh

    MemberSep 25, 2011

    @simplycoder >I guess you arnt getting my question ,The preference of ++a is ONE thats why it will increment the value of 'a' whereever it is saved(stack) and now the new value(i.e 2) of a will be processed. Agree with your answer about post increment but I wasnt talking about it infact
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register