Replies
Welcome, guest
Join CrazyEngineers to reply, ask questions, and participate in conversations.
CrazyEngineers powered by Jatra Community Platform
-
@simplycoder-NsBEdD • Sep 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. -
@piyushh-O70sb6 • Sep 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? -
@simplycoder-NsBEdD • Sep 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. -
@piyushh-O70sb6 • Sep 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