cpointersformatting

Reasoning behind Barr C Coding Standard: Why have white spaces around asterisk in pointer declaration?


The Barr C Coding Standard 2018 has the Rule 3.1e:

The pointer operators * and & shall be written with white space on each side within declarations but otherwise without a space on the operand side.

The reasoning given for this rule is rather vague:

Reasoning: In source code, the placement of white space is as important as the placement of text. Good use of white space reduces eyestrain and increases the ability of programmers and reviewers of the code to spot potential bugs.

Is there some more precise reason why I would want to place whitespaces on both sides of the asterisk?
In a declaration I would personally prefer to write the asterisk directly in front of the variable name:

int *pBuffer;

This way I think it is immediatly clear where the asterisk is belonging to. Especially to avoid ambiguity if someone tries to declare several pointers in one line:

int * pBuffer, pReceive;    // pBuffer is actual pointer, pReceive is not

But I assume the Barr people have some real reasoning for their rule. Can somebody enlighten me why this formatting might make sense?


Solution

  • First, I have a small issue with the wording in the rule: * in pointer declarator is not an operator; only the * deference operator is, because it actually does an operation.

    While I don't know why Barr has that rule, personally I prefer it because of the consistency with more complicated declarations:

    // Pointer is clearly visible
    int const volatile * const volatile foo = ...;  
    
    // Looks awkward, possibly a typo
    int const volatile *const volatile foo = ...;   
    

    Declaring multiple variables within the same declaration is not a good practice, especially when pointers are involved:

    int volatile * const foo, const bar; // What?!