Assign variable value inside if-statement
Variables can be assigned but not declared inside the conditional statement:
int v;
if((v = someMethod()) != 0) return true;
You can assign, but not declare, inside an if
:
Try this:
int v; // separate declaration
if((v = someMethod()) != 0) return true;
Yes, you can assign the value of variable inside if.
I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single =
instead of ==
or ===
.
It will be better if you do something like this:
int v;
if((v = someMethod()) != 0)
return true;
an assignment returns the left-hand side of the assignment. so: yes. it is possible. however, you need to declare the variable outside:
int v = 1;
if((v = someMethod()) != 0) {
System.err.println(v);
}