Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variable value inside if-statement [duplicate]

Tags:

java

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.

like image 466
Jose Salvatierra Avatar asked Apr 22 '13 13:04

Jose Salvatierra


People also ask

Can you assign a variable inside an if statement?

Yes, you can assign the value of variable inside if.

Can you declare a variable in an if statement C++?

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.

Can we use assignment operator in if condition?

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)


2 Answers

Variables can be assigned but not declared inside the conditional statement:

int v; if((v = someMethod()) != 0) return true; 
like image 149
Parth Soni Avatar answered Sep 28 '22 02:09

Parth Soni


You can assign, but not declare, inside an if:

Try this:

int v; // separate declaration if((v = someMethod()) != 0) return true; 
like image 24
Bohemian Avatar answered Sep 28 '22 04:09

Bohemian