J
Jason
Programming recently I was the habit of leaving out the braces on if
statements if the branch only applied to a single line, assuming it would
all work and be equivalent to "if(condition) { statement; }" I implemented
an algorithm and it did not work for a while and when i tracked the problem
down it was as if a certain action was not being done from one of these if
statements that did not have a brace, so I placed all if statements in
braces and it worked as expected. This was not a result of misunderstanding
on my part such as including 2 statements under the braceless if and I know
indentation is not important, the statements were usually all on one line
anyhow.
It appeared to work ok when I first started doing it, but not when there was
a few in a row or near each other inside while loops and such like. In some
parts of my code I have neglected to change them to braces without any
problems, confusing me.
I also sometimes feel the desire to omit braces from while and for loops
because i find them irritating and like to shorten my code. Am I able to
avoid braces or not? Is it guaranteed to work or do different compilers
produce different results? If I have code that works perfectly now and all
I do is remove braces from single statement if, for and while loops, is it
guaranteed to make no difference or am I naive to some other potential
problem?
thanks for clarifying.
statements if the branch only applied to a single line, assuming it would
all work and be equivalent to "if(condition) { statement; }" I implemented
an algorithm and it did not work for a while and when i tracked the problem
down it was as if a certain action was not being done from one of these if
statements that did not have a brace, so I placed all if statements in
braces and it worked as expected. This was not a result of misunderstanding
on my part such as including 2 statements under the braceless if and I know
indentation is not important, the statements were usually all on one line
anyhow.
It appeared to work ok when I first started doing it, but not when there was
a few in a row or near each other inside while loops and such like. In some
parts of my code I have neglected to change them to braces without any
problems, confusing me.
I also sometimes feel the desire to omit braces from while and for loops
because i find them irritating and like to shorten my code. Am I able to
avoid braces or not? Is it guaranteed to work or do different compilers
produce different results? If I have code that works perfectly now and all
I do is remove braces from single statement if, for and while loops, is it
guaranteed to make no difference or am I naive to some other potential
problem?
thanks for clarifying.