1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Code and Curly Brackets

Discussion in 'C' started by creeps, Aug 28, 2010.

  1. creeps

    creeps New Member

    Joined:
    Aug 28, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I'm going through K.N. King's introductory C Programming: A Modern Approach (2e) and every time I see the code in the book, I can't help but wonder what's the better way to write your code in the following situation. Should I use the curly brackets or not, and how much does it matter? Here are the three versions of the same idea (I guess the last version is the worst):

    Version 1, with curly brackets:
    while(1) {

    if(1) {

    i++;
    }
    }
    Version 2, without curly brackets:
    while(1)
    if(1)
    i++;
    Version 3, condensed version of the above code:
    while(1)
    if(1) i++;
    Personally, I've been using the first version for 2 years now (I've previous PHP experience), but looking at it again, all those curly brackets seem like overkill. On the other hand, it's arguably easier to add a second expression to the loop or the conditional. But the second version looks cleaner, somehow it reminds me of Python, and I thought of using it, but I wanted to know if it were considered good practice, before picking up any bad habits. Thanks!
     
  2. hellork

    hellork New Member

    Joined:
    Nov 2, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Writing TML with no H.
    Location:
    In my mom's basement.
    A debugger or objdump would tell you in seconds if there were any differences in the compiled code, which there aren't. And you may desire to buddy up with one anyway, if you are serious about writing any code. Plus, they are easy to use.

    Brackets are completely optional in C. If you indent your code there are programs that add them for you. I don't know. I assume there are, but I couldn't find any, so I put one up on freshmeat called "Anchor" so it's just a personal preference whether you use them or not. :person:
     

Share This Page