#Is it ok to not include {} when the inner code block contains more than 1 instruction

11 messages · Page 1 of 1 (latest)

deft quiver
#

For example this code runs ok. The for loop body seems to count as only 1 instruction. is this guaranteed to work? and not considered a smell?

        for(int i = 0; i<10; i++)
                if(i%2==0){
                        printf("number ");
                        printf("%d\n", i);
                } else
                        printf("this is not it\n");
blazing swallowBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

deft quiver
#

im worried about adding bugs to my code and have been adding {} that are probably not needed and I'd like to make things as terse as possible

vivid ingot
#

So this does work as the entire if/else chain is treated (sort of) as the one statement.

However, for sake of clarity, it would be probably better to use the {} even if not strictly needed

deft quiver
#

agreeded, but the behavior is guarnteed?

vivid ingot
#

Yes

inner valley
#

As a rule of thumb: If in doubt, use curly braces

vivid ingot
#

ifs and all of their sub statements are all considered one statement for the sake of grammar parsing

deft quiver
#

thank you @atomic field @vivid ingot

#

!solved

blazing swallowBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity