Why was the statement (j++); forbidden?

后端 未结 3 1554
深忆病人
深忆病人 2021-01-30 10:01

The following code is wrong (see it on ideone):

public class Test
{
    public static void Main()
    {
        int j = 5;
        (j++);      // if we remove th         


        
3条回答
  •  臣服心动
    2021-01-30 10:21

    beacause the brackets around the i++ are creating/defining an expression.. as the error message says.. a simple expression cant be used as a statement.

    why the language was designed to be this way? to prevent bugs, having misleading expressions as statements, that produce no side effect like having the code

    int j = 5;
    j+1; 
    

    the second line has no effect(but you may not have noticed). But instead of the compiler removing it(because the code is not needed).it explicitly asks you to remove it(so you will be aware or the error) OR fix it in case you forgot to type something.

    edit:

    to make the part about bracked more clear.. brackets in c# (besides other uses, like cast and function call), are used to group expressions, and return a single expression (make of the sub expressions).

    at that level of code only staments are allowed.. so

    j++; is a valid statement because it produces side effects
    

    but by using the bracked you are turning it into as expression

    myTempExpression = (j++)
    

    and this

    myTempExpression;
    

    is not valid because the compiler cant asure that the expression as side effect.(not without incurring into the halting problem)..

提交回复
热议问题