如何在Java中将变量赋值给需要表达式的位置?

huangapple go评论85阅读模式
英文:

How's it possible to assign variable where expression needed in java?

问题

我已经搜索了关于表达式和语句之间的区别,并且出现了一个问题。

在C或Java中,我可以在if语句中像这样分配变量。

int a;
// someFunc返回一个整数值
if ((a=someFunc()) == 1) {
    // 做点什么
}

相反地,在Python中不允许这样做。

if (a = someFunc() is 1):
    # 做点什么

当然,遵循PEP 572,在Python 3.8之后可以使用它,但应该使用:=符号。

然而,a=someFunc()并不是表达式,而是语句,在执行后不返回任何值。对吗?
所以,Python解释代码的方式看起来合理,而Java的方式则不同。

但是,在Java或C中如何解释这种代码方式?为什么允许这样做?

英文:

I've searched about the difference between expression and statement, and a question came up.

In C or java, I can assign variable in if statement like this.

int a;
// someFunc returns an integer value
if ((a=someFunc()) == 1) {
    // do something
}

In contrary, python doesn't allow this.

if (a = someFunc() is 1):
    # do something

of course, following PEP 572, after python 3.8 i can use it,
but should use := symbol.

however, a=someFunc() is not expression but statement which returns nothing after execution. right?
so, python's way of interpreting code looks reasonable, and java's doesn't

but, how's it possible to interpret that way of code in java or C? and why is it allowed?

答案1

得分: 1

我将尝试通过采用你的例子来解释:

int a;
if((a = someFunc()) == 0) {
    //在这里执行一些操作
}

在这里遵循以下顺序:

  1. 调用 someFunc() 方法,执行后预期将根据我们声明的变量返回某个整数值。
  2. 在方法中返回值后,将其存储在变量 a 中。
  3. 现在括号内的整个语句被视为变量 a 中的值,即 (a = someFunc()) 变成了变量 a,而它本身是通过调用方法 someFunc() 返回的整数值。
  4. 现在将此值与 0 进行比较,并根据 if 语句进行验证。
英文:

I will try explaining this by taking your example:

int a;
if((a = someFunc()) == 0) {
    //do something here
}

Over here the below sequence is followed:

  1. someFunc() method is called, which after getting executed is expected to return some integer value as per our variable declared.
  2. After the value is returned from the method it gets stored inside the variable a.
  3. Now the whole statement is present inside parentheses is treated as the value present inside variable a, i.e. (a = someFunc()) becomes a which again is an integer value return by calling the method someFunc().
  4. Now this value is getting compared with 0 and the if statement is validated accordingly.

huangapple
  • 本文由 发表于 2020年9月25日 00:34:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64050673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定