I've searched for this, but couldn't find an answer and for whatever reason I was too ashamed to ask professor, due to that feeling when hundreds of people stare at you...
Anyhow, my question is what's the importance of having brackets? Is it OK if I omit them? Example:
for (int i = 0; i < size; i++) {
a += b;
}
vs
for (int i = 0; i < size; i++)
a += b;
I know both of them will work, but if I omit the brackets (which I tend to do a lot, due to visibility) will that change anything, anything at all? As I said, I know it works, I tested it dozen of times, but now some of my uni assignments are getting larger, and for some reason I have irrational fear that in the long run, this my cause some problems? Is there a reason to fear that?
it should be a reflex to reformat the code as well... that is of course for professional programmers in professional teams
Result wise , it is the same thing.
Only two things to consider.
- Code Maintainability
- Loosely coupled code. (may execute something else. because you haven't specified the scope for the loop. )
Note: In my observation, if it is loop with in a loop. Inner Loop without braces is also safe. Result will not vary.
Using the brackets future proofs the code against later modifications. I've seen cases where brackets were omitted and someone later added some code and didn't put the brackets in at that time. The result was that the code they added didn't go inside the section they thought it did. So I think the answer is that its good practice in light of future changes to the code. I've seen software groups adopt that as a standard, i.e. always requiring brackets even with single line blocks for that reason.
It's probably best to use the curly braces everywhere for the simple fact that debugging this would be an extreme nuisance. But other wise, one line of code doesn't necessarily need the bracket. Hope this helps!