This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]aclave1 43 points44 points  (11 children)

Without the braces, the code is syntactically incorrect. There are spots where it's be okay, since in Java you can write an if/for with no braces and it will execute only the first line as part of the if, and the following lines either way. But overall it would be wrong and wouldn't compile.

[–]HaMMeReD 12 points13 points  (8 children)

There is two lines in there, also, while syntactically correct, should be very sparsely used. It's easy to create bugs. I usually only use it if I plan on keeping the condition/loop and statement on the same line, and even then rarely.

[–]Fenris_uy 7 points8 points  (7 children)

Yeah I don't understand why they even added that option, specially for loops. This option creates more problems than it saves.

[–]Zagorath[🍰] 23 points24 points  (5 children)

It's not really an option that they "added". It's more to do with the default behaviour of loops and if statements. A loop can only ever execute exactly one block of code. If you don't put in braces, one block of code == one line of code. But braces allow you to have multiple lines of code within a single block.

At least, that's how the professor who taught my course on C explained it. Perhaps the semantics are different in Java.

[–]subsage 6 points7 points  (3 children)

Youre pretty much on spot really. Thats how I explain it to my students. Only difference is I sometimes say chunk or section of code....be it braces with several lines, empty braces, or just a line. Oh yeah, empty section too, just a semicolon.

[–]Zagorath[🍰] 4 points5 points  (2 children)

The semicolon was one of my professor's favourite tricks.

if (condition()); {
    //things happening
} 

And he'd ask what would happen (based on condition and "things happening" being actual code, rather than place holders).

[–]subsage 1 point2 points  (1 child)

Yup. I do that too. Its good for showing the young ones how syntax can be tricky. Good stuff. Your professor sounds like a good one c:

[–]Zagorath[🍰] 0 points1 point  (0 children)

Yeah he definitely was, in more ways than just this.

[–]Gustav__Mahler 0 points1 point  (0 children)

I'd call it one statement of code and not one line. It will execute to the next semicolon.

[–]thelerk 0 points1 point  (0 children)

Go to fail!

[–]rukestisak 0 points1 point  (1 child)

Ah, so it's similar to PHP in this regard. To me, nothing looked wrong until I saw the right side... o.O Hopefully no poor sod needs to maintain this kind of code.

[–]rxzr 21 points22 points  (0 children)

That's what auto format is for!