繁体   English   中英

我是否可以通过if else / statement声明变量

[英]Am I able to declare variable by if else/statement

您可以通过if / else语句声明变量吗?

int num1;
int num2;
int num3;

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

您可以在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

您也可以在if / else中声明一个变量,但是此后将不可见。

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 / else中分配变量,请确保确保已分配该变量。

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.

使用条件运算符(也称为三元运算符)通常比分配if / else更好。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM