Since when did we stop using brackets?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • askalottaqs
    New Member
    • Jun 2007
    • 75

    Since when did we stop using brackets?

    I was compiling this piece of code within the SDK of a program, and there was this piece

    [code=c]
    if (horizontal)
    for (y = 0; y < allocy; ++y)
    for (x = 0; x < allocx/2; ++x)
    {
    opus_pixel tmp;
    tmp = pixels[y * allocx + x];
    pixels[y * allocx + x] = pixels[y * allocx + allocx - x - 1];
    pixels[y * allocx + allocx - x - 1] = tmp;
    }
    [/code]
    How come a part of it has brackets and another doesn't, it compiled just fine when i did.

    Thanks for any info
  • arnaudk
    Contributor
    • Sep 2007
    • 425

    #2
    Strictly speaking, you only need brackets after an 'if' or 'for' statement if you want to execute more than one instruction.

    In your case, the 'if' will execute one command, namely the first 'for'. The first 'for' will loop over one command: the second 'for'. The second 'for', however, executes more than one command, hence they are enclosed in brackets, otherwise only the declaration opus_pixel tmp; would be looped over and the remaining commands executed when the loop ends.

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #3
      If there is only one statement beneath a for loop/while loop/if block, the braces are optional. In this case, the inner for loop (and its associated block) is the only statement in the outer for loop's block, so the {} are optional. Same is true for the if statement and the outer for loop.

      Comment

      • askalottaqs
        New Member
        • Jun 2007
        • 75

        #4
        thanks a lot for the replies! i should have known that :S

        cheers

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          In many places it is considered best practice to always put the braces in.

          If you don't put in the braces for nested if statements you can end up with the else clauses associated with the wrong if.

          Comment

          • Ganon11
            Recognized Expert Specialist
            • Oct 2006
            • 3651

            #6
            Or, a problem I have faced: Originally, I think an If branch only needs one statement inside and neglect the brackets. Later I come back and expand upon that portion of code without putting the brackets in. A compilation error later, I had to add them anyway.

            I think it's cleaner just to put them in no matter what.

            Comment

            Working...