SlideShare a Scribd company logo
1 of 6
Download to read offline
Logical Expressions in C/C++. Mistakes
Made by Professionals
Author: Svyatoslav Razmyslov
Date: 11.04.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.
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:
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:
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:
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 NULLn");
} else if (en_RenderType==RT_BRUSH && // <=
en_RenderType==RT_FIELDBRUSH) { // <=
strm.FPrintF_t("Collision info: Brush entityn");
} 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:
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 AND 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.

More Related Content

What's hot

Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016PVS-Studio
 
We Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityWe Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityPVS-Studio
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgePVS-Studio
 
How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.PVS-Studio
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxPVS-Studio
 
Beginner C++ easy slide and simple definition with questions
Beginner C++ easy slide and simple definition with questions Beginner C++ easy slide and simple definition with questions
Beginner C++ easy slide and simple definition with questions khawajasharif
 
De so 1
De so 1De so 1
De so 1kiennt
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cMd Nazmul Hossain Mir
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in cMemo Yekem
 
What static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannotWhat static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannotAndrey Karpov
 
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestChecking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestPVS-Studio
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckAndrey Karpov
 
Sony C#/.NET component set analysis
Sony C#/.NET component set analysisSony C#/.NET component set analysis
Sony C#/.NET component set analysisPVS-Studio
 
Checking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timeChecking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timePVS-Studio
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectPVS-Studio
 

What's hot (20)

Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016
 
We Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityWe Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High Quality
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 
How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBox
 
Beginner C++ easy slide and simple definition with questions
Beginner C++ easy slide and simple definition with questions Beginner C++ easy slide and simple definition with questions
Beginner C++ easy slide and simple definition with questions
 
De so 1
De so 1De so 1
De so 1
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-c
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
What static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannotWhat static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannot
 
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestChecking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
 
Exception handling
Exception handlingException handling
Exception handling
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd Check
 
Learn Java Part 2
Learn Java Part 2Learn Java Part 2
Learn Java Part 2
 
Sony C#/.NET component set analysis
Sony C#/.NET component set analysisSony C#/.NET component set analysis
Sony C#/.NET component set analysis
 
Checking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timeChecking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second time
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Presentation1
Presentation1Presentation1
Presentation1
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ project
 

Viewers also liked

A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source Code
A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source CodeA Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source Code
A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source CodePVS-Studio
 
Разработка крупного Standalone проекта на юнити: улучшаем производительность
Разработка крупного Standalone проекта на юнити: улучшаем производительностьРазработка крупного Standalone проекта на юнити: улучшаем производительность
Разработка крупного Standalone проекта на юнити: улучшаем производительностьВадим Воробьев
 
У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...
У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...
У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...Ivan Novikov
 
"C# vs JS" by Maxim Goncharuk
"C# vs JS" by Maxim Goncharuk"C# vs JS" by Maxim Goncharuk
"C# vs JS" by Maxim GoncharukBinary Studio
 
что пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studio
что пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studioчто пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studio
что пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studiocorehard_by
 
упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)
упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)
упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)corehard_by
 
ракописни букви с н
ракописни букви с нракописни букви с н
ракописни букви с нbrane71
 

Viewers also liked (11)

A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source Code
A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source CodeA Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source Code
A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source Code
 
Разработка крупного Standalone проекта на юнити: улучшаем производительность
Разработка крупного Standalone проекта на юнити: улучшаем производительностьРазработка крупного Standalone проекта на юнити: улучшаем производительность
Разработка крупного Standalone проекта на юнити: улучшаем производительность
 
У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...
У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...
У.М.Н.И.К-2015: Информационная система моделирования динамики пластических де...
 
"C# vs JS" by Maxim Goncharuk
"C# vs JS" by Maxim Goncharuk"C# vs JS" by Maxim Goncharuk
"C# vs JS" by Maxim Goncharuk
 
+1 вступ
+1 вступ+1 вступ
+1 вступ
 
сила духа
сила духасила духа
сила духа
 
что пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studio
что пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studioчто пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studio
что пришлось тестировать и о чем узнать при подготовке Linux версии pvs-studio
 
правописание приставок
правописание приставокправописание приставок
правописание приставок
 
упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)
упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)
упрощаем переход от Json к c++ структурам и обратно (николай гродзицкий)
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
ракописни букви с н
ракописни букви с нракописни букви с н
ракописни букви с н
 

Similar to Logical Expressions Mistakes by Professionals

Analysis of Godot Engine's Source Code
Analysis of Godot Engine's Source CodeAnalysis of Godot Engine's Source Code
Analysis of Godot Engine's Source CodePVS-Studio
 
What comments hide
What comments hideWhat comments hide
What comments hidePVS-Studio
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Andrey Karpov
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical softwarePVS-Studio
 
Checking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerChecking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerPVS-Studio
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingAndrey Karpov
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingPVS-Studio
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
 
The compiler is to blame for everything
The compiler is to blame for everythingThe compiler is to blame for everything
The compiler is to blame for everythingPVS-Studio
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggyPVS-Studio
 
Python and Ruby implementations compared by the error density
Python and Ruby implementations compared by the error densityPython and Ruby implementations compared by the error density
Python and Ruby implementations compared by the error densityPVS-Studio
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
 
Analyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectAnalyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectPVS-Studio
 
Re-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large reportRe-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large reportPVS-Studio
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
 
4. programing 101
4. programing 1014. programing 101
4. programing 101IEEE MIU SB
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckAndrey Karpov
 

Similar to Logical Expressions Mistakes by Professionals (20)

Analysis of Godot Engine's Source Code
Analysis of Godot Engine's Source CodeAnalysis of Godot Engine's Source Code
Analysis of Godot Engine's Source Code
 
What comments hide
What comments hideWhat comments hide
What comments hide
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical software
 
Checking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerChecking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzer
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
The compiler is to blame for everything
The compiler is to blame for everythingThe compiler is to blame for everything
The compiler is to blame for everything
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
Python and Ruby implementations compared by the error density
Python and Ruby implementations compared by the error densityPython and Ruby implementations compared by the error density
Python and Ruby implementations compared by the error density
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Analyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectAnalyzing the Dolphin-emu project
Analyzing the Dolphin-emu project
 
Re-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large reportRe-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large report
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
 
4. programing 101
4. programing 1014. programing 101
4. programing 101
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
 

Recently uploaded

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 

Recently uploaded (20)

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 

Logical Expressions Mistakes by Professionals

  • 1. Logical Expressions in C/C++. Mistakes Made by Professionals Author: Svyatoslav Razmyslov Date: 11.04.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. 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:  != || !=  == || !=
  • 2.  == && ==  == && != 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: 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()) ); .... }
  • 3. 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: 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:
  • 4. 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 NULLn"); } else if (en_RenderType==RT_BRUSH && // <= en_RenderType==RT_FIELDBRUSH) { // <= strm.FPrintF_t("Collision info: Brush entityn"); } 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: A real example from ChakraCore project, a JavaScript-engine for Microsoft Edge.
  • 5. 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 AND 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
  • 6. 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.