Semicolon at end of 'if' statement

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

    While working on a programming assignment for class where I am working with a N by N grid of doodads and comparing characteristics of a random doodad to those above, below, left, and right, I found a nice use of this to prevent nested statements and potential boundary exceptions. My goal was to minimize code and keep from nesting if-statements.

    if (row == 0); 
    else (method (grid[row][col], grid[row-1][col]));
    if (row == N-1);
    else (method (grid[row][col], grid[row+1][col]));
    if (col == 0);
    else (method (grid[row][col], grid[row][col-1]));
    if (col == N-1);
    else (method (grid[row][col], grid[row][col+1]));

    where method(Doodad a, Doodad b) does some operation between a and b.

    Alternatively, you could use exception handling to avoid this syntax, but it works and works well for my application.

提交回复
热议问题