﻿# Terrible tips for a C\+\+ developer: 2026 edition, Part 2

We're introducing an updated edition of the terrible tips for a C\+\+ developer book\. We'll be posting it on our blog in parts\. The book includes a total of 60 tips\.

Each part will feature a list of "tips" that developers really shouldn't follow\. Each tip comes with an explanation of why it's bad, as well as a breakdown of its less obvious aspects\. This series is designed to help beginner programmers learn the ropes, while entertaining experienced developers with some of the more unexpected C\+\+ quirks\.

![1431_terrible_tips_pt2/image1.png](https://import.viva64.com/docx/blog/1431_terrible_tips_pt2/image1.png)

## Terrible tip N5\. printf, printf, printf, printf

**I'll call the printf function as many times as there are lines to print\. We've always done it this way\.**

Although the previous case is unusual, developers often overuse the `printf` function\. A lot of them have written this way and continue to do so\. This style also appears in AI\-generated code\. In other words, we taught it some bad habits\.

Here's an example of the generated code:

```cpp
printf("File System Commands:\n");
printf("  ls                    - List all files in RAMFS\n");
printf("  cat <filename>        - Display file contents\n");
printf("  touch <file> <text>   - Create/update file with content\n");
printf("  vtext <filename>      - Open text editor (F12=Save, F4=Exit)\n");
printf("\nSystem Commands:\n");
printf("  clear                 - Clear the screen\n");
printf("  help                  - Show this help message\n");
printf("  info                  - Display system information\n");
printf("  test                  - Interactive input test\n");
```

The code works, but it's redundant\. There's no point in calling the slow `printf` function over and over again; you can do it more efficiently:

```cpp
printf("File System Commands:\n"
       "  ls                    - List all files in RAMFS\n"
       "  cat <filename>        - Display file contents\n"
       "  touch <file> <text>   - Create/update file with content\n"
       "  vtext <filename>      - Open text editor (F12=Save, F4=Exit)\n"
       "\nSystem Commands:\n"
       "  clear                 - Clear the screen\n"
       "  help                  - Show this help message\n"
       "  info                  - Display system information\n"
       "  test                  - Interactive input test\n");
```

The code is now shorter and faster\.

Of course, optimization isn't required when printing informational text\. However, in some cases, you can achieve significant performance improvements by reducing the number of calls to formatting functions within loops\.

However, there's more to it\. The code above is easy to break when someone modifies it\. You might accidentally include an escape sequence such as `%i`\. This can happen when a character is part of the text and you simply don't think to escape it\.

We'll discuss security vulnerabilities associated with the `printf` function in one of the following chapters\. One more improvement is worth making for now: use the `puts` function instead\. It's short, fast, and safe:

```cpp
puts("File System Commands:\n"
     "  ls                    - List all files in RAMFS\n"
     "  cat <filename>        - Display file contents\n"
     "  touch <file> <text>   - Create/update file with content\n"
     "  vtext <filename>      - Open text editor (F12=Save, F4=Exit)\n"
     "\nSystem Commands:\n"
     "  clear                 - Clear the screen\n"
     "  help                  - Show this help message\n"
     "  info                  - Display system information\n"
     "  test                  - Interactive input test");
```

The only thing to keep in mind is that `puts` appends a newline character to the end of the string\. So, to make sure the printed output matches the previous version, I removed one `\n` from the text\.

## Terrible tip N6\. Macros are cool

**Use macros everywhere, especially nested ones\. It's a good way to shorten code, and you'll free up hard drive space\. It'll also entertain your colleagues while they're debugging it\.**

C\+\+ offers plenty of ways to avoid macros\. I strongly recommend using them as sparingly as possible\.

Let me be clear: I'm not a zealot, and I'm not suggesting we abandon macros for idealistic reasons\. For example, macros can be perfectly acceptable when you need to generate repetitive code\. I also have no problem with macros in legacy applications built with MFC\. There's no point in fighting something like this:

```cpp
BEGIN_MESSAGE_MAP(efcDialog, EFCDIALOG_PARENT )
  //{{AFX_MSG_MAP(efcDialog)
  ON_WM_CREATE()
  ON_WM_DESTROY()
  //}}AFX_MSG_MAP
END_MESSAGE_MAP()
```

Some macros are just part of the landscape, and that's fine\. They really were designed to make programming easier\.

I'm talking about a different kind of macro: one that developers use to avoid creating a proper function or to shorten an existing one\. Let's look at a few reasons to avoid such macros\.

### First: code that uses macros often attracts bugs

I can't explain why this happens from a philosophical standpoint, but it does\. Furthermore, bugs involving macros are often difficult to spot during [code reviews](https://pvs-studio.com/en/blog/terms/0073/)\.

I've described several such cases in my articles\. For example, in the Midnight Commander project, I found that the `isspace` function had been replaced with the following macro:

```cpp
#define isspace(c) ((c)==' ' || (c) == '\t')
```

This macro caused a loop condition to behave incorrectly\. The developers who used `isspace` assumed they were calling the actual function that treats as whitespace spaces, tabs, and other characters:

* form feed \(0x0c, '\\f'\);
* line feed \(LF, 0x0a, '\\n'\);
* carriage return \(CR, 0x0d, '\\r'\);
* vertical tab \(0x0b, '\\v'\)\.

What about this way of shortening `std::printf`?

```cpp
#define sprintf std::printf
```

Somebody got carried away with macros in the StarEngine project to shorten function calls from the standard library:

|\`\`\`cpp<br>\.\.\.\.<br>\#define scout std::cout<br>\#define sstringstream std::stringstream<br>\#define sofstream std::ofstream<br>\#define sifstream std::ifstream<br>\#define sfstream std::fstream<br>\.\.\.\.<br>\`\`\`||

Another developer walked right into this carefully laid trap\. I think they intended to call the standard `sprintf` function here to print to the buffer:

```cpp
sprintf(buf, "%d", value);
```

Instead, they called the `std::printf` function\. The icing on the cake is a format string \(the first argument\) that is an uninitialized buffer designed for writing, not for reading\.

One might argue that the programmers are to blame for these errors, not the macros\. That's right\. Of course, programmers are always responsible for their mistakes\. Although\.\.\.

The key issue is that macros cause errors\. So, macros should be used with extreme caution—or not at all\. Now, let's look at a couple more examples to drive the point home\.

The ATL library offers string conversion macros, including `A2W`, `T2W`, etc\. However, few developers realize how dangerous it is to use them in loops\. These macros call the `alloca` function, meaning that each loop iteration allocates more memory on the stack\. Although the program may appear to work correctly, it can run out of stack space at any moment if it starts processing longer strings or the number of loop iterations increases\.

Macros like `A2W` look innocent only on the surface\. They look like functions but actually have side effects that are difficult to detect\.

Also, I can't ignore such attempts to shorten code using macros:

```cpp
void initialize_sanitizer_builtins (void)
{
  ....
  #define DEF_SANITIZER_BUILTIN(ENUM, NAME, TYPE, ATTRS) \
  decl = add_builtin_function ("__builtin_" NAME, TYPE, ENUM, \
             BUILT_IN_NORMAL, NAME, NULL_TREE);  \
  set_call_expr_flags (decl, ATTRS);          \
  set_builtin_decl (ENUM, decl, true);

  #include "sanitizer.def"

  if ((flag_sanitize & SANITIZE_OBJECT_SIZE)
      && !builtin_decl_implicit_p (BUILT_IN_OBJECT_SIZE))
    DEF_SANITIZER_BUILTIN (BUILT_IN_OBJECT_SIZE, "object_size",
         BT_FN_SIZE_CONST_PTR_INT,
         ATTR_PURE_NOTHROW_LEAF_LIST)
  ....
}
```

Only the first line in the macro belongs to the `if` statement\. The remaining lines execute regardless of the condition\. You could call this a C\-style bug since I found it in the GCC compiler using PVS\-Studio\. GCC is written primarily in C, a language where it's hard to get by without macros\. However, a proper function would have worked just as well here\.

### Second: macros make code harder to read

If you've ever worked on a project full of macros that were built from other macros, then you know how difficult it can be to understand such code\. If you haven't, take my word for it: it's not a pleasant experience\. The GCC compiler I mentioned earlier is one example of code that's particularly hard to follow\.

According to a popular story, Apple invested in LLVM as an alternative to GCC because GCC's code had become too complex due to its heavy reliance on macros\. I can't remember where I read this, though, so I can't provide any sources\.

### Third: writing macros is difficult

It's easy to write a bad macro\. I often encounter bugs in code that result from poorly written macros\. However, writing a good, reliable macro is often harder than implementing an equivalent function\.

Unlike a function, a macro can't be treated as a standalone entity, which is why it's different\. A developer has to consider it in the context of every possible use case right from the start\. Otherwise, they may easily encounter an issue like this:

```cpp
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
m = MIN(ArrayA[i++], ArrayB[j++]);
```

The `i` and `j` variables will be incremented not once, but twice\.

Of course, workarounds for such cases have long been invented, so the macro can be implemented safely:

```cpp
#define MAX(a,b) \
   ({ __typeof__ (a) _a = (a); \
      __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })
```

However, here's the question: do we really need all of this in C\+\+? No, C\+\+ has templates and other ways to write efficient code\. So, why do I keep seeing such macros in C\+\+ programs?

### Fourth: debugging becomes more difficult

Some people believe debugging is for the weak\. You should write bug\-free code from the start instead of hunting for bugs with a debugger\. Blah, blah, blah\.\.\. That's certainly an interesting topic to discuss, but in real projects, debugging is useful and helps developers find bugs\. Macros complicate the process and definitely slow down bug hunting\.

### Fifth: false positives of static code analyzers

Due to the way they work, many macros generate numerous false positives in static analyzers\. I can confidently say that most false positives in C and C\+\+ code analysis stem from macros\. Analyzers simply can't distinguish between clever, correct code and buggy one\.

### What can we do?

Let's avoid using macros in C\+\+ programs unless absolutely necessary\.

C\+\+ offers a rich set of tools, including function templates, automatic type deduction \(`auto`, `decltype`\), and constexpr functions\.

In almost every case, you can write a function instead of a macro\. Developers often avoid doing so out of sheer laziness\. Such laziness does more harm than good, and we should fight it\. The extra time you spend writing a proper function will pay off many times over\. Your code will be easier to read and maintain\. You'll also be less likely to make mistakes, and compilers and static analyzers will produce fewer false positives\.

Someone might argue that code that uses a function is less efficient\. That's just another excuse\.

Modern compilers do an excellent job of inlining code, even if you don't explicitly use the `inline` keyword\.

Evaluating expressions at compile time doesn't require macros as well\. In fact, they can cause more problems than they solve\. Using `constexpr` is a much better and safer way to achieve the same result\.

Let me show you an example\. My colleague found this classic macro error in the FreeBSD kernel:

```cpp
#define ICB2400_VPOPT_WRITE_SIZE 20

#define  ICB2400_VPINFO_PORT_OFF(chan) \
  (ICB2400_VPINFO_OFF +                \
   sizeof (isp_icb_2400_vpinfo_t) +    \
  (chan * ICB2400_VPOPT_WRITE_SIZE))          // <=

static void
isp_fibre_init_2400(ispsoftc_t *isp)
{
  ....
  if (ISP_CAP_VP0(isp))
    off += ICB2400_VPINFO_PORT_OFF(chan);
  else
    off += ICB2400_VPINFO_PORT_OFF(chan - 1); // <=
  ....
}
```

The `chan` argument is used in the macro without being wrapped in parentheses\. As a result, the `ICB2400_VPOPT_WRITE_SIZE` constant is multiplied not by the expression `(chan - 1)`, but only by one\.

Here's the expanded macro:

```cpp
off += (ICB2400_VPINFO_OFF + sizeof(isp_icb_2400_vpinfo_t) +
       (chan - 1 * ICB2400_VPOPT_WRITE_SIZE));
```

The error wouldn't have occurred if a regular function had been written instead of a macro:

```cpp
size_t ICB2400_VPINFO_PORT_OFF(size_t chan)
{
  return   ICB2400_VPINFO_OFF
         + sizeof(isp_icb_2400_vpinfo_t)
         + chan * ICB2400_VPOPT_WRITE_SIZE;
}
```

Modern C and C\+\+ compilers will most likely inline the function automatically, making the code just as efficient as its macro\-based equivalent\.

At the same time, the code becomes easier to read and no longer suffers from the issue described earlier\.

If you know that the input value is always a constant, you can add `constexpr` to ensure the compiler performs all calculations at compile time\. The FreeBSD kernel is written in C, but let's assume we're working with C\+\+ and `chan` is a constant\. In that case, it's best to declare the `ICB2400_VPINFO_PORT_OFF` function as follows:

```cpp
constexpr size_t ICB2400_VPINFO_PORT_OFF(size_t chan)
{
  return   ICB2400_VPINFO_OFF
         + sizeof(isp_icb_2400_vpinfo_t)
         + chan * ICB2400_VPOPT_WRITE_SIZE;
}
```

I hope I've managed to convince you\. Wishing you as few macros as possible in your code\!

## Terrible tip N7\. Disable warnings

**Disable compiler warnings\. They distract you from your work, making it more difficult to write concise code\.**

Developers know that compiler warnings are their friends\. They help catch bugs at compile time\. It's much easier and faster to fix an error based on a compiler warning than to debug code that doesn't work\.

However, I've encountered a situation where some components in a large project were compiled with all warnings disabled\.

After writing some new code and running the application, I saw that it wasn't behaving as expected\. When I went back over my code, I spotted an error and quickly fixed it\. But I was surprised that the compiler hadn't issued a warning\. It was a serious error, similar to using an uninitialized variable\. I knew for sure that the compiler should have issued a warning about code like that, but it didn't\.

A brief investigation revealed that warnings had been disabled entirely in the DLL module being compiled and in several others\. Then, I brought in some senior colleagues to investigate further what had happened\.

For several years, these modules had been compiled with warnings disabled\. At some point, one of the developers was assigned to migrate the build to a more recent compiler version\. And that's exactly what they did\. The updated compiler began issuing new warnings, especially in the legacy code these modules use\.

The reasons behind the developer's actions remain unclear, but it appears they simply disabled warnings in some modules\. Maybe they planned to do this temporarily so that warnings wouldn't interfere with fixing compilation errors, but then they forgot to enable them\. Unfortunately, we couldn't determine what exactly happened because the developer had already left the company\.

After re\-enabling warnings, I spent some time refactoring the code so the compiler would stop issuing them\. It wasn't too demanding, though\. The whole job took just one day\. While working through the warnings, I also fixed several other bugs that had gone unnoticed until then\. Learn to appreciate warnings from the compiler and static analyzer\!

**A useful tip**

Try to keep your project completely free of compiler warnings\. Otherwise, you'll see the [broken windows theory](https://en.wikipedia.org/wiki/Broken_windows_theory) in action\. If your code always produces 10 warnings when compiled, an 11th one won't seem like a big deal\. Even if you don't write code that triggers warnings, your colleagues might\. If everyone treats this as acceptable, the situation quickly spirals out of control\. The more warnings the compiler issues, the less attention people pay to new ones\.

Moreover, warnings will gradually lose their significance\. If you're used to the compiler constantly issuing warnings, you might miss a new one pointing to a real error in your latest code\.

**\-Werror**

Here's another useful tip: set the compiler to treat warnings as errors\. This creates a zero\-tolerance policy for warnings across your team\. You will either fix warnings or explicitly suppress them\. Otherwise, the code simply won't compile\. This approach can do wonders for code quality\.

However, there's a downside: whenever you update the compiler or any of your dependencies, you'll have to spend extra time fixing warnings that have become compilation errors\.

A compiler update may introduce new diagnostic rules or improve existing ones\. As a result, your code may stop compiling, forcing you to refactor it immediately\. The same applies to libraries, which may alter their interfaces, macros, and other components\.

Is this a reason to avoid `-Werror`? No, but it's best to be prepared for these potential issues\.

## Terrible tip N8\. The shorter the variable name, the better

**Use one or two letters to name variables\. This way you'll fit a more complex expression on one line on the screen\.**

This approach does allow you to write shorter code\. But it'll be just as short as it's incomprehensible when you come back to it later\. Without meaningful variable names, such code becomes write\-only\. You can write it and even debug it right away, while you still remember what each variable stands for, but once some time has passed, making sense of that code will be extremely difficult\.

Another way to ruin code is to use abbreviations instead of meaningful variable names\. For example, writing `AC` instead of `ArrayCapacity`\.

In the first case, it's clear that we're talking about capacity, or the amount of memory reserved for a container\. In the second, we have to guess what the mysterious `AC` stands for\.

**Should you always avoid short names? No\.** Use common sense\. It's perfectly fine to use names like `i`, `j`, and `k` for loop counters\. This is a well\-established convention, so any programmer can easily understand code that uses these names\.

Abbreviations can also make sense in some cases, such as code that implements numerical methods, simulates processes, and so on\. Such code simply performs calculations based on specific formulas described in comments or documentation\. If a variable in a formula is called `SC0`, it makes sense to use the same name in your code\.

For example, take a look at variable declarations in the COVID\-19 CovidSim Model project:

```cpp
int n;             /**< number of people in cell */
int S, L, I, R, D; /**< S, L, I, R, D are numbers of Susceptible,
                    Latently infected, Infectious,
                    Recovered and Dead people in cell */
```

These variable names are valid\. Their meanings are explained in the comments\. Such naming conventions enable compact notation of formulas:

```cpp
Cells[i].S = Cells[i].n;
Cells[i].L = Cells[i].I = Cells[i].R = Cells[i].cumTC = Cells[i].D = 0;
Cells[i].infected = Cells[i].latent = Cells[i].susceptible + Cells[i].S;
```

I'm not saying this is a good approach or coding style, but sometimes short names are the most practical choice\. Think carefully about every recommendation, rule, and methodology\. Understand when it's worth making an exception and when it isn't\.

"Code Complete" is a useful book that offers insights into naming variables, classes, and functions\. I highly recommend reading the relevant chapter, as well as the entire book\.

## Terrible tip N9\. Magic numbers

**Use strange numbers\. This way, your program code will look smarter and more impressive\. Doesn't this code line look hardcore: qw \= ty / 65 \- 29 \* s;?**

Numbers with no obvious purpose in code are called magic numbers\. Using them is considered poor programming practice because it makes the code difficult to understand\.

A magic number has no meaning on its own and can cause confusion when it appears in code without any context or an explanatory comment\. Changing it to another number, even a similar one, can have unpredictable consequences\. Magic numbers decrease code portability across platforms and increase the overall cost of project maintenance and development\.

Using named constants and enums instead of raw numbers is better\. However, it doesn't mean that every constant needs a name\. Firstly, some constants, such as `0` or `1`, have an obvious purpose\. Secondly, naming every numeric constant in programs that perform mathematical calculations may actually make them harder to read\. In such cases, comments explaining the formulas are a better choice\.

Unfortunately, it's impossible to cover all the techniques for writing clean, readable code in a single chapter\. So, I once again encourage you to read "Code Complete", the book I mentioned in the previous chapter\.

Sometimes, it's easy to guess what a particular number in the code represents\. In that case, you wouldn't really call it a magic number\. However, these numbers can still cause problems\. Let's look at a few examples\.

The **first example** is from a game developers' article\. I read it about ten years ago, so I don't remember the title or who posted it\. The article described how a company developed a custom static analyzer for in\-house use that could detect issues specific to game code\. One of the diagnostic rules looked for constants such as 1024, 1600, and so on\. These numbers represent screen resolutions in pixels\. A developer might quickly test something by using these values, then forget to replace them with calls to the appropriate functions\.

The issue with these numbers isn't that they're difficult to identify\. A developer will quickly realize that a number is related to the number of pixels on the screen\. The real issue is that the defect is visible only during testing when different screen resolutions are used\.

The **second example** is pi\. One day, PVS\-Studio static analyzer prompted us to take a closer look at this code in the Bullet Physics SDK:

```cpp
float yScale = 1.0 / tan((3.141592538 / 180.0) * fov / 2);
```

It didn't like the number `3.141592538`, which is the one and only mathematical constant Pi\. What's wrong with it? Does the analyzer report every number?

No\. Here's the catch: this number just looks like Pi\. In reality, it's not Pi at all\. The number is incorrect\.

```cpp
This is what's written in the code: 3.141592 53 8
This is the real Pi: 3.14159265358
```

`6` and `5` are missing\. Sure, it's not a big deal\. This error has little effect on calculation accuracy\. However, it would be better if the code author didn't try to show off their knowledge by writing Pi from memory, since the `M_PI` named constant already exists\.

The **third example** is type sizes\. In my articles, I've often described the errors that occur when porting applications, for example, from 32\-bit to 64\-bit architecture\. When it comes to magic numbers, we're talking about errors in buffer size calculations or incorrect bitwise operations\.

```cpp
size_t values[ARRAY_SIZE];
memset(values, 0, ARRAY_SIZE * 4);
```

This is a classic error: a programmer assumed that `[size_t](https://pvs-studio.com/en/blog/terms/0044/)` was 4 bytes\. That was true in a 32\-bit program, but in a 64\-bit one, `size_t` is 8 bytes\. As a result, only half the buffer is filled with zeroes\.

We'll continue discussing data types in the next chapter, but for now, here's another example of a bit\-related error\. I encountered the following code once:

```cpp
// constant '1111..110000'
const size_t M = 0xFFFFFFF0u;
```

Judging by the comment, the programmer expects the `M` constant to have all bits set to one, except for the four least significant bits\. However, when building a 64\-bit application, the result will differ from what they expect\.

The `0xFFFFFFF0u` constant has the `unsigned int` type\. When expanded to `size_t`, which is an eight\-byte unsigned type, the most significant bits are filled with zeros\.

In other words, the constant has the following binary representation:

```cpp
00000000,00000000,00000000,00000000,11111111,11111111,11111111,11110000
```

However, writing the fixed code still requires using some constant:

```cpp
// constant '1111..110000'
const size_t M = ~(static_cast<size_t>(0xF));
```

In any case, forewarned is forearmed\. Be careful with code that contains explicit numeric constants\.

P\.S\. This code can actually be shortened, but it isn't necessary:

```cpp
const size_t M = ~0xF;
```

The `0xF` constant is of the `int` type\. So, after bit inversion, the `0xFFFFFFF0` value will become signed\. When converted to `size_t`, the value first expanded to the `0xFFFFFFFFFFFFFFF0` signed value of the `[ptrdiff_t](https://pvs-studio.com/en/blog/terms/0041/)` type\. Only then does it become the required unsigned value, `0xFFFFFFFFFFFFFFF0u`\. The approach involves so many unobvious factors that it's better to avoid it\. I'd go with the first option: it's longer, but much more straightforward\.

## To be continued

In upcoming posts, you'll find more terrible tips for C\+\+ programmers\. Make sure you subscribe to [our blog newsletter](https://pvs-studio.com/en/subscribe/) to stay up to date with all our latest content\!

Follow Andrey Karpov on [LinkedIn](https://uz.linkedin.com/in/andrey-karpov-pvs-studio) and [X](https://x.com/Code_Analysis)\.