Bifalgorithm post · Computer science one · Computing a Logarithm

Why can an extra semicolon make an if statement behave incorrectly?

Why can an extra semicolon make an if statement behave incorrectly? (Computer science one · Computing a Logarithm) — "Some compilers may give a warning, but th…

Ideas in this flowchart

  • A semicolon can make an if statement control an empty statement instead of the following print block.
  • The code is valid Java; a compiler may issue a warning, but it compiles and runs.
  • An if statement binds to the immediately following executable statement or code block.
  • The semicolon supplies an empty executable statement for the if statement.
  • The code is effectively equivalent to: int x = 15; if(x < 10) { } System.out.println("x is less than 10");
  • The print block follows the empty statement but is not bound to the if statement.
  • Therefore, the print statement executes regardless of the value of x.
  • With x = 15, the program still prints "x is less than 10," contrary to the intended behavior.
Feed/

Why can an extra semicolon make an if statement behave incorrectly?

No cover

Channel

Computer science one

1 page

"Some compilers may give a warning, but this is valid Java; it will compile and it will run. However, it will end up printing x is less than 10, even though x = 15! Recall that a conditional statement binds to the executable statement or code block immediately following it. In this case, we’ve provided an empty executable statement ended by the semicolon. The code is essentially equivalent to int x = 15; if(x < 10) { } System.out.println(\"x is less than 10\"); Which is obviously not what we wanted. The semicolon ended up binding to the empty executable statement, and the code block containing the print statement immediately followed, but was not bound to the conditional statement which is why the print statement executed regardless of the value of x."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.