Semicolon at end of 'if' statement

前端 未结 18 1645
没有蜡笔的小新
没有蜡笔的小新 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:41

    Is there any situation in which this would be useful?

    Useful? As in "makes your code cleaner, clearer, faster, more maintainable"? Not at all. This is most likely poor, confusing code.

    But it's not necessarily benign. Such a statement can perform actions and/or alter state due to methods which cause side effects, and optionally evaluate those methods due to short-circuiting of operators.

    if( a() && b() );
    

    Here, a() or b() may do something, and b() will only execute if a() is true.

    As to why, I think the answer is simply that it would be worse to deviate from defined, expected behavior (e.g. statements like while(reader.read());) than the alternative of developers writing bad code.

    Writing bad code is always possible. And just to reiterate, this would be bad code in almost any case.

提交回复
热议问题