Semicolon at end of 'if' statement

2018-12-31 04:21发布

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 == b);
// Do stuff

Which basically means that the stuff will be done whether a equals b or not, and the if statement has no point whatsoever. Why doesn't Java give me an error? Is there any situation in which this would be useful?

16条回答
孤独总比滥情好
2楼-- · 2018-12-31 04:55

Semicolon at the end of,
if(a==b); simply finish the statement in single line which means ignore the result of condition and continue the execution from the next line
This code is useful, on the other hand sometime introduce bug in program, for example,

case 1.

a = 5;
b = 3;
if(a == b);
prinf("a and b are equal");

case 2.

a = 5;
b = 5;
if(a == b);
prinf("a and b are equal");
would print the same output on the screen...

查看更多
余生请多指教
3楼-- · 2018-12-31 04:55

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);<br>
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.

查看更多
笑指拈花
4楼-- · 2018-12-31 04:56

Just a FYI about the usability and what difference it makes or can make if there is a statement like that

Consider a piece of code like the following.

int a = 10;
if ((a = 50) == 50);

System.out.println("Value of a = " + a);

Clearly in this case, the if statement does change the output. So a statement like that can make a difference.

This is a situation where this could be useful or better to say have an impact on program.

查看更多
素衣白纱
5楼-- · 2018-12-31 04:56

I can think of a scenario where an empty statement is required (not for if condition but for while loop).

When a program just want an explicit confirmation from the user to proceed. This may be required when the work after the user confirmation depends on some other things and user want to take control of when to proceed.

    System.out.println("Enter Y to proceed. Waiting...");
    System.out.println("");

    while(!(new Scanner(System.in).next().equalsIgnoreCase("Y")));

    System.out.println("Proceeding...");
    // do the work here
查看更多
登录 后发表回答