To get a trial key
fill out the form below
Team License (a basic version)
Enterprise License (an extended version)
* By clicking this button you agree to our Privacy Policy statement

Request our prices
New License
License Renewal
--Select currency--
USD
EUR
GBP
RUB
* By clicking this button you agree to our Privacy Policy statement

Free PVS-Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
>
Logical Expressions in C, C++, C#, and …

Logical Expressions in C, C++, C#, and Java. Mistakes Made by Professionals

Apr 11 2016

In programming, a logical expression is a language construct that is evaluated as true or false. Many books that teach programming "from scratch" discuss possible operations on logical expressions familiar to every beginner. In this article, I won't be talking about the AND operator having higher precedence than OR. Instead, I will talk about common mistakes that programmers make in simple conditional expressions consisting of no more than three operators, and show how you can check your code using truth tables. Mistakes described here are the ones made by the developers of such well-known projects as FreeBSD, Microsoft ChakraCore, Mozilla Thunderbird, LibreOffice, and many others.

0390_BooleanExpressionPro/image1.png

Introduction

I develop a static analyzer for C/C++/C# code, known as PVS-Studio. My job involves dealing with both open-source and proprietary code of various projects, and, as the result of this activity, I write a lot of articles regarding the analysis of open-source projects, where I talk about errors and defects found in these projects. With all that great amount of code that has been through our analyzer, we started to notice certain patterns of programming mistakes. For example, my colleague Andrey Karpov once wrote an article about the last-line effect after he had gathered a large collection of examples of mistakes made in the last lines or blocks of similar looking code fragments.

In the beginning of this year, I used the analyzer to scan some projects by large IT companies, which, following the modern trend, make their projects' sources publicly available under free licenses. I started to notice that almost every project has errors in conditional expressions that deal with incorrect use of conditional operators. Expressions themselves are quite simple and consist of just three operators:

  • != || !=
  • == || !=
  • == && ==
  • == && !=

In total, you can write 6 conditional expressions using these operators, but 4 of them are incorrect: two are always true or false; in two others, the result of the whole expression does not depend on the result of one of its subexpressions.

To prove that a conditional expression is incorrect, I will construct a truth table for every example. I will also give an example from real code for each case. We will talk about the ternary operator ?: as well, whose precedence is almost the lowest, although, few programmers know about it.

Since incorrect conditional expressions are found mostly in code that checks return values of various functions, comparing them with error codes, I will be using variable err in synthetic examples below, while code1 and code2 will be used as constants, which are not equal. The value "other codes" will stand for any other constants that are not equal to code1 and code2.

Incorrect use of the || operator

Expression != || !=

The following is a synthetic example where the conditional expression will always evaluate to true:

if ( err != code1 || err != code2)
{
  ....
}

This is the truth table for this code:

0390_BooleanExpressionPro/image2.png

And here is a real example of this error from LibreOffice project.

V547 Expression is always true. Probably the '&&' operator should be used here. sbxmod.cxx 1777

enum SbxDataType {
  SbxEMPTY    =  0,
  SbxNULL     =  1,
  ....
};

void SbModule::GetCodeCompleteDataFromParse(
  CodeCompleteDataCache& aCache)
{
  ....
  if( (pSymDef->GetType() != SbxEMPTY) ||          // <=
      (pSymDef->GetType() != SbxNULL) )            // <=
    aCache.InsertGlobalVar( pSymDef->GetName(),
      pParser->aGblStrings.Find(pSymDef->GetTypeId()) );
  ....
}

Expression == || !=

A synthetic example where the result of the whole expression does not depend on the result of its subexpression err == code1:

if ( err == code1 || err != code2)
{
  ....
}

Truth table:

0390_BooleanExpressionPro/image3.png

A real example from FreeBSD project:

V590 Consider inspecting the 'error == 0 || error != - 1' expression. The expression is excessive or contains a misprint. nd6.c 2119

int
nd6_output_ifp(....)
{
  ....
  /* Use the SEND socket */
  error = send_sendso_input_hook(m, ifp, SND_OUT,
      ip6len);
  /* -1 == no app on SEND socket */
  if (error == 0 || error != -1)           // <=
      return (error);
  ....
}

It's not much different from our synthetic example, is it?

Incorrect use of the && operator

Expression == && ==

A synthetic example, where the result of the conditional expression will always be false:

if ( err == code1 && err == code2)
{
  ....
}

Truth table:

0390_BooleanExpressionPro/image4.png

A real example from SeriousEngine project.

V547 Expression is always false. Probably the '||' operator should be used here. entity.cpp 3537

enum RenderType {
  ....
  RT_BRUSH       = 4,
  RT_FIELDBRUSH  = 8,
  ....
};

void
CEntity::DumpSync_t(CTStream &strm, INDEX iExtensiveSyncCheck)
{
  ....
  if( en_pciCollisionInfo == NULL) {
    strm.FPrintF_t("Collision info NULL\n");
  } else if (en_RenderType==RT_BRUSH &&       // <=
             en_RenderType==RT_FIELDBRUSH) {  // <=
    strm.FPrintF_t("Collision info: Brush entity\n");
  } else {
  ....
  }
  ....
}

Expression == && !=

A synthetic example where the result of the whole conditional expression does not depend on the result of its subexpression err != code2:

if ( err == code1 && err != code2)
{
  ....
}

Truth table:

0390_BooleanExpressionPro/image5.png

A real example from ChakraCore project, a JavaScript-engine for Microsoft Edge.

V590 Consider inspecting the 'sub[i] != '-' && sub[i] == '/'' expression. The expression is excessive or contains a misprint. rl.cpp 1388

const char *
stristr
(
  const char * str,
  const char * sub
)
{
  ....
  for (i = 0; i < len; i++)
  {
    if (tolower(str[i]) != tolower(sub[i]))
    {
      if ((str[i] != '/' && str[i] != '-') ||
            (sub[i] != '-' && sub[i] == '/')) {              / <=
           // if the mismatch is not between '/' and '-'
           break;
      }
    }
  }
  ....
}

Incorrect use of the ?: operator

V502 Perhaps the '?:' operator works in a different way than it was expected. The '?:' operator has a lower priority than the '|' operator. ata-serverworks.c 166

static int
ata_serverworks_chipinit(device_t dev)
{
  ....
  pci_write_config(dev, 0x5a,
           (pci_read_config(dev, 0x5a, 1) & ~0x40) |
           (ctlr->chip->cfg1 == SWKS_100) ? 0x03 : 0x02, 1);
  }
  ....
}

Before we finish with this article, I'd like to say a few words about the ternary operator ?:. Its precedence is almost the lowest of all operators. Only the assignment operator, the throw operator, and the comma operator have lower precedence. The error from the code sample above was found in the kernel of FreeBSD project. The authors used the ternary operator for selecting the required checkbox and for the sake of short, neat code. However, bitwise OR has higher precedence, so the conditional expression is evaluated in the wrong order. I decided to include this error in the article because it is very common for the projects I have scanned.

Conclusion

The patterns of errors in conditional expressions, described in this article, can be very dangerous if you are not careful enough writing the code. Despite the small number of operators, an incorrect conditional expression, as a whole, may be misinterpreted by the compiler. Such code may look quite sensible and pass code review. To secure yourself from these errors, use truth tables to check your expressions when in doubt, and also make sure you regularly scan your code with static analyzers.

Popular related articles
The way static analyzers fight against false positives, and why they do it

Date: Mar 20 2017

Author: Andrey Karpov

In my previous article I wrote that I don't like the approach of evaluating the efficiency of static analyzers with the help of synthetic tests. In that article, I give the example of a code fragment…
The Evil within the Comparison Functions

Date: May 19 2017

Author: Andrey Karpov

Perhaps, readers remember my article titled "Last line effect". It describes a pattern I've once noticed: in most cases programmers make an error in the last line of similar text blocks. Now I want t…
Appreciate Static Code Analysis!

Date: Oct 16 2017

Author: Andrey Karpov

I am really astonished by the capabilities of static code analysis even though I am one of the developers of PVS-Studio analyzer myself. The tool surprised me the other day as it turned out to be sma…
The Ultimate Question of Programming, Refactoring, and Everything

Date: Apr 14 2016

Author: Andrey Karpov

Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The au…
Static analysis as part of the development process in Unreal Engine

Date: Jun 27 2017

Author: Andrey Karpov

Unreal Engine continues to develop as new code is added and previously written code is changed. What is the inevitable consequence of ongoing development in a project? The emergence of new bugs in th…
How PVS-Studio Proved to Be More Attentive Than Three and a Half Programmers

Date: Oct 22 2018

Author: Andrey Karpov

Just like other static analyzers, PVS-Studio often produces false positives. What you are about to read is a short story where I'll tell you how PVS-Studio proved, just one more time, to be more atte…
Characteristics of PVS-Studio Analyzer by the Example of EFL Core Libraries, 10-15% of False Positives

Date: Jul 31 2017

Author: Andrey Karpov

After I wrote quite a big article about the analysis of the Tizen OS code, I received a large number of questions concerning the percentage of false positives and the density of errors (how many erro…
PVS-Studio for Java

Date: Jan 17 2019

Author: Andrey Karpov

In the seventh version of the PVS-Studio static analyzer, we added support of the Java language. It's time for a brief story of how we've started making support of the Java language, how far we've co…
Technologies used in the PVS-Studio code analyzer for finding bugs and potential vulnerabilities

Date: Nov 21 2018

Author: Andrey Karpov

A brief description of technologies used in the PVS-Studio tool, which let us effectively detect a large number of error patterns and potential vulnerabilities. The article describes the implementati…
The Last Line Effect

Date: May 31 2014

Author: Andrey Karpov

I have studied many errors caused by the use of the Copy-Paste method, and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have ne…

Comments (0)

Next comments
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →
Accept