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!

The braces(curly brackets) are there to define blocks of code and to help make your code readable...In some situations the coder can choose which he/she prefers but you should err on the side of readability.

Edited 6 Years Ago by gerard4143: n/a

It is all about clarity, and as with everything where you must choose, there are advantages and disadvantages among them. You will grow a preference eventually. Nevertheless, it is considerate good programming practice to be consistent in the style when you code. Especially, when you do not have the luxury of applying your preference, e.i. company practices, group project, or code maintenance, written by others.

Use the curlys.

An alternate of version 1, and the format I prefer:

while(1) 
{
    if(1) 
    {
        i++;
    }
}

I personally find that in your original style I tend to loose the {, but in this version the block is visually better defined. Again, my preference. Both work just as well.

If you want to get rid of the brackets I suggest *only* doing it when your conditional statement is followed by a single statement.

(eg.: while(1) x = 2)

If you need multiple lines to put it in (Like in your 2nd and 3rd version), just use brackets because it will become a pain to read.

Personally I would either do:

while(1) {
   if(1) {
      i++;
   }
}

or

while(1) {
   if(1) i++;
}

Edited 6 Years Ago by [Alpha]-0mega-: n/a

This question has already been answered. Start a new discussion instead.