+ 2
Can you explain this , why the value of this code after executing is 4 .
code : int i=0; i = ++i + ++i; count <<i;
14 ответов
+ 2
This code will output 4 with C++/C and 3 with JAVA. This difference is due to the change in precedence of ++ and + operators in these Languages.
In C/C++ pre-increment operator (++) has more precedence over addition operator (+). Thus value of i first increments to 1 and then to 2. this value is calculated first and then the addition will be performed. So its output will be 2+2=4.
But when we concider java, + has more precedence over ++. So first i gets the value 1 and this will be one of the operand of + and then i get the value 2, which is the second operand. The sum is calculated by this way.
The lines with multiple operator follows their precedence for that language.
0
++i always works first before the code. hence your 0 becomes first 1 then 2. cause you have ++i twice. now it is essentially i = 2 + 2.
which is 4.
0
@gautam..is this the only case with C++ or others language also follow the same . Because I have run the code in Java and JavaScript both gives the output as 3.
0
Good day friends, I don't know abt c++ programming language buh if am to solve this question with Java, the answer should be two reason:
i=0;// ur variable i is 0
i=++i + ++i;//this stage u v pre incremented i twice, that is 1 + 1=2.
DecodesWorm 12032016
0
@Shivprasad k.. Is the precedence off pre-inccrement only or post-increment also have higher precedence .. if it so then what will be the output of this ..
i=0;
i=i++ + i++;
then i=?.
0
What does this syntax means count<<i
0
Wow sou silly of me the answer is 3 reason is that the first ++i gives u 1 and the second ++i makes the i to be 2 then add them it becomes 3
DecodesWorm12032016
0
@DecodesWorm
Mathematically you are correct, but when we code it, its not happens what u said in all cases, but sometimes (means some languages)
0
@Sachin Shukla
In case of JAVA its simply 1 because its a postincrement operator and + has more precedence. so initial value of i is added and the result is incremented.
but when we turn towards c++, its result is 2.
this is little bit confusing for me.
I think, here zeros are added followed by two increment operations, which result 2. I am not sure about this anyway.
0
@DecodesWorm
You should try these codes. You can find the changes if you choose different platforms.
0
3
0
hi all .. I have posted two codes of increment operator in C++ and Java ..please have a look and give .. proper explanation .. if possible .. thanks ..
0
ans is 2 in java
0
3