The operators like pre-increament(or decreament) and post increament(or decreament) is very commonly used operators for the programmers. It is widely used in the loop. I know, it’s pretty simple to understand. Well, It’s not restricted to be used for the loop only. It can be used for a simple instructions like
++i * ++i * --i * i++ ....
It’s tricky to get the correct value of this operation. And, It totally depends upon the compiler you are using. I always used to get stuck in thses kind of operations. But today I would like to share my understanings with you guys.
Okay!, Lets start with the most popular language, i.e., C Language and see how C compiler treats this ++ and – opeartor when used for the calculation.
Let me write a small piece of code
main()
{
int x = 3, y, z;
y = ++x * ++x * ++x;
printf(“The Value of y = %d”, y);
x = 3;
z = x++ * x++ * x++;
printf(“\n The Value of z = %d”, z);
}
Any Guesses? Well, The value of ‘z’ is not hard to get but the value of ‘y’. The output of the above written code is :
The Value of y = 216
The Value of z = 27
Surprised with the value of y? As I mentioned earlier, it totally depends upon the compilers, but in most of the C compilers you will get the same value.
Okay, let me tell you the logic now. Whenever the “++” or “--” operators are used for the operations like in the above code. It’s value are pre-calculated. Further, the calculated value used for the rest of the operations.
e.g.,
x = 3;
y = ++x * ++x * ++x;
As we can see that, the “++” operator has been used three times here, so the value of x would be
x = x+3(only for pre-increament operator)
i.e, x = 6;
now the y = 6 * 6 * 6, i.e 216.
Well, The compilers like Java or JavaScript will give a different output, In Java or JavaScript, the output would be simply 4 * 5 * 6 = 120. It’s perhaps the C language only who treats these operators in this way. Anyways, what if there is a mixture of pre-increament and pre-decreament operator? Something Like,
int i = 2, j;
j = --i * ++i * ++i * ++i * ++i * --i;
It’s pretty simple, “--” has been used twice while “++” used for four times. So basically it’s two times “++”. Yes, you can cancel out each “--” with a “++” and vice versa.
now the final value of i is
i = i+2, i.e., 4
j = 4 * 4 * 4 * 4 * 4 * 4;
j = 4096.
In Short,
In Short,
Remember, since "++" or "--" is having the highest priority among all the operators so we need to pay attention towards this operator. Calculate the final value of the variable, by counting the number of "++" and "--" associated with the variable and cancelling out each "++" with "--" and vice versa. Preceed with this final value to perform the rest of the calculation.
No comments:
Post a Comment