I was wondering whether it is possible to assign a variable a value inside a conditional operator like so:
if((int v = someMethod()) != 0) return v;
Is there some way to do this in Java? Because I know it's possible in while
conditions, but I'm not sure if I'm doing it wrong for the if-statement or if it's just not possible.
Yes, you can assign the value of variable inside if.
If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement.
Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With