What is your indentation preference ?

May 11, 2008
19,582
1,196
126
I prefer the Allman and as second best the GNU style. It is much easier to read for me.
I do not mind scrolling once in a while since i use a large editing window.

Allman :
Code:
while (x == y)
{
    something();
    somethingelse();
}

GNU:
Code:
while (x == y)
  {
    something();
    somethingelse();
  }

The other styles, i find more difficult to process when doing fast reading.
It is lucky for me, also used at my work.

https://en.wikipedia.org/wiki/Indent_style

What do you guys and gals prefer ?
 

Gryz

Golden Member
Aug 28, 2010
1,551
203
106
I prefer K&R style. Where the bracket after the if or while is on the same line. But where I work now we use Allman style. It was relatively easy to get adjusted.

The reason I reacted a little strong at your similar question a few weeks ago, is because coding style at my current job. When I applied for the job, I asked them: "do you have a coding style". Their answer was: "not one style for everyone, but each sub-component of our software has its own style". That turned out to be not true. Sometimes each file has a different style. Sometimes each function. Sometimes I see 3 different style on one line. It drives me nuts. Or depressed. It really makes me depressed sometimes for an hour when I see new code, just checked in last week by a colleague from over-sees.

In a previous job, long time ago, we had hundreds if not 1000+ programmers working on one software system. And they all used K&R style. And when someone would do something ugly, or something stupid, they would get corrected. In my current job, it's almost forbidden to criticize the coding-style of a colleague. Unless his code crashes. It's unbelievable.

Your eyes get used to seeing patterns. If code is written in one style, you see quicker what is going on. You see quicker when something is unusual, and requires a little extra thought to make sure you understand what is going on. If you use 10 different coding styles in a file, your mind is constantly on alert. "Do I understand what is going on here ? Did I miss a subtle thing ?"

I'll give you an example that I saw this week in our own code. In all my years of programming, I've only ever seen people write code like:
Code:
for (i = 0; i < max; i++)
Right ?
When you increment something, you write: i++; counter++; pointer++;
This one programmer in our over-seas team writes: ++i; ++counter; ++pointer;

It drives me nuts. Usually when you use ++(*pointer) in stead of (*pointer)++, it is for a reason. If you change the location of the increment, the behaviour of your code changes. Doesn't happen often, but sometimes it does. You immediately are on alert when you see the ++ before the expression. But no, my colleague has to write ++i;
Pfff. :)

She also like to write:
Code:
if (NULL == pointer)
{

Switching the left and right operand of the comparison. I understand why she does it. To prevent mistakes like "if (pointer = NULL)". But you know, we got a compiler to warn us for that. Switching the operands is unusual. And it hurts my eyes. I might look like a whiner, but I know I am not the only one who doesn't like "if (5 == i)". And there are dozens of examples like this.

I think it begins with realizing why it is important to write code that is readable. Code is written once. But if you write professional code, your code will be read hunderds if not thousands of times. If you spend and extra few seconds, or an extra minute, to make your code better readable, it will always pay off in the long run. Some people don't realize this. It can be hard to convince them (or, in my opinion, educate them).

So the first time I speak with the lead-programmer of the component I am working at. He says: "our code is old, has been changed a lot, lots of people worked on it. The comments are often not correct any more. So I have removed a lot of comment over the last years". I asked "but then you add new comments, right" ? Nope. He proudly told me he only removes comments. Hardly ever adds any.

It's taken me a year to start understand how our code hangs together.
Some of my colleagues think they save the company money by not worrying about comments, in-code documentation, coding-style, names of functions and variables.
But my boss just paid me a year's worth of salary, just for me to understand what we're doing.
And every new hire has to go through that process.

So yes, William (OP), your question is very relevant imho.

I prefer K&R over Allman, because when you have 1 line if-clauses, you pay only 1 line penalty of adding curly-brackets. Consider these examples:
Code:
if (i == 8)
    do_something();

if (i == 9)
{
    do_something();
}

if (i == 10) {
    do_something();
}
I prefer the last style. But right now I am using a mix of the first 2 styles. Because the others in my group do that.
I don't like the GNU-style at all. 2-Space indentation makes it harder to see where the curly brackets belong.
 
May 11, 2008
19,582
1,196
126
I can understand your frustration. :hug:

Especially the (5 == i).
That is awful. It reads unnatural.
Because you check on i and not on 5.
But that may also have to do with our language and how we read mathematics. English and a lot of other Germanic languages are setup in such a way. Dutch is as well. From left to right.

I find the Allman style easy to read because when i look at it, i see the if statement. After that the accolade open on a new line and then i know the following code up to the accolade closed will be executed depending on the if statement. I find the Allman style easier to keep parts of the code in my mind while reading through other sections of code. An accolade with some white space means take some rest to me in between. While the other more dense writing styles make me tired.
 

Ichinisan

Lifer
Oct 9, 2002
28,298
1,234
136
I only dabble in coding occasionally and I prefer to almost minify my source code, especially when doing JavaScript or PHP that doesn't really compile. I still indent for readability and I use tabs for efficiency -- not spaces (I totally get the Richard Hendrix character). Opening bracket would go on the same line with the opening condition or name of the function. Unneeded spaces would be removed.
 

Merad

Platinum Member
May 31, 2010
2,586
19
81
It drives me nuts. Usually when you use ++(*pointer) in stead of (*pointer)++, it is for a reason. If you change the location of the increment, the behaviour of your code changes. Doesn't happen often, but sometimes it does. You immediately are on alert when you see the ++ before the expression. But no, my colleague has to write ++i;

In C++ land it is (or at least used to be, I haven't really looked in a few years) best practice to use pre-increment everywhere unless you specifically need the behavior of post-increment. The reason being that when you are dealing with STL and other iterator types, post-increment requires creating a copy of the iterator, that's immediately discarded. Maybe/hopefully compiler optimization has improved enough where the copy is optimized away, but it used to carry a measurable amount of overhead: http://antonym.org/2008/05/stl-iterators-and-performance.html

Switching the left and right operand of the comparison. I understand why she does it. To prevent mistakes like "if (pointer = NULL)". But you know, we got a compiler to warn us for that. Switching the operands is unusual. And it hurts my eyes. I might look like a whiner, but I know I am not the only one who doesn't like "if (5 == i)".

This is another common best practice from the C++ world - not unusual at all. Yes, there are compiler warnings, but they're turned off by default in most compilers and, being warnings, are easily disabled or ignored. Not to mention that assignment in a conditional *is* sometimes useful. This turns an ambiguous warning into an outright error (assignment to a rvalue). it annoyed me for the longest time and I resisted using it, but after giving and using it on a few projects I highly recommend it.
 
Jun 18, 2000
11,123
700
126
I care less about the style, only that it's applied consistently. We have a preference file for eclipse that everybody on our team has to apply to their workspace, then eclipse auto formats on save.

My aggravation now is newer versions of eclipse (4.5+) wrap long lines differently. Simply opening and saving a file that hasn't been touched in a while results in a bunch of reformatted lines, which is a pain in the ass if you need to compare revision history.
 

Red Squirrel

No Lifer
May 24, 2003
67,398
12,142
126
www.anyf.ca
Generally I prefer Allman...ish. Something like this:

Code:
while (x == y)
{
    something();
    somethingelse();
}

Basically same as you posted but no blank returns before/after the brackets.

Edit: Actually seems it's the forum that does that. So yeah basically the same one you posted first. That's typically how I go.


In some rare cases I might have an entire loop all on one line like this:

Code:
while(something)DoSomethingElse();

Typically I reserve this for a very basic repetitious task. Typically I might just make a function for it instead and the while will be inside the function. Ex: waiting on threads to be ready. The same code might be in multiple places so no use making a "block" out of it.
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
Visual Studio's editor in C/C++ mode defaults to Allman, which is fine with me. It also has nice touches like auto-fixing indenting when you copy-paste code or add an outer control structure.
 

Gryz

Golden Member
Aug 28, 2010
1,551
203
106
In C++ land it is best practice to use pre-increment everywhere .... post-increment requires creating a copy of the iterator, that's immediately discarded.
Thanks for explaining. I didn't know that. It probably means there will be no way to convince her to use the i++ notation. :(

Yes, there are compiler warnings, but they're turned off by default in most compilers and, being warnings, are easily disabled or ignored.
At my current job gcc does generate a warning if you use an assignment in a test.
In that other job I had years ago, all makefiles had -Wall -Werror. That is the proper way to make sure programmers on large project don't get sloppy. In my current job we use -Werror, but lots of warnings are disabled. I understand that enabling all warnings would cause extra work. But imho it would be worthwile. I got bitten already once because I changed a 32-bit flag integer to a 64-bit flag integer, and thought I could depend on the compiler to tell me where else I needed to change variables into 64-bit. Nah. That warning was disabled.

Not to mention that assignment in a conditional *is* sometimes useful.
Sure. But I prefer the longer, more explicit version of writing code.
Code:
if ((pointer = someotherpointer) == NULL) {
    do_warning();
    return(ERROR);
}

if (!(pointer = someotherpointer)) {
    do_warning();
    return(ERROR);
}

pointer = someotherpointer;
if (!pointer) {
    do_warning();
    return(ERROR);
}
I find the 3nd way of writing down code much more readable than the first way. Unfortunately I think many programmers seem to think that the first way is "more professional", or something. The 2nd way is correct, but downright evil.
Anyway, I prefer the 3rd way, but I can deal with the first way of writing this.

Those same programmers in my company also seem to enjoy writing code like:
Code:
if (sometruth != FALSE) {
    return(FALSE);
} else {
    return(TRUE);
}
Now this really does drive me nuts. :)
 

rh71

No Lifer
Aug 28, 2001
52,853
1,048
126
When I'm scrolling down code quickly for opening and closing tags/braces, I'm looking near the left margin. It makes no sense for me to start a curly bracket at the end of a line. Indentation isn't as big a factor as that is so either Allman or GNU are fine.
 

Murloc

Diamond Member
Jun 24, 2008
5,382
65
91
I can understand your frustration. :hug:

Especially the (5 == i).
That is awful. It reads unnatural.
Because you check on i and not on 5.
But that may also have to do with our language and how we read mathematics. English and a lot of other Germanic languages are setup in such a way. Dutch is as well. From left to right.
works the same in latin languages. It's universal to write x = 2 and not 2 = x anyway.
 

Merad

Platinum Member
May 31, 2010
2,586
19
81
Thanks for explaining. I didn't know that. It probably means there will be no way to convince her to use the i++ notation. :(

If you're writing C (IIRC from past threads?) it really doesn't make a difference. Or when applied to primitives in C++. Of course, relaying this info and convincing her to change are two different matters... :)
 
May 11, 2008
19,582
1,196
126
Generally I prefer Allman...ish. Something like this:

In some rare cases I might have an entire loop all on one line like this:

Code:
while(something)DoSomethingElse();

Typically I reserve this for a very basic repetitious task. Typically I might just make a function for it instead and the while will be inside the function. Ex: waiting on threads to be ready. The same code might be in multiple places so no use making a "block" out of it.

I do this sometimes too.

When i have for example this :


Code:
if(ptmrs->timer1 != 0)
  ptmrs->timer1--;
if(ptmrs->timer2 != 0)
  ptmrs->timer2--;
if(ptmrs->timer3 != 0)
  ptmrs->timer3--;

I will write it in this way.
But only for single line statments and because it is allowed.
This is so simple, that it is easy to understand what is going on.
 

Merad

Platinum Member
May 31, 2010
2,586
19
81
I will write it in this way.
But only for single line statments and because it is allowed.
This is so simple, that it is easy to understand what is going on.

The real question in that case would be, why aren't you using an array/vector/whatever, and a loop? :p

Omitting optional braces is dangerous, and IME, not worth the risk. My firm rule is that the only time you can omit braces is on an "if" at the beginning of a method or constructor (i.e., when checking preconditions), and the if statement must either throw an exception or return.
 

Gryz

Golden Member
Aug 28, 2010
1,551
203
106
If you do it that way, just put a empty line in between.
We use Allman. But I omit the curly brackets at the start of a function, if I wanna do some generic checks on parameters and state.

Code:
void
do_my_stuff(char *name, int age)
{
    if (!name)
        return;

    if ((age < 16) || (age > 65))
        return;

    if (g_some_state != WHAT_I_EXPECT)
        return;

    /*
     * Do the real work.
     */
    for (i = 0; i < A_LOT; i++)
    ....
That way it is obvious that the first 3 ifs are simple checks to make your function a bit more robuts. The real body of the function starts after that. Imho, it should be the goal of every good programmer to make it very obvious to others what the code is doing, where the complexity is, etc. Style can help a lot there.
 
  • Like
Reactions: mxnerd

Schmide

Diamond Member
Mar 7, 2002
5,587
719
126
This is the way I like my switch statements.

Code:
      switch (value) {
         case 0: {
            do something
         }
         break;
         case 1: {
            do something else
         }
         break;
         default: {
            do do  default
         }
         break;
      }

This is the way Microsoft Visual Studio thinks I like them. I've tried everything to make it stop putting the breaks so far to the right

Code:
      switch (value) {
         case 0: {
            do something
         }
                 break;
         case 1: {
            do something else
         }
                 break;
         default: {
            do do  default
         }
                 break;
      }

Deep breaks are for techno heads
 
Last edited:
May 11, 2008
19,582
1,196
126
The real question in that case would be, why aren't you using an array/vector/whatever, and a loop? :p

Omitting optional braces is dangerous, and IME, not worth the risk. My firm rule is that the only time you can omit braces is on an "if" at the beginning of a method or constructor (i.e., when checking preconditions), and the if statement must either throw an exception or return.

I cannot use vectors. With the mcu with a arm7tdmi core that i used before, i used optimized handwritten assembly.

Code:
        SUB        r14, r14,#4                                // Adjust lr to proper address.                     
        STMFD        r13!, {r0-r7,r14}                    // Save registers to stack.

        LDR            r0,=_ASM_OS_MEM_TMR_MEM        // Load memory address of first software timer.
        LDMIA        r0!,{r1-r10}
        CMP            r1, #0                                        // Update first 10 software timers, 0 to 9.
        SUBNE        r1, r1, #1 
        CMP            r2,    #0
        SUBNE        r2, r2, #1 
        CMP            r3,    #0
        SUBNE        r3, r3, #1 
        CMP            r4,    #0
        SUBNE        r4, r4, #1 
        CMP            r5,    #0
        SUBNE        r5, r5, #1 
        CMP            r6,    #0
        SUBNE        r6, r6, #1 
        CMP            r7,    #0
        SUBNE        r7, r7, #1 
        CMP            r8,    #0
        SUBNE        r8, r8, #1 
        CMP            r9,    #0
        SUBNE        r9, r9, #1 
        CMP            r10,    #0
        SUBNE        r10, r10, #1 
        LDR            r0,=_ASM_OS_MEM_TMR_MEM       
        STMIA        r0!,{r1-r10}
        
        LDR            r0,=_ASM_OS_MEM_TMR_MEM2    // Load memory address of software timer 10.
        LDMIA        r0!,{r1-r10}
        CMP            r1, #0                                        // Update second 10 software timers, 10 to 19.
        SUBNE        r1, r1, #1 
        CMP            r2,    #0
        SUBNE        r2, r2, #1 
        CMP            r3,    #0
        SUBNE        r3, r3, #1 
        CMP            r4,    #0
        SUBNE        r4, r4, #1 
        CMP            r5,    #0
        SUBNE        r5, r5, #1 
        CMP            r6,    #0
        SUBNE        r6, r6, #1 
        CMP            r7,    #0
        SUBNE        r7, r7, #1 
        CMP            r8,    #0
        SUBNE        r8, r8, #1 
        CMP            r9,    #0
        SUBNE        r9, r9, #1 
        CMP            r10,    #0
        SUBNE        r10, r10, #1 
        LDR            r0,=_ASM_OS_MEM_TMR_MEM2       
        STMIA        r0!,{r1-r10}
        
        MOV        r14,pc                                          // Store the return address (=pc+4) in r14 (=lr).
        BX         r12                                                 // Branch to address pointed to by r12.

        LDMFD        r13!,{r0-r7,pc}^                        // Restore registers and return to code that was interrupted.


Now i use thumb2 because i am playing around with a cortex m4 mcu, and thumb2 does not have the conditional execution flags embedded in every instruction such as ARM instructions have.
Also, the timers are 32 bit wide.
I could reduce them to 16 bit but i am not sure the thumb2 instruction set has such instructions to perform a compare and subtract 2 16 bit values in a two instructions.


I only omit braces with a single execution line in an if statement. :)
And the indentation makes it easier to read.
 

HumblePie

Lifer
Oct 30, 2000
14,667
440
126
I prefer K&R style. Where the bracket after the if or while is on the same line. But where I work now we use Allman style. It was relatively easy to get adjusted.

The reason I reacted a little strong at your similar question a few weeks ago, is because coding style at my current job. When I applied for the job, I asked them: "do you have a coding style". Their answer was: "not one style for everyone, but each sub-component of our software has its own style". That turned out to be not true. Sometimes each file has a different style. Sometimes each function. Sometimes I see 3 different style on one line. It drives me nuts. Or depressed. It really makes me depressed sometimes for an hour when I see new code, just checked in last week by a colleague from over-sees.

In a previous job, long time ago, we had hundreds if not 1000+ programmers working on one software system. And they all used K&R style. And when someone would do something ugly, or something stupid, they would get corrected. In my current job, it's almost forbidden to criticize the coding-style of a colleague. Unless his code crashes. It's unbelievable.

Your eyes get used to seeing patterns. If code is written in one style, you see quicker what is going on. You see quicker when something is unusual, and requires a little extra thought to make sure you understand what is going on. If you use 10 different coding styles in a file, your mind is constantly on alert. "Do I understand what is going on here ? Did I miss a subtle thing ?"

I'll give you an example that I saw this week in our own code. In all my years of programming, I've only ever seen people write code like:
Code:
for (i = 0; i < max; i++)
Right ?
When you increment something, you write: i++; counter++; pointer++;
This one programmer in our over-seas team writes: ++i; ++counter; ++pointer;

It drives me nuts. Usually when you use ++(*pointer) in stead of (*pointer)++, it is for a reason. If you change the location of the increment, the behaviour of your code changes. Doesn't happen often, but sometimes it does. You immediately are on alert when you see the ++ before the expression. But no, my colleague has to write ++i;
Pfff. :)

She also like to write:
Code:
if (NULL == pointer)
{

Switching the left and right operand of the comparison. I understand why she does it. To prevent mistakes like "if (pointer = NULL)". But you know, we got a compiler to warn us for that. Switching the operands is unusual. And it hurts my eyes. I might look like a whiner, but I know I am not the only one who doesn't like "if (5 == i)". And there are dozens of examples like this.

I think it begins with realizing why it is important to write code that is readable. Code is written once. But if you write professional code, your code will be read hunderds if not thousands of times. If you spend and extra few seconds, or an extra minute, to make your code better readable, it will always pay off in the long run. Some people don't realize this. It can be hard to convince them (or, in my opinion, educate them).

So the first time I speak with the lead-programmer of the component I am working at. He says: "our code is old, has been changed a lot, lots of people worked on it. The comments are often not correct any more. So I have removed a lot of comment over the last years". I asked "but then you add new comments, right" ? Nope. He proudly told me he only removes comments. Hardly ever adds any.

It's taken me a year to start understand how our code hangs together.
Some of my colleagues think they save the company money by not worrying about comments, in-code documentation, coding-style, names of functions and variables.
But my boss just paid me a year's worth of salary, just for me to understand what we're doing.
And every new hire has to go through that process.

So yes, William (OP), your question is very relevant imho.

I prefer K&R over Allman, because when you have 1 line if-clauses, you pay only 1 line penalty of adding curly-brackets. Consider these examples:
Code:
if (i == 8)
    do_something();

if (i == 9)
{
    do_something();
}

if (i == 10) {
    do_something();
}
I prefer the last style. But right now I am using a mix of the first 2 styles. Because the others in my group do that.
I don't like the GNU-style at all. 2-Space indentation makes it harder to see where the curly brackets belong.


I HATE that last style. If you ever have to open that code up in something without some form of intellisense, like notepad, then it's a massive PITA figuring out scope of nest code sequences. If you have the open and closing brackets on the same indent level all the time, it doesn't matter what you are using to view the code. It always lines up properly. It always allows you to figure out what scope you are in.

I prefer using 2 only, but can deal with 1 as well. 3 just bugs the bajeebus out of me and anyone that uses it.
 
Last edited:

Malogeek

Golden Member
Mar 5, 2017
1,390
778
136
yaktribe.org
I don't know the name, but I general do this:
Code:
if (whatever) {
    something();
}
I always write in this way as well. Allman makes more sense for matching brackets visually but I've just always preferred this method instead. It's not really a good way for others reviewing your code though.
 

smackababy

Lifer
Oct 30, 2008
27,024
79
86
I always write in this way as well. Allman makes more sense for matching brackets visually but I've just always preferred this method instead. It's not really a good way for others reviewing your code though.
Depends what you're doing. I write a lot of functional code and it makes it easier to have each "verb" per line.
Code:
var someArray.map((item) => {
     return transform(item);
}).reduce((agg, item) => {
     if(item.something) return agg;
     return agg.concat(item.whatever);
}).foreach((each) => {
     show(each);
});