Unicorn with delicious cookie
Nous utilisons des cookies pour améliorer votre expérience de navigation. En savoir plus
Accepter
to the top
>
>
>
Table-style code formatting

Table-style code formatting

25 Fév 2025

Table-style code formatting enhances code readability and clarity. This streamlines code reviews and helps catch errors and typos more easily.

Principle of use

Let's examine a code snippet from the ReactOS project, where PVS-Studio detected an error:

V560 A part of conditional expression is always true: 10035L.

void adns__querysend_tcp(adns_query qu, struct timeval now) {
  ....
  if (!(errno == EAGAIN || EWOULDBLOCK || 
        errno == EINTR || errno == ENOSPC ||
        errno == ENOBUFS || errno == ENOMEM)) {
  ....
}

This is a small code fragment—it's not hard to spot the error here. However, this can be much harder to catch it in real cases. Developers may simply skip similar comparison blocks without paying much attention.

Why do developers overlook such bugs? We tend to miss such errors and don't want to read them carefully because the conditions are poorly formatted. We think that if checks are of the same type and written by one code author, it means that they will be correct, with no errors in conditions.

But a solution exists—it's table-style formatting.

In this case, the error is that a developer forgot to write errno ==. As a result, the condition is always true, since the EWOULDBLOCK constant is 10035.

Here's the fixed code:

if (!(errno == EAGAIN || errno == EWOULDBLOCK || 
      errno == EINTR || errno == ENOSPC ||
      errno == ENOBUFS || errno == ENOMEM)) {

Now, let's explore how to refactor this code snippet better. First, take a look at the code formatted using a basic table-style formatting approach.

if (!(errno == EAGAIN  || EWOULDBLOCK     || 
      errno == EINTR   || errno == ENOSPC ||
      errno == ENOBUFS || errno == ENOMEM)) {

Although this improves readability somewhat, it's still not ideal for two reasons:

  • the error remains difficult to spot;
  • we need to insert many spaces for alignment.

That's why we need to enhance code formatting using two approaches. Firstly, don't add more than one comparison per line—this makes the error easy to catch and the typo more conspicuous:

a == 1 &&
b == 2 &&
c      &&
d == 3 &&

Secondly, it's better to write operators (&&, ||, etc.) at the beginning of the line rather than at the end.

Notice how much work it takes to write spaces:

x == a          &&
y == bbbbb      &&
z == cccccccccc &&

But this way requires much less effort:

   x == a
&& y == bbbbb
&& z == cccccccccc

The code looks unusual, but it's easy to get used to it. That's why we recommend this approach to code formatting.

Let's combine it all together and rewrite the code in this improved style:

if (!(   errno == EAGAIN
      || EWOULDBLOCK
      || errno == EINTR
      || errno == ENOSPC
      || errno == ENOBUFS
      || errno == ENOMEM)) {

Yes, the code now takes up more lines, but the error is much more noticeable. The increased line count is not an issue—readability and typo prevention matter far more than minimizing the number of lines.

Let's continue refactoring:

const bool error =    errno == EAGAIN
                   || errno == EWOULDBLOCK
                   || errno == EINTR
                   || errno == ENOSPC
                   || errno == ENOBUFS
                   || errno == ENOMEM;
if (!error) {

Developers can also put the check into the function:

static bool IsInterestingError(int errno)
{
  return    errno == EAGAIN
         || errno == EWOULDBLOCK
         || errno == EINTR
         || errno == ENOSPC
         || errno == ENOBUFS
         || errno == ENOMEM;
}
....
if (!IsInterestingError(errno)) {

Drawbacks

In rare cases, table-style formatting can be detrimental.

Here's an example:

inline 
void elxLuminocity(const PixelRGBi& iPixel,
                   LuminanceCell< PixelRGBi >& oCell)
{
  oCell._luminance = 2220*iPixel._red +
                     7067*iPixel._blue +
                     0713*iPixel._green;
  oCell._pixel = iPixel;
}

We found this code in the eLynx SDK proejct. Developers aimed to align the code and write 0 before 713. Unfortunately, they forgot that 0 as the beginning of the number means it'll be in octal format.

String array

Table-style formatting can be applied to all language constructs, not just conditions.

The next code snippet comes from the Asterisk project, where PVS-Studio has detected an error:

V653 A suspicious string consisting of two parts is used for array initialization. It is possible that a comma is missing. Consider inspecting this literal: "KW_INCLUDES" "KW_JUMP".

static char *token_equivs1[] =
{
  ....
  "KW_IF",
  "KW_IGNOREPAT",
  "KW_INCLUDES"
  "KW_JUMP",
  "KW_MACRO",
  "KW_PATTERN",
  ....
};

Here is a typo: a developer forgot a comma. As a result, two separate strings with different meanings are combined into one, i.e. the compiler interprets it as follows:

  ....
  "KW_INCLUDESKW_JUMP",
  ....

The error could have been avoided by applying table-style formatting. In such a case, a developer can easily spot a missed comma.

static char *token_equivs1[] =
{
  ....
  "KW_IF"        ,
  "KW_IGNOREPAT" ,
  "KW_INCLUDES"  ,
  "KW_JUMP"      ,
  "KW_MACRO"     ,
  "KW_PATTERN"   ,
  ....
};

Note: If we place a separator—in this case, it's a comma—on the right, we need to add extra spaces, which is inconvenient. This becomes even more troublesome if we add a new long line or expression—we'll have to reformat the whole table.

Therefore, it's better to format the code as follows:

static char *token_equivs1[] =
{
  ....
  , "KW_IF"
  , "KW_IGNOREPAT"
  , "KW_INCLUDES"
  , "KW_JUMP"
  , "KW_MACRO"
  , "KW_PATTERN"
  ....
};

Now, we can easily notice a missing comma and avoid adding spaces. The code looks neat and clear. While this formatting style may seem unconventional at first, it's easy to adapt to.

Additional information

Popular related articles

S'abonner

Comments (0)

close comment form
close form

Remplissez le formulaire ci‑dessous en 2 étapes simples :

Vos coordonnées :

Étape 1
Félicitations ! Voici votre code promo !

Type de licence souhaité :

Étape 2
Team license
Enterprise licence
** En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité
close form
Demandez des tarifs
Nouvelle licence
Renouvellement de licence
--Sélectionnez la devise--
USD
EUR
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
La licence PVS‑Studio gratuit pour les spécialistes Microsoft MVP
close form
Pour obtenir la licence de votre projet open source, s’il vous plait rempliez ce formulaire
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
I want to join the test
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
check circle
Votre message a été envoyé.

Nous vous répondrons à


Si l'e-mail n'apparaît pas dans votre boîte de réception, recherchez-le dans l'un des dossiers suivants:

  • Promotion
  • Notifications
  • Spam