How to Make Fewer Errors at the Stage of Code Writing. Part N2

Unicorn and C++ operator ?:

Introduction

You may read the previous post here. This time we’ll take error samples from various famous projects to stress their prevalence. The errors I’m going to demonstrate here were found with the help of the PVS-Studio analyzer during a relatively large term. I have informed developers of almost all of the projects about the errors, so I hope they will fix the defects in new code revisions. I’m writing this in introduction because I always receive letters after publishing articles with a request “please inform the project’s developers about the errors you’ve found”.

1. Do Not Use the Ternary Operation ‘?:’ in Compound Expressions

A ternary conditional operation is written in C/C++ code with the ‘?:’ operator. This is an operation that returns its second or third operand depending on the value of the logical expression defined by the first operand. For example:

int minValue = A < B ? A : B;

A ternary operation has a very low priority (see the table). Programmers often forget about it and that is why the ternary operation is quite dangerous.

Figure 1 - C/C++ operations arranged in priority descending order

Figure 1 – C/C++ operations arranged in priority descending order

Note that the ‘?:’ operation has a lower priority than addition, multiplication, bitwise OR operator and so on. Consider this code:

int Z = X + (A == B) ? 1 : 2;

It works differently than it might seem at first sight. Most likely, the programmer intended to add the X value to number 1 or 2 depending on the (A == B) condition. But actually it is the “X + (A == B)” expression which is the condition. In fact, it is this code written in the project:

int Z = (X + (A == B)) ? 1 : 2;

While the programmer wanted this to be:

int Z = X + (A == B ? 1 : 2);

What occurs to you first is that you just should know the priorities of operations. Well, programmers do know them but too insidious is this ternary operation! Not only novices make mistakes with it but experienced programmers as well. You may easily find them even in the most quality code. Here are a couple of examples.

Picture 0

Picture 8

I even came across a discussion on the Internet where some man was too dogmatic saying that using additional parentheses is a bad form and that if somebody is not sure about the way an expression will be calculated, he must study instead of writing programs. Unfortunately, I’ve failed to find this discussion but I do not agree with such opinions. Of course, you must know priorities but if you use heterogeneous operations in an expression, you’d better use parentheses to secure yourself from errors. This will not only protect you from potential errors but make code readable for other developers.

Not only novice programmers but also skillful ones make mistakes caused by confusion of priorities. An expression does not necessarily need to be quite complicated and long; you may make a mistake in relatively simple expressions. Let’s consider some examples.

Picture 10

V564 The ‘&’ operator is applied to bool type value. You’ve probably forgotten to include parentheses or intended to use the ‘&&’ operator. game g_client.c 1534

#define SVF_CASTAI 0x00000010
char *ClientConnect(...) {
  ...
  if ( !ent->r.svFlags & SVF_CASTAI ) {
  ...
}

Picture 11

V564 The ‘&’ operator is applied to bool type value. You’ve probably forgotten to include parentheses or intended to use the ‘&&’ operator. dosbox sdlmain.cpp 519

static SDL_Surface * GFX_SetupSurfaceScaled(Bit32u sdl_flags,
                                            Bit32u bpp) {
  ...
  if (!sdl.blit.surface || (!sdl.blit.surface->flags&SDL_HWSURFACE)) {
  ...
}

And one more sample from Chromium:

V564 The ‘&’ operator is applied to bool type value. You’ve probably forgotten to include parentheses or intended to use the ‘&&’ operator. base platform_file_win.cc 216

#define FILE_ATTRIBUTE_DIRECTORY 0x00000010
bool GetPlatformFileInfo(PlatformFile file, PlatformFileInfo* info) {
  ...
  info->is_directory =
    file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0;
  ...
}

The expressions are simple. The developers are attaboys. Still there are errors. So, using parentheses in slippery fragments will not be superfluous.

I think the following is the best way: When operations are simple and usual, you don’t need additional parentheses. For example:

if (A == B && X != Y)
if (A - B < Foo() * 2)

But if you use rarer operators (~, ^, &, |, <<, >>, ?:), you’d better add explicit parentheses. They will both make code clearer and secure you from a potential error. For example:

If ( ! (A & B))
x = A | B | (z < 1 ? 2 : 3);

Exploiting parentheses when using rare operations will also help you with the “?:” operator discussed above. How we should handle “?:” is a matter of taste. Personally I like the method of simplification.

Summary

Write simple and clear code. Splitting long and complex expressions into several strings you get longer code. But this code is much clearer to read and comprehend. It is less probable that you will make a mistake in such code. Do not be afraid to create an additional variable – the compiler will optimize the code well.

Do not be greedy about using parentheses in expressions where rare operators are used or where bit and logical operations are mixed.

A programmer who will read your code with parentheses in the future will only be grateful to you for it.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read