Why can't we define a variable inside an if statement?

前端 未结 5 1072
余生分开走
余生分开走 2020-12-01 04:13

Maybe this question has been answered before, but the word if occurs so often it\'s hard to find it.

The example doesn\'t make sense (the expression is

5条回答
  •  长情又很酷
    2020-12-01 04:41

    This has to do with the difference between a statement, and an expression. An expression has a value, whereas a statement does not.

    Using your examples, notice these classifications:

    StringBuilder sb; // statement
    
    sb = new StringBuilder("test") // expression
    
    StringBuilder sb = new StringBuilder("test"); // statement
    

    Notice that only the middle portion is a expression.

    Now we move onto your conditional statement. The syntax for using the not-equals operator is

    expression != expression
    

    So on both sides of the != you need something that actually has a value (this just makes sense). Ergo, you cannot have statements on either side of the operator. This is why the one version of your code works, while the other does not.

提交回复
热议问题