﻿# Table\-style code formatting

Table\-style code formatting enhances code readability and clarity\. This streamlines [code reviews](https://pvs-studio.com/en/blog/terms/0073/) 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](https://pvs-studio.com/en/docs/warnings/v560/) A part of conditional expression is always true: 10035L\.

```cpp
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:

```cpp
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\.

```cpp
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:

1. the error remains difficult to spot;
1. 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:

```cpp
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:

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

But this way requires much less effort:

```cpp
   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:

```cpp
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:

```cpp
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:

```cpp
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:

```cpp
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](https://pvs-studio.com/en/blog/examples/v536/) 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](https://pvs-studio.com/en/docs/warnings/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"\.

```cpp
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:

```cpp
  ....
  "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\.

```cpp
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:

```cpp
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

1. Andrey Karpov\. [Common patterns of typos in programming](https://pvs-studio.com/en/blog/posts/cpp/1064/)\.
1. Andrey Karpov\. [The Ultimate Question of Programming, Refactoring, and Everything](https://pvs-studio.com/en/blog/posts/cpp/0391/)\.