Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any minor difference between ; or {} to represent a null statement?

I understand that the statement terminator symbol ;, if used solitarily, represents a null statement. Also, "empty loop bodies" can be a useful programming construct, and are made using null statements.

Looking at the while statement below, on line #2, I decided to replace the terminating ; symbol, with a pair of back-to-back {} curly braces. The code compiled and ran OK. Does this mean that the Java compiler replaces an empty code block (represented by the "empty" {} curly braces), with a ; based null statement?

If Java does something slightly different, would the resulting bytecode be identical in both cases? (I'm sorry that I can't check this ATM. I'm new to Java, and I don't yet have the necessary knowledge to display and examine bytecode).

int i=0,j=100;

// Either a terminating ; symbol or {} braces work to make an "empty loop body".
while (++i < --j) {}  
System.out.println("The midpoint between 0 and 100 is " +i);  // Midpoint is 50.
like image 227
user2911290 Avatar asked Nov 25 '13 11:11

user2911290


2 Answers

The two are semantically identical, and the compiler will generate the same code in both cases. If you're trying to intentionally include an empty loop body, {} makes it more clear that it's on purpose rather than just a stray semicolon. You should always explicitly comment such cases, and it's usually better to rework your code to avoid a busy-wait loop altogether.

like image 162
chrylis -cautiouslyoptimistic- Avatar answered Oct 18 '22 01:10

chrylis -cautiouslyoptimistic-


The same byte-code will be generated in both cases.

I prefer to use { } instead of ;, the latter can sometime have a feeling of typo when it's used in for and while loops.

If I have this code:

while(i-- < j++);
System.out.println("Wild World");

I would think maybe it's a typo, ; shouldn't be here.

But if I have:

while(i-- < j++) { }
System.out.println("Wild World");

I know there is a reason for that..

like image 38
Maroun Avatar answered Oct 18 '22 01:10

Maroun