Semicolon at end of 'if' statement

前端 未结 18 1646
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:01

Today, after half an hour of searching for a bug, I discovered that it is possible to put a semicolon after an if statement instead of code, like this:

if(a          


        
18条回答
  •  花落未央
    2020-11-22 01:43

    It is an old leftover from the days when there was more syntactic sugar to differentiate expressions from statements.

    Basically, the comma was used as the list item separator, so the semicolon was used as the "list of statements" separator. The downside is in the handling of null items in lists, and null statements in blocks.

    In a list of items, Java uses the explicit keyword null, but a "null statement" is just an empty line. Allowing the existence of an empty line is a holdover from tradition inherited from C.

    Why do it? Especially with an if statement when you know that no statements are being executed: Because some if statements have side effects:

     int c;
     if ((c = in.read()) != -1);
    

    Yes, it is not the best example, but basically it says read a byte from the stream and do nothing. Might be useful in some corner cases, but even if this example isn't the best, it illustrates the intent. We want to feel the side-effects of the expression without accidentally executing any statements.

提交回复
热议问题