user5504713
user5504713

Reputation:

Am I able to declare variable by if else/statement

Can you declare a variable through an if/else statement?

int num1;
int num2;
int num3;

if (num1 <= num2){
    num3 = (num1-num2);
}else{
    num3 = (num2-num1);
}

Upvotes: 0

Views: 48

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37655

You can assign a variable in an if/else:

int num1 = 2;
int num2 = 3;
int num3;                // This is a declaration

if (num1 <= num2){
    num3 = (num1-num2);  // This is an assignment
}else{
    num3 = (num2-num1);  // This is an assignment
}
// We can use num3 here

You can also declare a variable in an if/else, but it won't be visible afterwards.

int num1 = 2;
int num2 = 3;

if (num1 <= num2){
    int num3 = (num1-num2);  // This is a declaration and assignment in one.
}else{
    int num3 = (num2-num1);  // So is this
}
// We can't use num3 here.

If you assign a variable in an if/else, make sure that it is guaranteed to get assigned.

int num1 = 2;
int num2 = 3;
int num3;

if (num1 <= num2){
    num3 = (num1-num2);  
}else if (num1 == 9) {
    num3 = (num2-num1);  
}
// We can't use num3 here because the compiler can't be sure that one of the assignments happened.

It is often nicer to use the conditional operator (also known as the ternary operator) rather than assigning in an if/else

int num3 = num1 <= num2 ? num1 - num2 : num2 - num1;

Upvotes: 2

Related Questions