A method called in a ternary operator increments a variable and returns a boolean value. When the function returns false the value is reverted. I expected the variable to be 1 but am getting 0 instead. Why?
public class Main {
public int a=0;//variable whose value is to be increased in function
boolean function(){
a++;
return false;
}
public static void main(String argv[]){
Main m=new Main();
m.a+=(m.function()?1:0);
System.out.println(m.a);//expected output to be 1 but got a 0 !!!!!
}
}
m.function()
always returns false, so the value that gets added on is 0... 0 + 0 = 0. – Brutala
– Handspringm.a = m.a + 1 or 0 depending on whether function is true.
– Brutal0
and in operation it is false som.function()?1:0
also return 0?? – Workoutfalse != 0
in Java... Ternary Operator is(condition ? valueIfTrue : valueIfFalse)
. – Brutala += (a++ == 1) ? 1 : 0;
(I know that the function always returnsfalse
but this was the only inline statement I could think of as equivalent in this situation. – Handspringm.a
. It's the fact that the+=
operator somehow replaces the post-increment state ofa
. – Handspringm.a = 0 (the current value) + (potentially 1 or 0)
. – Brutala
. – Handspringa += function()?1:0;
? The same thing? I don't have a way to compile C# currently. – Kiblah