Está en la página 1de 3013

BD

BugDetective (License Required)

BD-MISC
Miscellaneous
RULES
Always close transactions [BD-MISC-TRANS-1]

Always close transactions [BD-MISC-TRANS-1]


DESCRIPTION
This rule detects situations where a transaction associated with a certain
variable
('transaction object') is not closed.
SINCE
v7.0
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
This rule must be parameterized before it is used.
The parameterization dialog consists of two tables: 'Functions that start
a transaction'
and 'Functions that terminate a transaction'.
PARAMETERIZATION COMMON TO BOTH TRANSACTION STARTERS AND TERMINATORS
'Enabled' column:
Should be used to include/exclude an already-defined starter/terminator
from being taken
into account during the analysis.
'Fully qualified type name or namespace' column:
Allows for specification of the entity the starter/terminator is declared
within.
If this field is left empty, only the global function with the name
specified
in the 'Function name' column will be considered a transaction
starter/terminator.
If this field is filled with '*', the function declared in any type
or namespace-- or a global function declared outside of any type or
namespace-- will be
considered a transaction starter/terminator.
'Function name' column:
The name of the transaction starting/terminating function should be
specified here.

'+ definitions in subclasses' column:


Indicates whether function definitions in subclasses should be considered
starters/terminators as well. This applies to both instance and noninstance functions
and makes sense only if the declaring type is specified.

SETTING UP TRANSACTION STARTERS


The 'Functions that start a transaction' table can be filled with the
descriptors of functions
that start a transaction. These can be represented by functions that are
able to do any of the following:
a) Return a transaction object.
b) Open a transaction on the object that the function is called upon. For
example, after the call
transaction->open(); "transaction" is an open transaction that has to
be properly closed.
c) Turn one of its actual parameters into a transaction object.
For any starting function, the fields in the columns labeled 'Returns a
transaction object',
'"this" object is a transaction one' and 'Numbers of the parameters for
the transaction object (1-based)'
should be used to depict the situation (a, b or c) that takes place. The
value of the latter
column is expected to be an ordinal number (1-based) of the affected
parameter.
For example, this should be set to "2" if the function designates its
second parameter
as a transaction object. Use '*' to specify that all parameters are
transaction object.
NOTE ABOUT CONSTRUCTORS
Any transaction starting function with a name (the value of the
appropriate field in the
'Function name' column) that is exactly the same as the unqualified name
of its declaring type
(the last segment of the value of the field in 'Fully qualified type name
or namespace' column)
is considered a constructor. The '"this" object is a transaction one'
check box must be ticked
for constructors that represent a starting function.
Changing values in the fields '+ definitions in subclasses', 'Returns a

transaction object'
and 'Numbers of the parameters for the transaction object (1-based)' has
no effect on the analysis
for constructors.
SETTING UP TRANSACTION TERMINATORS:
The second pane can be filled with functions that terminate a transaction
by being
called on the object that is designated as a transaction object, or by
being passed a transaction
object as one of their parameters.
As with transaction starters, the fields in the columns labeled '"this"
object is a transaction one'
and 'Numbers of the parameters for the transaction object' should be
filled appropriately for transaction
terminators.
A step-by-step example of how to correctly perform parameterization is
provided in
the 'EXAMPLE' section of this help page.
SPECIFYING THE APPROACH TO REPORTING OF VIOLATIONS AT THE MOMENT OF
APPLICATION TERMINATION
The "Do not report violations at application termination"
parameter allows you to manage reporting of violations at the moment of
application
termination. The default setting is "off" because it's generally
recommended
to close the transaction manually.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A

EXAMPLE
Example#1(C-style parameterization):
Consider the following parameterization of the rule:
- The function that starts a transaction is defined with the name 'start'
and the corresponding 'Returns a transaction object' check box is
ticked.
- The function that terminates a transaction is defined with the name
'terminate'
and '1' is set as the value of the corresponding cell of the
'Numbers of the parameters for the transaction object' table column.
Being parameterized in this way, the rule detects a violation on the
following
sample code:
#include<stdio.h>
void* start() { }
void terminate(void* a) { }
static void notClosedTransaction()
{
void* transaction;
transaction = start();
}

Example#2(C++-style parameterization):
Consider the following sample code:
namespace mySpace {
class MyTransaction
{
public:
void start();
void terminate();
static void terminateTransaction(MyTransaction* p)
{
};
};
}

static void transactionUse()


{
mySpace::MyTransaction* t = new mySpace::MyTransaction();
t->start();
} // 't' is not terminated

In order to detect an unclosed transaction in the code above, the rule


should be parameterized as follows:
- Function that starts a transaction:
'Fully qualified type name or namespace' field value:
"mySpace::MyTransaction";
'Function name' field value: "start";
'"this" object is a transaction one' check box status: checked.
- Terminating function:
'Fully qualified type name or namespace' field value:
"mySpace::MyTransaction";
'Function name' field value: "terminate";
'"this" object is a transaction one' check box status: checked.
- Another terminating function:
'Fully qualified type name or namespace' field value:
"mySpace::MyTransaction";
'Function name' field value: "terminateTransaction";
'Numbers of the parameters for the transaction object (1-based)'
field value: 1.

REPAIR
For Example#1:
By adding a call to terminating function, we repair the code so that
it does not trigger a violation:
#include<stdio.h>
void* start() { }
void terminate(void* a) { }
static void notClosedTransaction()
{
void* transaction;
transaction = start();

terminate(transaction);
}

For Example#2:
By adding a call to the terminating function, we repair the code so that
it does not trigger a violation:
namespace mySpace {
class MyTransaction
{
public:
void start();
void terminate();
static void terminateTransaction(MyTransaction* p)
{
};
};
}
static void transactionUse()
{
mySpace::MyTransaction* t = new mySpace::MyTransaction();
t->start();
t->terminate(); // mySpace::MyTransaction::terminateTransaction(t); may
be used as well
}

REFERENCES
N/A

BD-PB
Possible Bugs
RULES
Avoid accessing arrays out of bounds [BD-PB-ARRAY-1]
Avoid conditions that always evaluate to the same value [BD-PB-CC-2]
Avoid dereferencing before checking for null [BD-PB-DEREF-2]
Avoid use before initialization [BD-PB-NOTINIT-1]
Avoid null pointer dereferencing [BD-PB-NP-1]
Avoid buffer overflow due to defining incorrect format limits [BD-PBOVERFFMT-1]
Avoid overflow due to reading a not zero terminated string [BD-PBOVERFNZT-1]
Avoid overflow when reading from a buffer [BD-PB-OVERFRD-1]
Avoid overflow when writing to a buffer [BD-PB-OVERFWR-1]
Avoid switch with unreachable branches [BD-PB-SWITCH-2]
Avoid division by zero [BD-PB-ZERO-1]

Avoid accessing arrays out of bounds [BD-PB-ARRAY-1]


DESCRIPTION
This rule detects array access operations which may result in out of
bounds access.
Specifically, a violation is reported if an execution path with obvious
out-of-bounds
access is possible. This occurs when an index value is negative, equal to,
or greater than the array size.
SINCE
v7.0.22
NOTES
N/A
SECURITY RELEVANCE
The potential to access arrays beyond their boundaries is a severe
security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
The "Aggressively report violations for indexes changed inside loops" mode
prompts BugDetective to
report a violation any time that it suspects a problem with accessing an
array using a variable
changed inside a loop as the index -- even if there is high probability
that such a case may be a
false positive. Using this mode will result in more bugs being reported,
but it can also increase
the number of false alarms.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A

DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
void fillArray(int array[], int size)
{
int i;
for (i = 0; i <= size; i++) { // iterate from 0 to 100
array[i] = 0; // VIOLATION (accessing array out of bounds: "array[i]"
where (i == 100))
}
}
void example()
{
int array[100];
fillArray(array, 100);
// ...
}
REPAIR
The following is fixed example for which no violations will be reported:
void fillArray(int array[], int size)
{
int i;
for (i = 0; i < size; i++) { // iterate from 0 to 99
array[i] = 0; // NO VIOLATION
}
}
void example()
{
int array[100];
fillArray(array, 100);
// ...
}
REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)

CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131


http://cwe.mitre.org/top25/#CWE-131

Avoid conditions that always evaluate to the same value [BD-PB-CC-2]


DESCRIPTION
This rule identifies conditions that always evaluate to the same value.
Such conditions
often appear in the course of refactoring and during code evolution -especially when
code is edited by multiple developers. Often, the existence of such
conditions indicates
logical errors in the code. Additionally, such conditions may indicate
overly loose assumptions,
which results in less efficient code and fragments of dead code (as shown
below in the example section).
How it works:
This rule inspects conditions present in the code and determines whether
they are redundant.
To achieve this, it examines all the code paths that lead to the
condition. If it finds that
the condition evaluates to the same value on all these paths, it reports a
violation.
SINCE
v7.2
NOTES
When both the condition and the code that makes this condition constant
are within
the same function, this almost always indicates a problem with the logic.
When
one of these is in a different function, a more careful review is needed
before
proceeding to fix the reported violation. The review is important because
even though
an obvious solution may be to remove the check, it is possible that the
check
protects against future changes.
SECURITY RELEVANCE
N/A
PARAMETERS
BugDetective can be configured to assume that to some functions can be

passed arbitrary values.


It is controlled by "global functions", "functions with internal linkage",
"member functions with following visibility:"
checkboxes and the group of radio buttons representing member functions
visibilities.
"global functions" and "functions with internal linkage" parameters define
the rule assumptions about global functions
and functions with internal linkage (static global functions or functions
from anonymous namespaces)
"member functions with following visibility:" parameter determines the
assumptions for member functions.
If the checkbox is unchecked, we will assume, that there is no such member
function to which an arbitrary variable can be
passed. If the checkbox is checked, it indicates that there is a subset of
functions to which arbitrary values can
be passed.
In this case, the options are the following:
* public
* public, protected
* member functions of any visibility (least aggressive, most accurate)
Choosing the default options will result in fewer
violations being reported, and a very low number of false
positives. Choosing "public, protected" and "functions with internal
linkage"
also usually produces good results. You may want to try different options
and
pick the one best suited to your code base.
You can determine whether violations should be reported for the use of
named
compile-time constants leading to constant conditional expressions. Such
cases are not
reported by default. This can be changed by enabling the "Report about
issues related
to use of named compile-time constants" option. Often, compile-time
constants are used to
configure application behavior (for example, to work either in debug mode
or
release mode). If that is the case in the application being analyzed,
conditionals
that use compile-time constants are expected and do not represent dead
code. Otherwise,

enabling the option may be useful to detect more occurrences of dead code.
Consider
the following code as an example:
const bool DEBUG = false;
/* ... */
if (DEBUG) {
/* perform some debug output */
}
Although this condition is constant at any given moment, it is
intentionally left since
the developer may want to change the value of the named compile-time
constant. Therefore,
this normally should not be reported as a violation.
However, a more efficient way of writing the same code is via preprocessor
directives:
#define DEBUG 1
/* ... */
#ifdef DEBUG
/* perform some debug output */
#endif
The rule can help in enforcing this more efficient style.
BENEFITS
Helps you keep code in good shape and weed out logical inconsistencies as
soon as they
are introduced.
EXAMPLE
Here is an example which triggers a violation due to the presence of a
dead code fragment:
#include "stdio.h"
void processHexValue(char*);

static void checkRange(char* cur)


{
if ((*cur < '0') || (*cur > '9')) {
printf("Error: only digits are permitted");
return;
}
// obviously dead code
if ((*cur >= 'a') && (*cur <= 'f')) {
processHexValue(cur);
}
}

REPAIR
To repair the code, remove the redundant check:
#include "stdio.h"
static void checkRange(char* cur)
{
if ((*cur < '0') || (*cur > '9')) {
printf("Error: only decimal digits are permitted");
return;
}
}

Avoid dereferencing before checking for null [BD-PB-DEREF-2]


DESCRIPTION
This rule detects cases where a reference checked for being null gets
dereferenced
on any path leading to this check.
In some cases, the checks for null might have become redundant in the
course of
refactoring. In other cases, it is possible that the dereference was
introduced
into code that already had the null check, but the developer mistakenly
added
the dereference before the null check. This usually results in a null
reference
exception. In any case, such a condition usually points to an
inconsistency in
the code, which should be reviewed for correctness.
How it works:
The rule inspects null checks present in the code and determines whether
they
are redundant. To do this, it examines all the code paths that lead to
the null check (for example, of variable "foo"). If it finds a
dereferencing
of the variable "foo" along all these paths, then it reports a violation.

SINCE
v7.2
NOTES
When both the dereference and the null check are within the same function,
this almost always indicates a problem with the logic. When one of these
is in a different function, a more careful review is needed before
proceeding to fix the reported violation. Even though
an obvious solution may be to remove the null check, it is possible that
the null check is a protection against future changes.
SECURITY RELEVANCE
N/A
PARAMETERS

BugDetective can be configured to assume that to some functions can be


passed arbitrary values.
It is controlled by "global functions", "functions with internal linkage",
"member functions with following visibility:"
checkboxes and the group of radio buttons representing member functions
visibilities.
"global functions" and "functions with internal linkage" parameters define
the rule assumptions about global functions
and functions with internal linkage (static global functions or functions
from anonymous namespaces)
"member functions with following visibility:" parameter determines the
assumptions for member functions.
If the checkbox is unchecked, we will assume that there is no such member
function to which an arbitrary variable can be
passed. If the checkbox is checked, it indicates that there is a subset of
functions to which arbitrary values can
be passed.
In this case, the options are the following:
* public
* public, protected
* member functions of any visibility (least aggressive, most accurate)
Choosing the default options will result in fewer
violations being reported, and a very low number of false
positives. Choosing "public, protected" and "functions with internal
linkage"
also usually produces good results. You may want to try different options
and
pick the one best suited to your code base.
BENEFITS
Helps you detect code that is fraught with the danger of null
dereferencing and find
fragments of dead code.
EXAMPLE
Here is an example which triggers a violation due to a problem with logic:
#include "stdio.h"
static void checkSequence(char cur[])
{

if (cur[0] == '-') {
printf("Error: only positive values are permitted");
return;
}
// misplaced null check
if (cur == 0) {
printf("Error: null argument provided");
return;
}
}
REPAIR
The misplaced null check should precede the array processing code:
#include "stdio.h"
static void checkSequence(char cur[])
{
if (cur == 0) {
printf("Error: null argument provided");
return;
}
if (cur[0] == '-') {
printf("Error: only positive values are permitted");
return;
}
}

Avoid use before initialization [BD-PB-NOTINIT-1]


DESCRIPTION
This rule detects cases when a variable is used prior to its explicit
initialization.
SINCE
v7.0
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
The 'Report violation when a non-initialized variable is passed to a
function without source
code as a const parameter' check box allows you to specify if the rule
should trigger when a
non-initialized variable is passed as a const parameter to a function
whose source code
is not available. In case a parameter is a struct or a class, a violation
is only reported
if the object is completely uninitialized. For example, if one of a
struct's fields is initialized
and passed to a third-party function as a const parameter, a violation
won't be reported because the
struct is partially initialized.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A

EXAMPLE
The rule can detect a variety of erroneous situations.
Here are just a few examples where the rule triggers.
1.
static void useParameter(int* pi)
{
int j = *pi;
}
static void usageOfUninializedVariablePassedToMethodByAddress()
{
int i;
useParameter(&i); // VIOLATION
}
2.
static void pointerDerefInLhsOfDefinition()
{
int* notInitializedPointer;
*notInitializedPointer = 0; // VIOLATION
}
REPAIR
Always initialize a variable before its use.
REFERENCES
N/A

Avoid null pointer dereferencing [BD-PB-NP-1]


DESCRIPTION
This rule detects cases where there is a danger of a null pointer being
dereferenced.
SINCE
v7.0
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
"Reporting of violations where variable is known to be null due to a null
check"
This block of parameters allows you to specify which violations should be
reported:
* Only those where BD can prove that a certain variable gets assigned a
null value;
* Violations in the above category, plus violations where there is no
null value assignment but a check
for a null value that stipulates null pointer dereferencing at the
point of use.
For the second option to work, the "Enabled" check box in this block
should be checked.
Here is an example with the second type of violations:
int b = (ptr == 0); /* null check that stipulates null dereferencing at
violation point */
/* ... */
if (b) {
/* ... */
int i = *ptr; /* violation reported if the check box is ticked */
}
"Except for the following cases:"
This group of parameters helps to reduce the number of unwanted violations
caused by a null check. For cases when some function
or macro performs a null check, the parameterization determines whether it

should be assumed that the corresponding variable


can be null in the callers of the function.
"When the null check is performed inside macro invocation"
This parameter controls how null checks in macros are handled by the rule.
Consider the following example:
#define FOO(P) if (P == 0) { /* ... */ }
void bar(int* p)
{
FOO(p);
*p = 10; /* Violation or not? */
}
If this checkbox is unchecked, then in the example above the violation
will be reported.
Other parameters in this group are related to the visibility of the
functions. Consider the following example:
int* foo(int* p)
{
if (p == 0) {
/* ... */
}
return p;
}
void bar(int* p)
{
foo(p);
*p = 10; /* Violation or not? */
}
Should a violation be reported inside bar()? This depends on foo()'s
visibility and the parameterization of the rule.
"When the null check is performed inside a called function with internal
linkage"
If this checkbox is unchecked, then in the example above the violation
will be reported if the foo() function is
a function with internal linkage (a function, which is visible only in the
compilation unit where it is defined).

Static global functions and functions from anonymous namespaces are


functions with internal linkage.
"When the null check is performed inside a called global function"
If this checkbox is unchecked, then in the example above the violation
will be reported if the foo() function is
a global non-member function.
"When the null check is performed inside a called member function of the
following visibility:"
This parameter defines rule behavior for cases where foo() is a member
function.
If the checkbox is unchecked, then in the example above the violation will
always be reported
if foo() is a member function. If the checkbox is checked, the following
radio group of parameters is available:
* "public"
* "public, protected"
* "any visibility"
The following table presents all the possible cases of the
parameterization state when the checkbox is
checked. Each row represents one of the options of the radio group:

Parameterization:
"public"
"public, protected"
"any visibility"

member function visibility (foo)


| public | protected | private |
|
|
+
|
+
|
|
|
|
+
|
|
|
|
|

For table entries marked with '+', the violation will be reported in the
example above.
"Functions that do not accept NULL as their parameters" table:
Allows you to enumerate functions whose parameters are not allowed to
accept null.
Parameterization details:
'Enabled' column:
Should be used to include/exclude an already-defined function from being
taken
into account during the analysis.
'Fully qualified type name or namespace' column:

Allows for the specification of the entity the function is declared


within.
If this field is left empty, only the global function with the name
specified
in 'Function name' column will be considered.
If this field is filled with '*', a function declared in any type
or namespace, or a global function declared outside of any type or
namespace, will be
considered.
'Function name' column:
The name of the function should be specified here.
'+ definitions in subclasses' column:
This is to indicate whether the function definitions in subclasses should
be considered
as well. This applies to both instance and non-instance functions and
makes sense only
if the declaring type is specified.
'Numbers of the parameters not allowing NULL (1-based, comma-separated)'
column:
Allows you to specify the list of ordinal numbers of the function
parameters that are not
allowed to accept null. These numbers should be 1-based and separated by
comma (Example: 1,3),
or '*' can be used to specify that all parameters are not allowed to
accept null.

"External functions that may return NULL" table:


This rule can also be parameterized to consider functions that can
potentially
return null. To achieve better results, the rule provides a predefined set
of such
null returners from standard libraries. Those predefined functions are
used by
default. They can not be edited or removed from the list, but can be
enabled/disabled by using
the check box in the 'Enabled' column.
Additionally, you can extend the set of null returners to include
additional functions that
you assume being capable to return null.

Parameterization details:
Details are similar to those for "Functions that do not accept NULL as
their parameters" table described above,
except there is no 'Numbers of the parameters not allowing NULL (1-based,
comma-separated)' column.
A step-by-step example of how to create your own null returner is provided
in the 'EXAMPLE'
section of this help page.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Example#1 - Some code excerpts for which the rule reports a violation:
static void nullPointerDereference()
{
int* pointerToNull = 0;
int variable = *pointerToNull; /* VIOLATION */
}
static void zeroTracking()
{
int pointerValue = 0;
int* pointerToNull = pointerValue;
int variable = *pointerToNull; /* VIOLATION */
}
static void multiPointer()
{
int* zero = 0;
int** ppi = &zero;
int* pi = *ppi;

int k = *pi; /* VIOLATION */


}

Example#2 - custom null returner creation:


Consider the following code assuming createInstance() being potential null
returner:
namespace mySpace {
class MyClass
{
public:
int getNumber();
static MyClass* createInstance();
};
}
static void usingFactory()
{
mySpace::MyClass* instance = mySpace::MyClass::createInstance();
int num = instance->getNumber(); // VIOLATION
}
In order to detect possible null pointer dereferencing in the code above,
the rule should be parameterized as follows:
- Add custom null returner:
'Fully qualified type name or namespace' field value:
"mySpace::MyClass";
'Function name' field value: "createInstance";
Use '+ definitions in subclasses' if createInstance() defined in
subclasses
of mySpace::MyClass may return null as well.

REPAIR
Avoid null pointer dereferencing.
REFERENCES
N/A

Avoid buffer overflow due to defining incorrect format limits [BD-PB-OVERFFMT-1]


DESCRIPTION
The rule detects cases of possible overflow due to an incorrectly-defined
format specifier for
the scanf family of functions. A violation is reported when the format
string implies
that the read operation can overflow the given buffer.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
The possibility of buffer overflow is a severe security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE* file;
void read(char* buff, int buffSize)

{
char formatString[100];
char sizeString[100];
strcpy(formatString, "%");
strcat(formatString, itoa(buffSize, sizeString, 10));
strcat(formatString, "s");
fscanf(file, formatString, buff);
}
void test()
{
char buffer[100];
read(buffer, 101);
}
REPAIR
If the value passed as the "buffSize" parameter of the read() function is
changed
to correspond to the real buffer size, no violation is reported:
void test()
{
char buffer[100];
read(buffer, 100);
}
REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-120
http://cwe.mitre.org/top25/#CWE-120

Avoid overflow due to reading a not zero terminated string [BD-PB-OVERFNZT-1]


DESCRIPTION
The rule detects cases of possible overflow due to running a string
function on a string that
was not properly zero terminated.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
The possibility of buffer overflow is a severe security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *header, *header2; /* initialized somewhere */
void process(int flag, char* body)
{
char buffer[100], buffer2[100];

strcpy(buffer, header);
if (flag) {
buffer2[0] = 'a';
buffer2[1] = 'b';
strcat(buffer, buffer2);
} else {
strncpy(body, "abc", 2);
strcat(buffer, body);
}
/* ... */
}
REPAIR
The following code will not trigger a violation since the zero terminator
symbol is properly added:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *header, *header2; /* initialized somewhere */
void process(int flag, char* body)
{
char buffer[100], buffer2[100];
strcpy(buffer, header);
if (flag) {
buffer2[0] = 'a';
buffer2[1] = 'b';
buffer2[2] = 0;
strcat(buffer, buffer2);
} else {
strcpy(body, "ab");
strcat(buffer, body);
}
/* ... */
}
REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-120
http://cwe.mitre.org/top25/#CWE-120

Avoid overflow when reading from a buffer [BD-PB-OVERFRD-1]


DESCRIPTION
The rule detects when code reads from a buffer and the read operation can
go beyond
the buffer boundary.
Specifically, a violation is reported if an execution path with obvious
buffer
overflow is possible. This occurs when a value of the 'size' parameter is
negative
or greater than the actual buffer size.
This rule checks for buffer overflows for uses of the following functions:
void *memcpy(void *dest, const void *src, size_t n);
void bcopy(const void *src, void *dest, size_t n);
char *strncpy(char *dest, const char *src, size_t n);
char *strncat(char *dest, const char *src, size_t n);
size_t strlcpy(char *dst, const char *src, size_t size);
size_t strlcat(char *dst, const char *src, size_t size);
SINCE
v7.1
NOTES
N/A
SECURITY RELEVANCE
The possibility of buffer overflow is a severe security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
The "Aggressive mode" encourages BugDetective to report a violation any
time that BugDetective
suspect a problem - even if there is high probability that such a case may
be a false positive.
Applying this configuration will result in more bugs being reported, but
it can also
increase the number of false alarms.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is

described in the "Data Flow Static Analysis with BugDetective ->


Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <string.h>
void example()
{
int src[100];
int dest[200];
// ...
memcpy(dest, src, sizeof(dest)); // VIOLATION
}

REPAIR
The following code will not trigger a violation:
#include <string.h>
void example()
{
int src[100];
int dest[200];
// ...
memcpy(dest, src, sizeof(src)); // NO VIOLATION
}

REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131

http://cwe.mitre.org/top25/#CWE-131

Avoid overflow when writing to a buffer [BD-PB-OVERFWR-1]


DESCRIPTION
The rule detects when code writes to a buffer and the write operation can
go beyond
the buffer boundary.
Specifically, a violation is reported if an execution path with obvious
buffer overflow
is possible. This occurs when a value of the 'size' parameter is negative
or greater than
the actual buffer size.
This rule checks for buffer overflows for uses of the following functions:
void *memset(void *s, int c, size_t n);
void *memcpy(void *dest, const void *src, size_t n);
void bcopy(const void *src, void *dest, size_t n);
char *fgets(char *s, int size, FILE *stream);
int snprintf(char *str, size_t size, const char *format, ...);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);
int swprintf(wchar_t *wcs, size_t maxlen, const wchar_t *format, ...);
int vswprintf(wchar_t *wcs, size_t maxlen, const wchar_t *format, va_list
args);
char *strncpy(char *dest, const char *src, size_t n);
char *strncat(char *dest, const char *src, size_t n);
size_t strlcpy(char *dst, const char *src, size_t size);
size_t strlcat(char *dst, const char *src, size_t size);
int syslog(int type, char *bufp, int len);
SINCE
v7.1
NOTES
N/A
SECURITY RELEVANCE
The possibility of buffer overflow is a severe security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
The "Aggressive mode" encourages BugDetective to report a violation any
time that BugDetective

suspect a problem - even if there is high probability that such a case may
be a false positive.
Applying this configuration will result in more bugs being reported, but
it can also
increase the number of false alarms.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
Example 1:
#include <string.h>
void example()
{
int src[200];
int dest[100];
// ...
memcpy(dest, src, sizeof(src)); // VIOLATION
}

REPAIR
The following code will not trigger a violation:
#include <string.h>
void example()
{
int src[200];
int dest[100];

// ...
memcpy(dest, src, sizeof(dest)); // NO VIOLATION
}

REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-120
http://cwe.mitre.org/top25/#CWE-120

Avoid switch with unreachable branches [BD-PB-SWITCH-2]


DESCRIPTION
This rule identifies unreachable switch branches-- one kind of dead code.
Dead code often appears in the course of refactorings and during code
evolution-especially when code is edited by multiple developers. Often, the
existence of unreachable
switch branches indicates logical errors in the code (as shown below in
the example section).
How it works:
the rule inspects switch statements present in the code and determines
whether they
have unreachable branches or not. For this, it examines all the code paths
that lead
to the switch statement. If it finds that on all these paths some of the
case branches
of the switch statement are unreachable, it reports a violation.
SINCE
v7.2
NOTES
In order to make good use of this rule, the check box "Do not report
violations
when cause cannot be shown" in BugDetective configuration pane must be
unchecked.
SECURITY RELEVANCE
N/A
PARAMETERS
BugDetective can be configured to assume that to some functions can be
passed arbitrary values.
It is controlled by "global functions", "functions with internal linkage",
"member functions with following visibility:"
checkboxes and the group of radio buttons representing member functions
visibilities.
"global functions" and "functions with internal linkage" parameters define
the rule assumptions about global functions
and functions with internal linkage (static global functions or functions

from anonymous namespaces)


"member functions with following visibility:" parameter determines the
assumptions for member functions.
If the checkbox is unchecked, we will assume, that there is no such member
function, to which arbitrary variable can be
passed. If the checkbox is checked, then there is a subset of functions
for which we consider that arbitrary values can
be passed there.
In this cases the options are the following:
* public
* public, protected
* member functions of any visibility (least aggressive, most accurate)
Choosing the default options will result in fewer
violations being reported, and a very low number of false
positives. Choosing "public, protected" and "functions with internal
linkage"
also usually produces good results. You may want to try different options
and
pick the one best suited to your code base.
It is also possible to specify whether or not to report a violation for an
unreachable
default branch which is not declared explicitly. This is controlled by the
check box
labeled "Report about unreachable default branch even if it's not
explicitly defined".
BENEFITS
Helps you keep code in good shape and weed out logical inconsistencies as
soon as they
appear.
EXAMPLE
Here is an example which triggers a violation ("Do not report
violations when cause cannot be shown" check box in BugDetective
configuration pane must be unchecked):
#include "stdio.h"
enum Figures {
SPHERE,
CIRCLE,
CUBE,

SQUARE,
HIMESPHERE
};
static void guessFigure(int round, int volumetric)
{
int figure;
if (round && volumetric) {
figure = SPHERE;
} else if (round && !volumetric) {
figure = CIRCLE;
} else if (!round && volumetric) {
figure = CUBE;
} else {
figure = SQUARE;
}
switch (figure) {
case SQUARE:
printf("This is a sphere");
break;
case HIMESPHERE:
printf("This is a hemispere");
break;
case CIRCLE:
printf("This is a circle");
break;
case CUBE:
printf("This is a cube");
break;
default:
printf("This is a square");
break;
}
}
REPAIR
To repair the code, remove the unreachable branch:
#include "stdio.h"
enum Figures {
SPHERE,
CIRCLE,

CUBE,
SQUARE,
HIMESPHERE
};
static void guessFigure(int round, int volumetric)
{
int figure;
if (round && volumetric) {
figure = SPHERE;
} else if (round && !volumetric) {
figure = CIRCLE;
} else if (!round && volumetric) {
figure = CUBE;
} else {
figure = SQUARE;
}
switch (figure) {
case SQUARE:
printf("This is a sphere");
break;
case CIRCLE:
printf("This is a circle");
break;
case CUBE:
printf("This is a cube");
break;
default:
printf("This is a square");
break;
}
}

Avoid division by zero [BD-PB-ZERO-1]


DESCRIPTION
This rule detects execution paths where 0 can be used as a denominator
in a division operation. This is an exception situation and should be
avoided.
SINCE
v7.0
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
The "Aggressive mode" encourages BugDetective to report a violation any
time that BugDetective
suspect a problem - even if there is high probability that such a case may
be a false positive.
Applying this configuration will result in more bugs being reported, but
it can also
increase the number of false alarms.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
This rule can detect a variety of situations where division
by zero may occur. Below are a few examples this will trigger a
violation.
static int zeroMethod()

{
return 0;
}
static void assignmentRemainderOfMethodResult()
{
int a = 5;
a %= zeroMethod(); // VIOLATION
}
static void assignRemainderOfVar()
{
int a = 5;
int b = 0;
a %= b; // VIOLATION
}
REPAIR
Rewrite the code so that division by zero cannot occur.
REFERENCES
N/A

BD-RES
Resources
RULES
Ensure deallocation functions guarantee resource freeing [BD-RES-BADFREEF1]
Do not use resources that have been freed [BD-RES-FREE-1]
Do not free resources using invalid pointers [BD-RES-INVFREE-1]
Ensure resources are freed [BD-RES-LEAKS-1]

Ensure deallocation functions guarantee resource freeing [BD-RES-BADFREEF-1]


DESCRIPTION
This rule detects functions that were meant to free resources, but do not
guarantee that the resource
is freed under all circumstances. The rule checks functions whose name
matches the pattern
you designate (it is set to "*free*" by default). A violation is reported
when a function deallocates
resources passed as parameters on some paths, but on some paths they are
not deallocated. This
can imply that calling the closing function under certain conditions may
result in a resource leak.
The set of resources and related deallocation functions are defined in the
"Test Configurations -> Static -> Options -> BugDetective -> Resources"
tab.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
The parameterization dialog allows to define the name pattern for
functions that are to be checked.
The default value is "*free*".
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation. (Please note that in
order for BugDetective
to find violations in the example, "Memory (standard C)" must be turned on
in the resource
table on "Test Configurations -> Static -> Options -> BugDetective ->

Resources" tab):
#include <stdlib.h>
void bad_free(void* p, int condition)
{
if (condition) {
free(p);
}
}
REPAIR
The following code will not trigger a violation:
#include <stdlib.h>
void good_free(void* p)
{
if (p != 0) {
free(p);
}
}
REFERENCES
N/A

Do not use resources that have been freed [BD-RES-FREE-1]


DESCRIPTION
This rule detects uses of resources that have been freed. In particular, a
violation is reported
when a pointer or reference to a freed resource is:
*
*
*
*
*

returned from a function,


passed as a parameter to a function,
used in an arithmetic operation,
dereferenced, or
assigned to a variable/field/array element.

The rule can identify violations for any type of resource. The set of
resources
is defined in the "Test Configurations -> Static -> Options ->
BugDetective -> Resources" tab.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
The "Report violation when pointer to freed resource is compared to null"
check box
unsupresses/suppresses violations where a pointer to a freed resource is
compared to a null
pointer. This may be allowed by the code writing policy and application
design.
By default, such violations are not reported.
The "Report violation when pointer to freed resource is compared to other
pointers" check box
unsuppresses/suppresses violations where a pointer to a freed resource is
compared to other
pointers. This may be allowed by the code writing policy and application
design.
By default, such violations are not reported.

"Report unvalidated violations" is a parameter common to a large set of


BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
Prevents strange, often non-deterministic errors related to the use of
freed resources.
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
int compute(int* buffer, const int size)
{
int result = 0;
// perform computations
delete[] buffer;
return result;
}
void process(const int size)
{
int* buffer = new int[size];
int result = compute(buffer, size);
delete[] buffer;
// do something
}
REPAIR
Removing delete in the compute() function repairs the example above.
(Please note that in order for BugDetective
to find violations in the example, "Memory (standard C++)" must be turned
on in the resource
table on "Test Configurations -> Static -> Options -> BugDetective ->
Resources" tab):
int compute(int* buffer, const int size)
{
int result = 0;

// perform computations
return result;
}
void process(const int size)
{
int* buffer = new int[size];
int result = compute(buffer, size);
delete[] buffer;
// do something
}
REFERENCES
N/A

Do not free resources using invalid pointers [BD-RES-INVFREE-1]


DESCRIPTION
This rule detects attempts to free resources using an invalid pointer.
A violation is reported when the pointer used to free a resource meets any
of
the following conditions:
* It is a pointer to a string constant.
* It is acquired as a result of a cast of an integer constant to pointer
type (wild pointer).
* It is acquired via an address operation applied to a parameter, local,
global
or static variable (attempt to free resource in non-heap memory).
* It does not point to the beginning of the allocated chunk.
The rule can identify violations at calls to deallocation functions for
any type of resource.
The set of resources and corresponding deallocation functions are defined
at
"Test Configurations -> Static -> Options -> BugDetective -> Resources"
tab.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A

DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation. (Please note that in
order for BugDetective
to find violations in the example, "Memory (standard C)" must be turned on
in the resource
table on "Test Configurations -> Static -> Options -> BugDetective ->
Resources" tab):
#include <stdlib.h>
#define SIZE 100
int buffer[SIZE];
void process(int size)
{
int* data = buffer;
if (size > SIZE) {
data = (int*)malloc(size*sizeof(int));
}
/* do something with the data buffer */
free(data);
}
REPAIR
The following code will not trigger a violation:
#include <stdlib.h>
#define SIZE 100
int buffer[SIZE];
void process(int size)
{
int* data = buffer;
if (size > SIZE) {
data = (int*)malloc(size*sizeof(int));
}
/* do something with the data buffer */
if (size > SIZE) {

free(data);
}
}
REFERENCES
N/A

Ensure resources are freed [BD-RES-LEAKS-1]


DESCRIPTION
This rule helps to ensure that allocated resources are deallocated on all
paths.
Violations of the rule identify execution paths in an application where
resources
are leaked.
The rule can identify leaks of any type of resource. The set of resources
whose
leaks are to be detected is defined at
"Test Configurations -> Static -> Options -> BugDetective -> Resources"
tab.
SINCE
v7.0
SECURITY RELEVANCE
Failure to close resources may lead to starvation, which could have
security implications.
PARAMETERS
The "Assume third-party functions could store resource references"
parameter allows you to determine how strict the rule is when a reference
to a resource may be stored by a third-party function. For example, if
there is a
third-party function SpecialCollection.add() and a resource is passed as a
parameter
to this function, it will be stored in a collection and may later be
closed by iterating
over the collection. Since BugDetective does not know the exact behavior
of arbitrary
third-party functions, it behaves in either of the following ways:
* With this parameter enabled (the default), BugDetective assumes that
any
third-party function may store reference to a resource if the resource
is
passed into the function. This prevents it from reporting false
positives if
the resource is later closed using the stored reference.
However, this may also lead to false negatives (real leaks are not

reported
as violations).
* With this parameter disabled, BugDetective takes a more aggressive
approach: It
assumes that third-party functions do not affect resources in any way.
This
approach may lead to some false positives, but it will not overlook
some
of the real leaks that the default approach may miss.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
Having a strict policy with respect to closing resources helps to make an
application more
robust by preventing resource starvation.
DRAWBACKS
N/A
EXAMPLE
Here is an example that triggers violations. (Please note that in order
for BugDetective
to find violations in the example, "Files (stdio.h)" must be turned on in
the resource
table on "Test Configurations -> Static -> Options -> BugDetective ->
Resources" tab):
#include <stdio.h>
static void fileAllocation()
{
FILE* p = fopen("file.name", "r");
}
static void fileReallocation()
{
FILE* p = fdopen(0, "r");

p = freopen("file.name", "r", p);


}
REPAIR
The following code will not trigger violations:
#include <stdio.h>
static void fileAllocation()
{
FILE* p = fopen("file.name", "r");
fclose(p);
}
static void fileReallocation()
{
FILE* p = fdopen(0, "r");
p = freopen("file.name", "r", p);
fclose(p);
}

BD-SECURITY
Security
RULES
Avoid tainted data in array indexes [BD-SECURITY-ARRAY-1]
Protect against integer overflow/underflow from tainted data [BD-SECURITYINTOVERF-1]
Avoid buffer read overflow from tainted data [BD-SECURITY-OVERFRD-1]
Avoid buffer write overflow from tainted data [BD-SECURITY-OVERFWR-1]
Protect against command injection [BD-SECURITY-TDCMD-1]
Protect against file name injection [BD-SECURITY-TDFNAMES-1]
Protect against SQL injection [BD-SECURITY-TDSQL-1]

Avoid tainted data in array indexes [BD-SECURITY-ARRAY-1]


DESCRIPTION
This rule detects array access operations that may result in out of bounds
access.
Specifically, a violation is reported if an index value used to access an
array element
comes from a tainting function (e.g., user input) that can return
malicious data,
but is not checked for being non-negative (applicable to signed types) and
less than the size of the corresponding array.
Data from the following data sources are considered tainted:
* Parameters of the main() function
* Network
Additional sources of tainted data can be defined by parameterizing the
rule.
For details, see the PARAMETERS section.
SINCE
v7.1
NOTES
N/A
SECURITY RELEVANCE
The potential to access arrays beyond their boundaries is a severe
security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted
(in addition to those previously listed in the DESCRIPTION section):
*
*
*
*
*
*

Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables

The
Any
*
*
*

rule can be parameterized with a list of validating functions.


validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.

Validation functions allow this data to be safely passed


to dangerous functions.
Below is the description of columns which allow to define different
aspects of
functions in "Validating functions" table:
* The 'Enabled' column can be used to temporarily disable some of the
defined functions
for BugDetective analysis.
* The 'Fully qualified type name or namespace (wildcard)' column must be
filled with
the fully qualified name of the type or namespace where the function is
declared.
Use '*' if you want to describe function declared in any type or
namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given
function:
* The '"this" object is validated' column is used to specify that the
function cleans object on which
it is called.
* The 'returns validated data' column is used to specify that the function
cleans its return value.

* The 'Numbers of the parameters that are validated (1-based)' column is


used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by comma
or use '*' to specify that all parameters are affected.
The "Aggressively report violations for indexes changed inside loops" mode
prompts BugDetective to
report a violation any time that it suspects a problem with accessing an
array using a variable
changed inside a loop as the index -- even if there is high probability
that such a case may be a
false positive. Using this mode will result in more bugs being reported,
but it can also increase
the number of false alarms.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <stdio.h>
int example(int array[100])
{
int i;
scanf("%d", &i);
return array[i]; // VIOLATION ("i" is an unknown value possibly < 0 or >=
100)
}

REPAIR
The following code will not trigger a violation:
#include <stdio.h>
int example(int array[100])
{
int i;
scanf("%d", &i);
if (i < 0 || i >= 100) {
return -1; // wrong input
}
return array[i]; // NO VIOLATION
}

REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131
http://cwe.mitre.org/top25/#CWE-131

Protect against integer overflow/underflow from tainted data [BD-SECURITY-INTOVERF-1]


DESCRIPTION
This rule detects cases where unvalidated input (tainted data) is used in
an arithmetic
operation that can result in numeric overflow (when the mathematical
result of an operation
is greater than the highest value that can be represented by the
operation's result type)
or underflow (when the mathematical result of an operation is lower than
the lowest value
that can be represented by the operation's result type) and is later used
in a dangerous
operation.
Since overflow may be expected in many cases, the rule tries to avoid
false positives by reporting
a violation only if a value that can be overflowed is later used in one of
the following
dangerous cases:
- As a memory buffer size in a memory allocation operation (overflow may
cause allocation
of a huge memory chunk and possibly denial of service)
- In a loop condition (overflow may lead to an infinite loop and thus to
denial of service)
- In pointer arithmetic (may cause accessing memory at illegal address and
thus undefined
behavior, including application crashes)

Data from the following data sources are considered tainted:


* Parameters of the main() function
* Network
Additional sources of tainted data can be defined by parameterizing the
rule.
For details, see the PARAMETERS section.
SINCE

v7.3
NOTES
N/A
SECURITY RELEVANCE
Integer overflow is a serious security threat because it can be used to
cause application crashes
and denial of service.
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted
(in addition to those previously listed in the DESCRIPTION section):
*
*
*
*
*
*
The
Any
*
*
*

Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables
rule can be parameterized with a list of validating functions.
validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.

Validation functions allow this data to be safely passed


to dangerous functions.
Below is the description of columns which allow to define different
aspects of
functions in "Validating functions" table:
* The 'Enabled' column can be used to temporarily disable some of the
defined functions
for BugDetective analysis.
* The 'Fully qualified type name or namespace (wildcard)' column must be
filled with
the fully qualified name of the type or namespace where the function is
declared.
Use '*' if you want to describe a function declared in any type or

namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given
function:
* The '"this" object is validated' column is used to specify that the
function cleans the object on which
it is called.
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger violations:

#include
#include
#include
#include
#include

<stdio.h>
<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>

#define BUFFER_SIZE 64
char buffer[BUFFER_SIZE];
#define MAX_LEN 1000000L
char decode(char c)
{
/* Decode character */
return c;
}
char* readMessage(int socket, char* header, int len)
{
int i, header_len;
long msg_len, total_len;
char* msg;
recv(socket, buffer, BUFFER_SIZE, MSG_NOSIGNAL);
msg_len = atol(buffer);
header_len = strlen(header);
total_len = header_len;
total_len += msg_len;
msg = (char*)malloc(total_len); /* VIOLATION, USAGE OF OVERFLOWED VALUE */
if (!msg) {
return 0;
}
strcpy(msg, header);
recv(socket, msg + msg_len, msg_len, MSG_NOSIGNAL);
for (i = header_len; i < total_len; i++) { /* VIOLATION, USAGE OF
OVERFLOWED VALUE */
msg[i] = decode(msg[i]);
}
return msg;
}

REPAIR
The following code will not trigger a violation:
#include
#include
#include
#include
#include

<stdio.h>
<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>

#define BUFFER_SIZE 64
char buffer[BUFFER_SIZE];
#define MAX_LEN 1000000L
char decode(char c)
{
/* Decode character */
return c;
}
char* readMessage(int socket, char* header, int len)
{
int i, header_len;
long msg_len, total_len;
char* msg;
recv(socket, buffer, BUFFER_SIZE, MSG_NOSIGNAL);
msg_len = atol(buffer);
header_len = strlen(header);
total_len = header_len;
total_len += msg_len;
if ((total_len < 0) || (total_len > MAX_LEN)) { /* check that total_len is
within an acceptable range */
return 0;
}
msg = (char*)malloc(total_len); /* NO VIOLATION */
if (!msg) {
return 0;
}
strcpy(msg, header);

recv(socket, msg + msg_len, msg_len, MSG_NOSIGNAL);


for (i = header_len; i < total_len; i++) { /* NO VIOLATION */
msg[i] = decode(msg[i]);
}
return msg;
}
REFERENCES
http://www.owasp.org/index.php/Integer_overflow
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-190
http://cwe.mitre.org/top25/#CWE-190

Avoid buffer read overflow from tainted data [BD-SECURITY-OVERFRD-1]


DESCRIPTION
The rule detects when code reads from a buffer and the read operation can
go beyond
the buffer boundary.
Specifically, a violation is reported if a 'size' value passed to a
function reading from a buffer
comes from a tainting function (e.g., user input) that can return
malicious data, but is not
checked for being non-negative (applicable to signed types) and not
greater than the size
of the corresponding buffer.
Data from the following data sources are considered tainted:
* Parameters of the main() function
* Network
Additional sources of tainted data can be defined by parameterizing the
rule.
For details, see the PARAMETERS section.
SINCE
v7.1
NOTES
N/A
SECURITY RELEVANCE
The possibility of buffer overflow is a severe security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted
(in addition to those previously listed in the DESCRIPTION section):
*
*
*
*

Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)

* Console
* Environment variables
The
Any
*
*
*

rule can be parameterized with a list of validating functions.


validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.

Validation functions allow this data to be safely passed


to dangerous functions.
Below is the description of columns which allow you to define different
aspects of
functions in "Validating functions" table:
* The 'Enabled' column can be used to temporarily disable some of the
defined functions
for BugDetective analysis.
* The 'Fully qualified type name or namespace (wildcard)' column must be
filled with
the fully qualified name of the type or namespace where the function is
declared.
Use '*' if you want to describe a function declared in any type or
namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given
function:
* The '"this" object is validated' column is used to specify that the
function cleans the object on which
it is called.

* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])
{
int size;
scanf("%d", &size);
memcpy(dest, src, size); // VIOLATION ("size" is an arbitrary value
possibly < 0 or > 100)
}

REPAIR
The following code will not trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])

{
int size;
scanf("%d", &size);
if (size >= 0 && size <= 100) {
memcpy(dest, src, size); // NO VIOLATION
}
}

REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131
http://cwe.mitre.org/top25/#CWE-131

Avoid buffer write overflow from tainted data [BD-SECURITY-OVERFWR-1]


DESCRIPTION
The rule detects when code writes to a buffer and the write operation can
go beyond
the buffer boundary.
Specifically, a violation is reported if a 'size' value passed to a
function writing to a buffer
comes from a tainting function (e.g., user input) that can return
malicious data,
but is not checked for being non-negative (applicable to signed types) and
not greater
than the size of the corresponding buffer.
Data from the following data sources are considered tainted:
* Parameters of the main() function
* Network
Additional sources of tainted data can be defined by parameterizing the
rule.
For details, see the PARAMETERS section.
SINCE
v7.1
NOTES
N/A
SECURITY RELEVANCE
Possible buffer overflow is a severe security threat.
If an application has a vulnerability of this kind, it can be exploited to
execute arbitrary code and gain full control over the application.
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted
(in addition to those previously listed in the DESCRIPTION section):
*
*
*
*

Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)

* Console
* Environment variables
The
Any
*
*
*

rule can be parameterized with a list of validating functions.


validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.

Validation functions allow this data to be safely passed


to dangerous functions.
Below is the description of columns which allow to define different
aspects of
functions in "Validating functions" table:
* The 'Enabled' column can be used to temporarily disable some of the
defined functions
for BugDetective analysis.
* The 'Fully qualified type name or namespace (wildcard)' column must be
filled with
the fully qualified name of the type or namespace where the function is
declared.
Use '*' if you want to describe function declared in any type or
namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given
function:
* The '"this" object is validated' column is used to specify that the
function cleans the object on which
it is called.

* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])
{
int size;
scanf("%d", &size);
memcpy(dest, src, size); // VIOLATION ("size" is an arbitrary value
possibly < 0 or > 100)
}

REPAIR
The following code will not trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])

{
int size;
scanf("%d", &size);
if (size >= 0 && size <= 100) {
memcpy(dest, src, size); // NO VIOLATION
}
}

REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-120
http://cwe.mitre.org/top25/#CWE-120

Protect against command injection [BD-SECURITY-TDCMD-1]


DESCRIPTION
This rule detects cases when data coming directly from the end-user can
influence
the code which is executed (for example, to form the name of the file to
be executed).
The rule supports functions for process execution from the standard C
library as well
as from POSIX. For example, it considers widely used system() function and
the exec family
of functions dangerous.
Data from the following data sources are considered tainted:
* Parameters of the main() function
* Network
Additional sources of tainted data can be defined by parameterizing the
rule.
For details, see the PARAMETERS section.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
Enforces 'A2 - Injection Flaws', #2 from the OWASP Top 10 2007 list.
If some tainted data will appear in an executed file name without
verification,
it may allow the execution of custom malicious code which could damage the
system.
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted
(in addition to those previously listed in the DESCRIPTION section):
* Files

*
*
*
*
*
The
Any
*
*
*

Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables
rule can be parameterized with a list of validating functions.
validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.

Validation functions allow this data to be safely passed


to dangerous functions.
Below is the description of columns which allow to define different
aspects of
functions in "Validating functions" table:
* The 'Enabled' column can be used to temporarily disable some of the
defined functions
for BugDetective analysis.
* The 'Fully qualified type name or namespace (wildcard)' column must be
filled with
the fully qualified name of the type or namespace where the function is
declared.
Use '*' if you want to describe function declared in any type or
namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given
function:
* The '"this" object is validated' column is used to specify that the

function cleans the object on which


it is called.
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
Also, there is an option that determines whether numerical data should be
considered tainted.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Consider a network application that receives some user-defined parameters
from a socket and
starts some processing using these parameters. In such situations, placing
unverified user data into
an execution request can have some dangerous consequences. For example,
users might be able to
run custom code on the server with application privileges.
For instance, providing " & shutdown -s -f -d p" as a command_parameter
value in the request
will cause a server to shutdown if the command is executed in the
following way:
#include <stdio.h>

#include
#include
#include
#include

<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>

void commandInjection(int socket)


{
char params[200], command[250];
recv(socket, params, 200, 0); /* Receiving command parameters from a
socket */
strcpy(command, "process_data -params ");
strcat(command, params);
system(command); // Command injection
}
REPAIR
Validating tainted data prior to its usage in the dangerous function
removes
the risk of command injection:
#include
#include
#include
#include
#include

<stdio.h>
<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>

char* validate(char*); /* properly implement validation function */


void commandInjection(int socket)
{
char params[200], command[250];
recv(socket, params, 200, 0); /* Receiving command parameters from a
socket */
strcpy(command, "process_data -params ");
strcat(command, validate(params));
system(command); /* OK, protected from command injection provided that
validate() is implemented properly */
}
REFERENCES
OWASP Top 10 2007 (A2 - Injection Flaws):
http://www.owasp.org/index.php/Top_10_2007

Web Application Security Consortium:


http://www.webappsec.org/projects/threat/classes/os_commanding.shtml
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-78
http://cwe.mitre.org/top25/#CWE-78

Protect against file name injection [BD-SECURITY-TDFNAMES-1]


DESCRIPTION
This rule detects when possibly tainted data is used as a filename or path
in file
manipulating functions, which could cause a file name injection. The rule
supports file manipulation
functions from the standard C and C++ libraries as well as those defined
by POSIX.
Data from the following data sources are considered tainted:
* Parameters of the main() function
* Network
Additional sources of tainted data can be defined by parameterizing the
rule.
For details, see the PARAMETERS section.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
If unverified data appears in file names, then an attacker could
potentially gain
access to any file on the system, providing specially-prepared malicious
data.
Enforcing this rule will help to protect against the OWASP 2007 Top 10
application vulnerability "A3 - Malicious File Execution".
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted
(in addition to those previously listed in the DESCRIPTION section):
*
*
*
*

Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)

* Console
* Environment variables
The
Any
*
*
*

rule can be parameterized with a list of validating functions.


validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.

Validation functions allow this data to be safely passed


to dangerous functions.
Below is the description of columns which allow you to define different
aspects of
functions in "Validating functions" table:
* The 'Enabled' column can be used to temporarily disable some of the
defined functions
for BugDetective analysis.
* The 'Fully qualified type name or namespace (wildcard)' column must be
filled with
the fully qualified name of the type or namespace where the function is
declared.
Use '*' if you want to describe function declared in any type or
namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given
function:
* The '"this" object is validated' column is used to specify that the
function cleans the object on which
it is called.

* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
Also, there is an option that determines whether numerical data should be
considered tainted.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Consider an application that stores some user-specific data in files on a
server (for
instance, a library with user stories) using the story name given by the
user as the file name.
The following code may be used to create a specific file and add the
story contents:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
void saveStory(int socket)
{
char storyName[50];
char storyContent[200];
/* Receive story from socket */

recv(socket, storyName, 50, 0);


recv(socket, storyContent, 200, 0);
FILE* f = fopen(storyName, "w"); /* File name injection */
fprintf(f, "%s", storyContent);
fclose(f);
}
In this case, if an attacker provides "c:\\windows\\system.ini" as a story
name
and some specially prepared configuration file contents as story contents,
then after saving this "story", the system-critical .ini file can be
modified
and some dangerous contents can be saved there.
REPAIR
Validate data prior to its usage:
void saveStory(int socket)
{
/* ... */
recv(socket, storyName, 50, MSG_WAITALL);
storyName = validate(storyName);
recv(socket, storyContent, 200, MSG_WAITALL);
storyContent = validate(storyContent);
/* ... */
}
char* validate(char*)
{
// verify the input so that the file can only be stored in the current
directory only,
// not under a user defined path
}
REFERENCES
OWASP Top 10 2007 (A3 - Malicious File Execution):
http://www.owasp.org/index.php/Top_10_2007-A3
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-22
http://cwe.mitre.org/top25/#CWE-22

Protect against SQL injection [BD-SECURITY-TDSQL-1]


DESCRIPTION
This rule detects cases of probable SQL injection when possibly tainted
data reaches
functions that execute or prepare SQL queries, retrieve connections, etc.
When an application uses data provided by the user (or by some unverified
data source)
to construct SQL queries and does not verify/validate such data before its
use,
it is possible for an attacker to alter the SQL statements in a way that
the developer
did not intend. As a result, the attacker can take total control of the
database or even
execute commands on the system.
The rule supports the following database APIs: ODBC, ADO, OLE DB.
Data from the following data sources are considered tainted:
* Parameters of the main() function
* Network
Additional sources of tainted data can be defined by parameterizing the
rule.
For details, see the PARAMETERS section.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
Enforces 'A2 - Injection Flaws', #2 from the OWASP Top 10 2007 list.
If data can appear in an SQL query without being validated,
a malicious user could take control of the database.
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted

(in addition to those previously listed in the DESCRIPTION section):


*
*
*
*
*
*
The
Any
*
*
*

Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables
rule can be parameterized with a list of validating functions.
validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.

Validation functions allow this data to be safely passed


to dangerous functions.
Below is the description of columns which allow to define different
aspects of
functions in "Validating functions" table:
* The 'Enabled' column can be used to temporarily disable some of the
defined functions
for BugDetective analysis.
* The 'Fully qualified type name or namespace (wildcard)' column must be
filled with
the fully qualified name of the type or namespace where the function is
declared.
Use '*' if you want to describe function declared in any type or
namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given

function:
* The '"this" object is validated' column is used to specify that the
function cleans the object on which
it is called.
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
Also, there is an option that determines whether numerical data should be
considered tainted.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Consider an example where an application reads the user name and
password from a file and then, for authentication purposes, tries to find
that user
information in a database. The code supporting this might look as
follows:
#include <sql.h>
#include <stdio.h>
const int BUFFER_SIZE = 1000;
const char* requestBeginning = "SELECT user_id, user_class, rights FROM

users WHERE user_name = '";


const char* requestPassword = "' and password = '";
const char* requestEnding = "'";
extern char* extractUsername(const char*);
extern char* extractPassword(const char*);
extern SQLHSTMT statementHandle;
void handleRequest(FILE* file)
{
char parametersString[BUFFER_SIZE];
fread(parametersString, 1, BUFFER_SIZE, file);
SQLCHAR request[BUFFER_SIZE];
strcpy(request, requestBeginning);
strcat(request, extractUsername(parametersString));
strcat(request, requestPassword);
strcat(request, extractPassword(parametersString));
strcat(request, requestEnding);
SQLExecDirect(statementHandle, request, strlen(request));
}
If the user enters the following string as both the user name and the
password:
' or ''='
then the SQL statement will look like the following:
SELECT user_id, user_class, rights FROM users WHERE user_name = '' or
''='' and password = '' or ''=''
This will get all users' information, so the attacker will be
authenticated as the first
user in the users table -- even though he did not provide the necessary
authorization
information.
REPAIR
Using SQLPrepare() function and setting the data from the user via
SQLBindParameter() function
(instead of direct creation of textual query including the parameter
values) ensures protection
from SQL injection:

#include
#include
#include
#include

<sql.h>
<sqltypes.h>
<sqlext.h>
<stdio.h>

const int BUFFER_SIZE = 1000;


const char* requestString = "SELECT user_id, user_class, rights FROM users
WHERE user_name = '?' and password = '?'";
extern char* extractUsername(const char*);
extern char* extractPassword(const char*);
extern SQLHSTMT statementHandle;
SQLINTEGER nameLen = SQL_NTS, passLen = SQL_NTS;

void handleRequest(FILE* file)


{
char parametersString[BUFFER_SIZE];
fread(parametersString, 1, BUFFER_SIZE, file);
char* name = extractUsername(parametersString);
char* pass = extractPassword(parametersString);
SQLBindParameter(statementHandle, 1, SQL_PARAM_INPUT, SQL_C_CHAR,
SQL_CHAR, 20, 0, name, 0, &nameLen);
SQLBindParameter(statementHandle, 2, SQL_PARAM_INPUT, SQL_C_CHAR,
SQL_CHAR, 20, 0, pass, 0, &passLen);
SQLPrepare(statementHandle, requestString, SQL_NTS);
SQLExecute(statementHandle);
}
REFERENCES
OWASP Top 10 2007 (A2 - Injection Flaws):
http://www.owasp.org/index.php/Top_10_2007
Web Application Security Consortium:
http://www.webappsec.org/projects/threat/classes/sql_injection.shtml
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-89

http://cwe.mitre.org/top25/#CWE-89

BD-TRS
Threads & Synchronization
RULES
Avoid double locking [BD-TRS-DLOCK-1]
Do not abandon unreleased locks [BD-TRS-LOCK-1]
Do not use blocking functions while holding a lock [BD-TRS-TSHL-1]

Avoid double locking [BD-TRS-DLOCK-1]


DESCRIPTION
This rule detects cases where a lock is acquired twice without
intermediate releasing.
While this is legal for the so-called recursive mutexes, it is not allowed
for regular
locks and may cause deadlocks.
SINCE
v9.0
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
The rule can be customized to check for double lock acquisitions of
certain common APIs
(from the list of supported APIs), it also possible to specify
multithreading
functions from any third-party API by providing specification of relevant
functions.
To view the list of all the supported APIs, configure the APIs that the
rule will
check as well as to define functions from a third-party API to be checked
by the rule,
please visit the "Multithreading" sub-tab on the "BugDetective options"
tab for your test
configuration.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
Prevents application deadlocks.

DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <pthread.h>
pthread_mutex_t* mutex;
bool preconditionHolds();
void exclusivelyCompute()
{
pthread_mutex_lock(mutex);
if (preconditionHolds()) {
/* perform some computations */
exclusivelyCompute(); // VIOLATION: recursive call will cause
double locking
}
pthread_mutex_unlock(mutex);
}
void run()
{
mutex = new pthread_mutex_t;
pthread_mutex_init(mutex, (const pthread_mutexattr_t*)0);
exclusivelyCompute();
}
REPAIR
The example can be repaired by separating locking and computation in
different functions
(but ensuring that the function performing unlocked computation is only
called from functions
performing appropriate locking):
#include <pthread.h>
pthread_mutex_t* mutex;
bool preconditionHolds();
static void nonexclusivelyCompute()
{
if (preconditionHolds()) {

/* perform some computations */


nonexclusivelyCompute(); // NO VIOLATION: locking is done only once
}
}
void exclusivelyCompute()
{
pthread_mutex_lock(mutex);
nonexclusivelyCompute();
pthread_mutex_unlock(mutex);
}
void run()
{
mutex = new pthread_mutex_t;
pthread_mutex_init(mutex, (const pthread_mutexattr_t*)0);
exclusivelyCompute();
}
REFERENCES
N/A

Do not abandon unreleased locks [BD-TRS-LOCK-1]


DESCRIPTION
This rule detects cases where a mutex is locked but not unlocked at an
appropriate place, which could cause an application deadlock.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
The rule can be customized to check for unlocked mutexes of certain common
APIs
(from the list of supported APIs). You can also specify multithreading
functions
from any third-party API by providing a specification of the relevant
functions.
You can view the list of all the supported APIs, configure the APIs that
the rule
will check, as well as define functions from a third-party API to be
checked by
the rule from the "BugDetective options> Multithreading" sub-tab for your
Test
Configuration.
The "Locked object may be unlocked from callers up to specified level"
parameter
allows you to manage the depth of analysis of the call graph. Lower
numbers are
recommended to enforce the best practice that locking and unlocking occur
at the
same nesting level. This practice is required by MISRA C/C++ & JSF
standards.
Higher numbers of the parameter value may be preferred for (rare) cases
where
locking and unlocking have to be performed on different levels as well as
in the
case where certain functions serve as wrappers to standard locking and

unlocking
functions. When such wrappers are involved, it is recommended to define
them as
separate multithreading APIs in the Test Configurations> Static>
BugDetective Options>
Multithreading tab. However, if this is not done but source code of the
wrappers
is included into the analysis scope and a relevant value of the "Locked
object may be
unlocked from callers up to specified level" parameter is used, then cases
where
custom wrapping APIs are used to lock a mutex but not unlock it will be
detected
automatically-- even without extending BugDetective's multithreading API
knowledge
base with the custom API. This is why the parameter of the value is set to
2 by
default; this ensures the detection of most bugs related to direct uses of
standard
locking functions as well as the use of custom wrappers around them-without
producing unnecessary false positives.
To demonstrate this, let's assume the following wrapper functions:
void mutex_lock()
{
pthread_mutex_lock(mutex);
// do something else
}
void mutex_unlock()
{
pthread_mutext_unlock(mutex);
// do something else
}
With the value of parameter set to 0, BugDetective will see the call to
pthread_mutex_lock inside the wrapper function "mutex_lock" and no
corresponding
call to pthread_mutex_unlock inside the function. Consequently, it will
report a
violation which is in fact a false positive because mutex_lock is not
meant to

call unlocking function by design and pthread_mutex_unlock is called from


the
other wrapper function named "mutex_unlock". Setting the depth to values
higher
than 0 prevents false positives for such wrapper functions while still
ensuring
that violations will be reported if the code doesn't call "mutex_unlock".
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
Prevents application deadlocks.
DRAWBACKS
N/A
EXAMPLE
Example 1. Here is an example that will trigger a violation:
#include <pthread.h>
pthread_mutex_t* mutex;
bool preconditionHolds();
void exclusivelyCompute()
{
pthread_mutex_lock(mutex);
if (preconditionHolds()) {
/* perform some computations */
pthread_mutex_unlock(mutex);
}
}
Example 2. To properly analyze the following example, the parameter
"Locked object may be unlocked from callers up to specified level" should
be set to "3" or more.
#include <pthread.h>

pthread_mutex_t mutex;
void
void
void
void
void
void

lockLevel1() {
unlockLevel1()
lockLevel2() {
unlockLevel2()
lockLevel3() {
unlockLevel3()

pthread_mutex_lock(&mutex); }
{ pthread_mutex_unlock(&mutex); }
lockLevel1(); }
{ unlockLevel1(); }
lockLevel2(); }
{ unlockLevel2(); }

bool preconditionHolds();
void exclusivelyCompute()
{
lockLevel3();
if (preconditionHolds()) {
/* perform some computations */
unlockLevel3();
}
}

REPAIR
Example 1. The example can be repaired by performing unlocking on all the
branches:
#include <pthread.h>
pthread_mutex_t* mutex;
bool preconditionHolds();
void exclusivelyCompute()
{
pthread_mutex_lock(mutex);
if (preconditionHolds()) {
/* perform some computations */
}
pthread_mutex_unlock(mutex);
}
Example 2.
#include <pthread.h>

pthread_mutex_t mutex;
void
void
void
void
void
void

lockLevel1() {
unlockLevel1()
lockLevel2() {
unlockLevel2()
lockLevel3() {
unlockLevel3()

pthread_mutex_lock(&mutex); }
{ pthread_mutex_unlock(&mutex); }
lockLevel1(); }
{ unlockLevel1(); }
lockLevel2(); }
{ unlockLevel2(); }

bool preconditionHolds();
void exclusivelyCompute()
{
lockLevel3();
if (preconditionHolds()) {
/* perform some computations */
}
unlockLevel3();
}
REFERENCES
N/A

Do not use blocking functions while holding a lock [BD-TRS-TSHL-1]


DESCRIPTION
This rule detects cases where functions that cease thread execution for a
certain time
(such as sleep()) are called from critical sections--thus unnecessarily
increasing
resource contention between threads.
SINCE
v7.2
NOTES
N/A
SECURITY RELEVANCE
N/A
PARAMETERS
The rule can be customized to check for unlocked mutexes of certain common
APIs
(from the list of supported APIs), it also possible to specify
multithreading
functions from any third-party API by providing specification of relevant
functions.
To view the list of all the supported APIs, configure the APIs that the
rule will
check as well as to define functions from a third-party API to be checked
by the rule,
please visit "Multithreading" sub-tab on the "BugDetective options" tab
for your test
configuration.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
Helps prevent unnecessary resource contention between threads as well as
thread starvation.

DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t* mutex;
static void testLock()
{
pthread_mutex_lock(mutex);
sleep(10);
/* do something */
pthread_mutex_unlock(mutex);
}
REPAIR
Removing the call to sleep() repairs the code:
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t* mutex;
static void testLock()
{
pthread_mutex_lock(mutex);
/* do something */
pthread_mutex_unlock(mutex);
}
REFERENCES
N/A

CDD
Code Duplication Detection
RULES
Avoid duplication of #include directives [CDD-001-4]
Avoid code duplication [CDD-002-2]
Avoid string literal duplication [CDD-003-2]
Avoid function duplication [CDD-004-2]

Avoid duplication of #include directives [CDD-001-4]


DESCRIPTION
Rule checks if there are duplicated #include directives.
Rule compares directives in one file at time (for example no violation
will be reported if the same file is included in header and source file).
Rule compares text used in #include directive so a violation will be
reported
only if the text is identical (for example no violation will be reported
if
different path was used to include a file).

SINCE
v9.2

BENEFITS
Rule improves readability and maintainability. Simplifies the code and
decreases preprocessing time.

EXAMPLE
// --- header1.h --#include "header2.h"
// --- file.cpp --#include "header1.h"
#include "header2.h" /* OK: not checked against includes in other files */
#include "header1.h" /* Violation: "header1.h" was included previously */
#define HEADER "header1.h"
#include HEADER
/* OK: we don't do macro replacement */
#include HEADER
/* Violation: HEADER was included previously */
#include <header1.h> /* OK: <header1.h> is different than "header1.h" */
#include "./header1.h" /* OK: "./header1.h" is different than "header1.h"
*/
#if 0
#include "header1.h" /* Violation: "header1.h" was included in outer
conditional inclusion scope */
#include "header3.h"

#else
#include "header3.h" /* OK - previous inclusion was inside other
conditional
inclusion scope*/
#endif
#include "header3.h" /* OK - previous inclusion was inside other
conditional
inclusion scope*/

REPAIR
Remove duplicated #include directives if they are not needed.

REFERENCES
Recommended by Parasoft

Avoid code duplication [CDD-002-2]


DESCRIPTION
This rule identifies duplicated code. The rule finds duplicated fragments
across all tested code,
whether or not the duplicated code appears in the same file.
Code duplication detection is focused on giving most useful results
so the performed analysis is not just simple text tokens compare.
Additional parameters which can be set for this rule can override compare
result
for different node types.
Start and end position of code duplication block is calculated using
several
internal rules, like:
- start point can be placed only on statement beginning
- end point can be placed only on statement end
- end point can't leave start point scope (duplicated code block for
example, can't start
in the middle of one function body and ends in different one)
For example:
@int foo(int a, int b)
{
@int r;%
@if (a < b) {
@r = b - a;%
} else {
@r = a - b;%
}
@return r;%
}
@ - marks possible start points for duplicated code part
% - marks possible end points for duplicated code part
A violation is reported for each occurrence.
See also: CDD-004
SINCE
v9.2
PARAMETERS

This rule can be parameterized to achieve best results.


* Minimum duplicate tokens size (default value is 80)
This parameter value defines minimum size of code fragment which may be
reported by this rule.
Variable names, string and numeric literals, keywords, operators are
count as one token.
For example:
if (param1 == 0) {
return a;
}

// 7 tokens
// 3 tokens
// 1 token

"Ignore ..." parameters allows some differences to be ignored


and reported as duplicated code:
* Ignore string and character literals (default is off)
Turn it on to ignore string literals differences
* Ignore number literals (default is off)
Turn it on to ignore number literals differences
* Ignore boolean literals (default is off)
Turn it on to ignore boolean literals differences
* Ignore identifiers (local/global variables, function names, ...)
(default is off)
Turn it on to ignore identifiers differences
BENEFITS
Rule improves readability and maintainability. Simplifies and reduce code
size.
Copying and pasting code will increase the cost of code maintenance
because
each time a modification is required, multiple instance of the same code
will need to be identified and then modified. Reducing or eliminating the
amount
of duplicated code can prevent this problem.
EXAMPLE
Parameters: Ignore identifiers turned on, minimum duplicated tokens size

set to 20.
int foo(int a, int b)
{
int r;
if (a < b) {
// duplicated code
r = b - a;
// duplicated code
} else {
// duplicated code
r = a - b;
// duplicated code
}
// duplicated code
return r;
}
int bar(int p, int q, bool v)
{
int result;
if (v) {
if (p < q) {
// duplicated code
result = q - p;
// duplicated code
} else {
// duplicated code
result = p - q;
// duplicated code
}
// duplicated code
} else {
return p + q;
}
return result;
}
REPAIR
int foo(int a, int b)
{
int r;
if (a < b) {
r = b - a;
} else {
r = a - b;
}
return r;
}
int bar(int p, int q, bool v)
{
int result;

if (v) {
result = foo(p, q);
} else {
result = p + q;
}
return result;
}

// use foo function here

Avoid string literal duplication [CDD-003-2]


DESCRIPTION
This rule identifies code with duplicated string literals. The rule finds
duplicated
string literals across all tested code, whether or not the duplicated
literals appear
in the same file. A violation is reported for each occurrence.
SINCE
v9.2
PARAMETERS
This rule can be parameterized to achieve best results.
* Minimum number of occurrences to be considered a violation (default
value is 5)
Will report violation only if minimum number of occurrences is found
* Ignore string literals of length less than (default value is 2)
All string literals which size is less than parameter value will not be
reported
* Ignore string literals that match specified regular expressions
All string literals which match any of regular expressions defined will
not be reported
BENEFITS
Rule improves readability and maintainability.
If a string literal is used repeatedly, it should be stored in a constant.
It would be much easier for a developer to change the value of a repeated
string
by just changing one single string constant instead of finding all the
repeated string
literals and changing them one by one.
EXAMPLE
const char* foo(int a, int b)
{
if (a > 0) {
return "pass";
// duplicated string
}
if (b > 0) {

return "pass";
}
if (a < b) {
return "pass";
}
if (a == b) {
return "pass";
}
if (a + b > 0) {
return "pass";
}
return "fail";

// duplicated string

// duplicated string

// duplicated string

// duplicated string

}
REPAIR
const char* foo(int a, int b)
{
const char* pass = "pass";
if (a > 0) {
return pass;
}
if (b > 0) {
return pass;
}
if (a < b) {
return pass;
}
if (a == b) {
return pass;
}
if (a + b > 0) {
return pass;
}
return "fail";
}

Avoid function duplication [CDD-004-2]


DESCRIPTION
This rule identifies duplicated implementations of functions. The rule
finds duplicated
implementations across all tested code, whether or not the duplicated code
appears
in the same file. A violation is reported for each occurrence.
See also: CDD-002
SINCE
v9.2
PARAMETERS
This rule can be parameterized to achieve best results.
* Minimum duplicate tokens size (default value is 80)
This parameter value defines minimum size of function which may be
reported by this rule.
Variable names, string and numeric literals, keywords, operators are
count as one token.
For example:
if (param1 == 0) {
return a;
}

// 7 tokens
// 3 tokens
// 1 token

"Ignore ..." parameters allows some differences to be ignored


and reported as duplicated code:
* Ignore string and character literals (default is off)
Turn it on to ignore string literals differences
* Ignore number literals (default is off)
Turn it on to ignore number literals differences
* Ignore boolean literals (default is off)
Turn it on to ignore boolean literals differences
* Ignore identifiers (local/global variables, function names, ...)
(default is off)
Turn it on to ignore identifiers differences

BENEFITS
Rule improves readability and maintainability. Simplifies and reduce code
size.
Copying and pasting code will increase the cost of code maintenance
because
each time a modification is required, multiple instance of the same code
will need to be identified and then modified. Reducing or eliminating the
amount
of duplicated code can prevent this problem.
EXAMPLE
Parameters: Ignore identifiers turned on, minimum duplicated tokens size
set to 20.
int foo(int a, int b)
{
int r;
if (a < b) {
r = b - a;
} else {
r = a - b;
}
return r;
}
int bar(int p, int q)
{
int result;
if (p < q) {
result = q - p;
} else {
result = p - q;
}
return result;
}
REPAIR
One of these functions can be removed and all references
can be switched to second one.

CODSTA
Coding Conventions
RULES
Array elements shall be accessed by the array operator [ ] [CODSTA-01-3]
Do not declare member variables as bit-fields [CODSTA-02-5]
Do not define constants via #define [CODSTA-03-3]
Do not declare local variables with the 'static' keyword [CODSTA-04-5]
Pointers to pointers should be avoided whenever possible [CODSTA-05-3]
Avoid using the '?:' operator [CODSTA-06-3]
If a function has no parameters, use ( ) instead of ( void ) [CODSTA-07-3]
Do not use break in for loops [CODSTA-08-2]
Do not cast pointers to functions to pointers to primitive types [CODSTA09-3]
Storage type modifiers shall be associated with the type, not the variable
or the function [CODSTA-10-3]
Assert liberally to document internal assumptions and invariants [CODSTA11-5]
Avoid using shift operations instead of arithmetic operations [CODSTA-123]
Avoid pointer arithmetic [CODSTA-13-3]
Never convert consts to non-consts [CODSTA-14-3]
Do not declare the size of an array when the array is passed into a
function as a parameter [CODSTA-15-2]
Do not declare the size of an array when the array is initialized [CODSTA16-2]
Do not compare a pointer to NULL or assign NULL to a pointer; use 0
instead [CODSTA-17-3]
Prefer while statements over do statements [CODSTA-18-5]
Use the ctype.h facilities for character test [CODSTA-19-3]
EOS should be used to terminate a string rather than NULL [CODSTA-20-2]
When using enum, the values of each member should be explicitly declared
[CODSTA-21-5]
Local variable or parameter names and class member variable or parent
class/struct member variable names shall differ by more than a single
character [CODSTA-22-1]
All 'if' statements should have an 'else' clause [CODSTA-23-3]
If FALSE is to be defined, and is not already defined, #define FALSE
should be 0 [CODSTA-24-5]
If FALSE is to be defined, and is not already defined, enum value FALSE
should be 0 [CODSTA-25-5]
Avoid magic numbers [CODSTA-26-3]
Avoid functions that modify global variables [CODSTA-27-3]
Define fields for union declarations [CODSTA-28-5]

"#define" or enum constants should be used instead of hard coded values


whenever possible [CODSTA-29-3]
Avoid returning handles to function parameters [CODSTA-30-3]
Never use explicit type conversions (casts) [CODSTA-31-3]
Do not write logical expressions of the type if(test) or if(!test) when
test is a pointer [CODSTA-32-3]
Do not use operator ++ or -- in the conditional expression of if, while,
or switch [CODSTA-33-3]
Use a typedef to simplify program syntax when declaring function pointers
[CODSTA-34-3]
Always provide a default branch for switch statements [CODSTA-35-3]
Pass built-in-types by value unless you are modifying them [CODSTA-36-3]
Do not use a #define that prevents the compiler from checking types except
ones used only in #ifs and #elifs conditions [CODSTA-37-3]
Do not use a #define that prevents the compiler from checking types
[CODSTA-38-3]
Avoid internal or external name conflict with a C++ reserved word [CODSTA39-1]
'void' should be used when a function is passed or returns no values
[CODSTA-40-3]
Avoid switch statements with only one case [CODSTA-41-4]
If TRUE is to be defined, and is not already defined, #define TRUE should
be 1 [CODSTA-42-5]
If TRUE is to be defined, and is not already defined, enum value TRUE
should be 1 [CODSTA-43-5]
Local variables and variables of class/parent classes/parent structs
should have different name [CODSTA-44-1]
Parameters and variables of class/parent classes/parent structs should
have different name [CODSTA-45-1]
Use positive logic rather than negative logic whenever practical [CODSTA46-5]
All structures should have typedefs [CODSTA-47-3]
The following digraphs will not be used <%, %>, <:, :>, %:, %:%: [CODSTA48-3]
Null initialize or increment expressions in for loops will not be used; a
while loop will be used instead [CODSTA-49-3]
Hexadecimal constants will be represented using all uppercase letters
[CODSTA-50-3]
Literal suffixes shall use uppercase rather than lowercase letters
[CODSTA-51-2]
The initialization expression in a for loop will perform no actions other
than to initialize the value of a single for loop parameter [CODSTA-52-3]
The increment expression in a for loop will perform no action other than
to change a single loop parameter to the next value for the loop [CODSTA-

53-3]
Every switch statement will have at least two cases and a potential
default [CODSTA-54-3]
Enumeration types shall be used instead of integer types (and constants)
as case labels [CODSTA-55-2]
All 'case' and 'default' labels of 'switch' statement should have an
explicit 'break' or a 'return' statement, or 'fall through' comment
[CODSTA-56-3]
Suspicious use of semicolon [CODSTA-57-4]
Cast to void is not allowed [CODSTA-58-4]
Hardcoded array declarations and 'malloc' calls should not be used
[CODSTA-59-4]
Avoid comparing values with TRUE macro/enum constant using equality
operators ("==", "!=") [CODSTA-60-3]
The final clause of a switch statement shall be the default-clause
[CODSTA-61-3]
A cast shall not convert a pointer to a function to any other pointer
type, including a pointer to function type [CODSTA-62-3]
Bitwise operators shall only be applied to operands of unsigned underlying
type [CODSTA-63-3]
An unconditional throw or break statement shall terminate every non-empty
switch-clause [CODSTA-64-3]
An object with integer type or pointer to void type shall not be converted
to an object with pointer type [CODSTA-65-3]
Non-constant operands to a binary bitwise operator shall have the same
underlying type [CODSTA-66-3]
The types used for an object, a function return type, or a function
parameter shall be token-for-token identical in all declarations and redeclarations [CODSTA-67-3]
A "U" suffix shall be applied to all octal or hexadecimal integer literals
of unsigned type [CODSTA-68-3]
Expressions with type (plain) char and wchar_t shall not be used as
operands to built-in operators other than =, ==, != and the unary &
operator [CODSTA-69-3]
Expressions with type enum shall not be used as operands to built-in
operators other than [ ], =, ==, !=, <, <=, >, >=, and the unary &
operator [CODSTA-70-3]
Named bit-fields with signed integer type shall have a length of more than
one bit [CODSTA-71-3]
Assembler instructions shall only be introduced using the asm declaration
[CODSTA-73-3]
Bit-fields shall not have enum type [CODSTA-74-3]
Bit-fields shall be either bool type or an explicitly unsigned or signed
integral type [CODSTA-75-3]

The identifier main shall not be used for a function other than the global
function main [CODSTA-76-3]
The goto statement shall jump to a label declared later in the same
function body [CODSTA-77-3]
Any label referenced by a goto statement shall be declared in the same
block, or in a block enclosing the goto statement [CODSTA-78-3]
For any iteration statement there shall be no more than one break or goto
statement used for loop termination [CODSTA-79-3]
The continue statement shall only be used within a well formed for loop
[CODSTA-80-3]
If a function has internal linkage then all redeclarations shall include
the static storage class specifier [CODSTA-81-3]
Avoid infinite loops [CODSTA-82-3]
All loops must have a fixed upper or lower bound [CODSTA-83-3]
Avoid exit points within infinite loops [CODSTA-85-3]
The validity of parameters must be checked inside each function [CODSTA86-3]
Use no more than one level of dereferencing [CODSTA-87-3]
Function pointers are not permitted [CODSTA-88-3]
The declaration should not contain more than one level of pointer
indirection [CODSTA-89-3]
Each operand of a logical '&&' or '||' shall be a postfix-expression
[CODSTA-90-3]
A function shall have at most one exit point [CODSTA-91-3]
The names of standard library macros and objects shall not be reused
[CODSTA-92-3]
The names of standard library functions shall not be overridden [CODSTA93-5]
Do not declare pointer or array type [CODSTA-94-3]
Do not declare pointer type [CODSTA-95-3]

CODSTA-CPP
Coding Conventions for C++
RULES
Prefer iostream.h to stdio.h [CODSTA-CPP-01-5]
Have assignment operator returns a reference to *this; make assignment
operator's return type a non-const reference to it's class' type [CODSTACPP-02-3]
Bitwise operators, comparison operators, logical operators, comma operator
should be const [CODSTA-CPP-03-3]
Constructors allowing for conversion should be made explicit [CODSTA-CPP04-1]
Do not use user-defined conversion functions [CODSTA-CPP-05-1]
Avoid returning handles to class data from member functions [CODSTA-CPP06-3]
Postfix increment and decrement should be implemented in terms of their
prefix counterparts [CODSTA-CPP-07-3]
Avoid overloading &&, || or , (comma) [CODSTA-CPP-08-3]
Avoid using reinterpret_cast [CODSTA-CPP-09-3]
Do not define structs that contain member functions [CODSTA-CPP-10-3]
Prefer C++-style casts [CODSTA-CPP-11-3]
Put classes that are used as base classes and classes that are used as
member variables into separate include files [CODSTA-CPP-12-3]
Put classes that are used as function return type into separate include
files [CODSTA-CPP-13-3]
Put classes that are used as argument types in function prototypes into
separate include files [CODSTA-CPP-14-3]
Put functions that are used in the body of inline member function into
separate include file [CODSTA-CPP-15-3]
When two operators are opposites (such as == and !=), it is appropriate to
define both [CODSTA-CPP-16-3]
Do not use the 'struct' keyword to declare a variable in C++ [CODSTA-CPP17-3]
Encapsulate global variables and constants, enumerated types, and typedefs
in a class [CODSTA-CPP-18-5]
Declare at least one constructor to prevent the compiler from doing so
[CODSTA-CPP-19-2]
If you'd like to support mixed-mode operations make operators a non-member
functions [CODSTA-CPP-20-3]
Assignment operator must return const reference [CODSTA-CPP-21-5]
Prefer non-member non-friend functions to member functions [CODSTA-CPP-223]
Whenever a global function is referenced, use the :: operator [CODSTACPP-23-5]

Avoid making any assignment operator virtual. Do not return const T& from
assignment operator [CODSTA-CPP-24-3]
Consider making virtual functions nonpublic, and public functions
nonvirtual [CODSTA-CPP-25-3]
Keep types and functions in separate namespaces unless they're
specifically intended to work together [CODSTA-CPP-26-3]
Keep a type and its nonmember function interface in the same namespace
[CODSTA-CPP-27-3]
When binary arithmetic operators are defined ( + , - , * , / , ^ , % , |
, & , >> , << ), assignment versions should be provided too [CODSTA-CPP28-3]
Prefer the canonical forms of arithmetic and assignment operators [CODSTACPP-29-3]
Prefer non-member operators than member ones to support mixed-mode
arithmetic [CODSTA-CPP-30-3]
Do not use the keyword 'explicit' for a constructor [CODSTA-CPP-31-5]
Member functions shall not be defined within the no-template class
definition [CODSTA-CPP-32-3]
Member functions shall not be defined within the template class definition
[CODSTA-CPP-33-3]
Avoid using static_cast on pointers [CODSTA-CPP-34-3]
Avoid dynamic_casts [CODSTA-CPP-35-3]
Avoid using global variables, global functions, and class in file outside
namespaces [CODSTA-CPP-36-3]
Do not define class/struct/union inside function implementation [CODSTACPP-37-3]
Conversion operator, operator->, operator(), operator[] should be const
[CODSTA-CPP-38-3]
Don't write namespace usings in a header file or before an #include
[CODSTA-CPP-39-3]
Limiting the number of objects of a class [CODSTA-CPP-40-5]
Do not use the 'enum' keyword to declare a variable in C++ [CODSTA-CPP-413]
Do not declare member variables with the 'mutable' keyword [CODSTA-CPP-423]
Declare reference parameters as const references whenever possible
[CODSTA-CPP-43-3]
Have the non-const version call the const version of member function
instead of duplicating the const version definition [CODSTA-CPP-44-3]
In the private section of a class items shall be declared in the following
order: Constructors, Destructor, Member Functions, Member Operator
Function, Enumerations and others [CODSTA-CPP-45-3]
Order of scopes in class: public before all others [CODSTA-CPP-46-3]

Order of scopes in classes: protected before private [CODSTA-CPP-47-3]


In the protected section of a class items shall be declared in the
following order: Constructors, Destructor, Member Functions, Member
Operator Function, Enumerations and others [CODSTA-CPP-48-3]
In the public section of a class items shall be declared in the following
order: Constructors, Destructor, Member Functions, Member Operator
Function, Enumerations and others [CODSTA-CPP-49-3]
Do not use static keyword except inside functions and classes [CODSTA-CPP50-3]
Do not define inline functions in source files [CODSTA-CPP-51-3]
Consider using the natural relationship between the assignment version of
an operator and the stand-alone version [CODSTA-CPP-52-3]
Declare parameters or local variable as const whenever possible [CODSTACPP-53-3]
Member functions shall be declared const whenever possible [CODSTA-CPP-543]
Arrays shall not be used in interfaces [CODSTA-CPP-55-2]
A class, structure, or enumeration will not be declared in the definition
of its type [CODSTA-CPP-56-3]
Namespaces will not be nested more than two levels deep [CODSTA-CPP-57-3]
The value returned by a function having a non-void return type that is not
an overloaded operator shall always be used [CODSTA-CPP-58-3]
The C library shall not be used [CODSTA-CPP-59-3]
Only those escape sequences that are defined in ISO/IEC 14882:2003 shall
be used [CODSTA-CPP-60-3]
Objects or functions with external linkage shall be declared in a header
file [CODSTA-CPP-61-3]
NULL shall not be used as an integer value [CODSTA-CPP-62-3]
Literal zero (0) shall not be used as the null-pointer-constant [CODSTACPP-63-3]
The condition of an if-statement and the condition of an iterationstatement shall have type bool [CODSTA-CPP-64-3]
The first operand of a conditional-operator shall have type bool [CODSTACPP-65-1]
C-style casts (other than void casts) and functional notation casts (other
than explicit constructor calls) shall not be used [CODSTA-CPP-66-3]
Each operand of the ! operator, the logical && or the logical || operators
shall have type bool [CODSTA-CPP-67-3]
The unary & operator shall not be overloaded [CODSTA-CPP-68-3]
A for loop shall contain a single loop-counter which shall not have
floating type [CODSTA-CPP-69-3]
If loop-counter is not modified by -- or ++, then, within condition, the
loop-counter shall only be used as an operand to <=, <, > or >= [CODSTACPP-70-3]

The loop-counter shall be modified by one of: --, ++, -=n, or +=n; where n
remains constant for the duration of the loop [CODSTA-CPP-71-3]
A loop-control-variable other than the loop-counter shall not be modified
within condition or expression [CODSTA-CPP-72-3]
A loop-control-variable other than the loop-counter which is modified in
statement shall have type bool [CODSTA-CPP-73-3]
There shall be no unnamed namespaces in header files [CODSTA-CPP-74-3]
using-directives shall not be used [CODSTA-CPP-75-3]
Multiple declarations for an identifier in the same namespace shall not
straddle a using-declaration for that identifier [CODSTA-CPP-76-3]
Const member functions shall not return non-const pointers or references
to class-data [CODSTA-CPP-77-3]
If a member function can be made static then it shall be made static,
otherwise if it can be made const then it shall be made const [CODSTA-CPP78-3]

Prefer iostream.h to stdio.h [CODSTA-CPP-01-5]


DESCRIPTION
This rule finds instances of stdio.h functions (such as scanf/printf)
and suggests changing them to iostream.h functions
(such as operator>> and operator<< ).

BENEFITS
Prevents using instances of stdio.h functions (such as scanf/printf).

EXAMPLE
#include <stdio.h>
int main( ) {
printf("%s\n", "Hello World"); // Violation
return 0;
}

REPAIR
#include <iostream>
using namespace std;
int main( ) {
cout<<"Hello World"<<endl; // OK
return 0;
}

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Shifting from C to C++",
Item 2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Have assignment operator returns a reference to *this; make assignment operator's return
type a non-const reference to it's class' type [CODSTA-CPP-02-3]
DESCRIPTION
This rule makes sure your assignment operator's return type is non-const
reference to it's class' type and that it returns a reference to its lefthand
argument, *this. Having operator= return a reference to *this protects you
from not knowing where the temporary gets destroyed and allows you to
declare
the operator='s parameter as a reference to const, which is safer than
just
declaring it to be a reference.
See also: CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37, MRM-40, MRM-47,
OOP-27,
OOP-30, OOP-34

BENEFITS
Returning reference to *this in operator= functions protects you from not
knowing where the temporary gets destroyed and allows you to declare
the operator='s parameter as a reference to const, which is safer than
just
declaring it to be a reference.

EXAMPLE
class A {
public:
A( ) { }
void operator=( A& a ) {
return;
}
};
class C {
public:
C( ) { }
C operator=( C& c ) {
C *cp;
return *cp;
}

// Violation

// Violation

};

REPAIR
class A {
public:
A( ) { }
A& operator=( A& a ) {
return *this;
}
};
class C {
public:
C( ) { }
C& operator=( C& c ) {
return *this;
}
};

// OK

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 15
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 15
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 82
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Bitwise operators, comparison operators, logical operators, comma operator should be const
[CODSTA-CPP-03-3]
DESCRIPTION
Bitwise operators, comparison operators, logical operators,
comma operator should be const.
See also: CODSTA-CPP-38, CODSTA-CPP-43, CODSTA-CPP-44,
MISRA-104, MISRA2004-16_7, OPT-21

BENEFITS
C++ powerful const property should be enforced as appropriate,
to provide additional checks on the correct behavior of the code.
The semantics of operators "&", "^", "|", "~", "!=", "<=", "<",
"==", ">=", ">", "!", "&&", "||" ,and ","
presumes that they do not change the internals of the object they
are called on. Therefore, it is a good practice to declare them const.

EXAMPLE
class A {
public:
A& operator^( int x );
A& operator==( int x );
A& operator&&( int x );
A& operator,( int x );
};

//
//
//
//

Violation
Violation
Violation
Violation

REPAIR
class A {
public:
A& operator^( int x ) const;
A& operator==( int x ) const;
A& operator&&( int x ) const;
A& operator,( int x ) const;
};

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Constructors allowing for conversion should be made explicit [CODSTA-CPP-04-1]


DESCRIPTION
Be wary of user-defined conversion functions.
Constructors allowing for conversion should be made explicit.
Constructors with one argument can be implicitly used by the compiler to
perform type conversions. Such calls may in the best case result in
creating
and destroying temporary objects, affecting runtime, and in the worst,
allow
the most meaningless code to compile. In the latter case, problems that
could
be detected at compile time are pushed to run-time testing.
See also: CODSTA-CPP-05

BENEFITS
Generally improves runtime performance and predictability of program
behavior. May detect severe coding defects masked by the compiler.

EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
virtual ~A( ) {}
private:
int _i;
};

// Violation

int main( ) {
return 0;
}

REPAIR
/* One argument constructors that are not meant for type conversion should
be declared explicit. Conversions should be performed by conversion
functions rather than relying on implicit constructor calls. */

class A {
public:
explicit A( int i ) : _i( i ) {}
virtual ~A( ) {}
private:
int _i;
};

// OK

int main( ) {
return 0;
}

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 5
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 40

Do not use user-defined conversion functions [CODSTA-CPP-05-1]


DESCRIPTION
Be wary of user-defined conversion functions. This rule warns you when it
finds
user-defined conversion functions. Such calls may in the best case result
in
creating and destroying temporary objects, affecting runtime, and in the
worst,
allow the most meaningless code to compile. In the latter case, problems
that
could be detected at compile time are pushed to run-time testing.
See also: CODSTA-CPP-04

BENEFITS
Generally improves runtime performance and predictability of program
behavior. May detect severe coding defects masked by the compiler.

EXAMPLE
class A {
public:
operator const char*( ) const;
};

// Violation

void foo(){
A a;
const char* ch_ptr = a; // implicit conversion
}

REPAIR
class A {
public:
const char* asPointerToConstChar( ) const; // OK
};
void foo(){
A a;

const char* ch_ptr = a.asPointerToConstChar(); // explicit conversion


}

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 5
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 177

Avoid returning handles to class data from member functions [CODSTA-CPP-06-3]


DESCRIPTION
"A function that returns a handle to an internal part of the object
is dangerous. It doesn't matter whether the handle is a pointer, a
reference,
or an iterator. It doesn't matter whether it's qualified with const.
It doesn't matter whether the member function returning the handle
is itself const. All that matters is that a handle is being returned,
because once that's being done, you run the risk that the handle will
outlive the object it refers to."
The rule reports a violation if a member function returns reference or
pointer
to class-data.
See also: CODSTA-CPP-77, OOP-12, OOP-36

SINCE
v7.2

NOTES
Handle to class-data is:
- reference to member variable
- pointer to member variable
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.

BENEFITS
The rule increases encapsulation, helps const member functions act const,
and minimizes the creation of dangling handles.

EXAMPLE
class Test
{
public:

Test(int & p) : _i(p)


{
_k = new int; // makes data pointed by _k a "class-data"
}
~Test()
{
if (_k) {
delete _k;
}
}
int* GetI1()
{
return &_i; // Violation
}
int& GetI2() const
{
return _i; // Violation
}
protected:
const int * GetI3() const
{
return _k; // Violation
}
private:
int & _i;
int * _k;
};
const int * ptr = 0;
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
ptr = GetI3(); // Pointer to internal object saved
}
private:
int z;
};
void bar()
{
int * i1 = 0;

{
Child c;
i1 = c.GetI1(); // Pointer to internal object saved
}
int & i2 = Child().GetI2(); // Reference to internal object saved
// Now "ptr", "i2" and "i3" are dangling pointers/references
}

REPAIR
Avoid returning handles to class-data.

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Postfix increment and decrement should be implemented in terms of their prefix counterparts
[CODSTA-CPP-07-3]
DESCRIPTION
"The prefix and postfix forms of these operators return different types.
In particular, prefix forms return a reference, postfix forms return
a const object. Let us make one more observation about the prefix and
postfix
increment operators. Except for their return values, they do the same
thing:
they increment a value. That is, they're supposed to do the same thing.
How can you be sure the behavior of postfix increment is consistent with
that of prefix increment? What guarantee do you have that their
implementations
won't diverge over time, possibly as a result of different programmers
maintaining and enhancing them? Unless you've followed the design
principle
embodied by the code below, you have no such guarantee. That principle is
that
postfix increment and decrement should be implemented in terms of their
prefix
counterparts. You then need only maintain the prefix versions,
because the postfix versions will automatically behave in a consistent
fashion."

SINCE
v7.0

BENEFITS
This rule prevents errorneous code and increase power and flexibility of
code.

EXAMPLE
class A {
public:
explicit A( int i = 0 ) : _i( i ) {}
~A( ) {}

A operator++( )
reference
{
++_i;
return *this;
}
A operator++( int )
const
{
A temp = *this;
++(*this);
return temp;
}
private:
int _i;
};

// Violation - return type is not

// Violation - return type is non

REPAIR
class A {
public:
explicit A( int i = 0 ) : _i( i ) {}
~A( ) {}
A& operator++( ) {
// OK
++_i;
return *this;
}
const A operator++( int ) {
// OK
A temp = *this;
++(*this);
return temp;
}
private:
int _i;
};

Prefix

increment operator

Postfix increment operator

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 6

2. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid overloading &&, || or , (comma) [CODSTA-CPP-08-3]


DESCRIPTION
"The built-in &&, || or, (comma) enjoy special treatment from the
compiler.
If you overload them, they become ordinary functions with very different
semantics, and this is a sure way to introduce subtle bugs and
fragilities."
This rule detects when you overload operator &&, || or ,(comma).

BENEFITS
Overloading these operators changes the way the compiler reads the
semantics of an expression, resulting in unpredictable program behavior.

EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
~A( );
int value( ) { return _i; }
private:
int _i;
};
int operator&&( A& lhs, A& rhs ) {
return lhs.value( ) && rhs.value( );
}

// Violation

REPAIR
Do not overload operator &&, || or ,(comma).

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,

(C) 2005 Pearson Education, Inc.


Chapter: "Functions and Operators", Rule 30
2. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 159
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-11
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid using reinterpret_cast [CODSTA-CPP-09-3]


DESCRIPTION
"Don't try to use reinterpret_cast to force the compiler to reinterpret
the
bits of an object of one type as being the bits of an object of a
different
type. That's the opposite of maintaining type safety, and reinterpret_cast
isn't even guaranteed to do that or anything else in particular."

BENEFITS
Prevents assumptions how data is represented, which may dramatically
affect
the safety and reliability of code.

EXAMPLE
class A{};
class B{};
void foo( ) {
A *a;
B *b = reinterpret_cast<B*>( a );
}

// Violation

REPAIR
class A{};
class B{};
void foo( ) {
A *a;
void *pv = a;
B *b = static_cast<B*>( pv );
}

// OK

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 92

Do not define structs that contain member functions [CODSTA-CPP-10-3]


DESCRIPTION
Member functions should be contained in classes, not structs, because
classes
support both multiple instances and encapsulation. Structs are also often
entirely public: whereas the default access level for members and base
classes
of a class is private. This rule detects if you define structs that
contain
member functions.

BENEFITS
Readability. It is generally expected that types with member functions
are classes, and many programmers still think of structs in terms
of their original meaning in C.

EXAMPLE
struct A
{
public:
int foo( );
};

// Violation

REPAIR
class A
{
public:
int foo( );
};

REFERENCES

// OK

Recommended by ParaSoft

Prefer C++-style casts [CODSTA-CPP-11-3]


DESCRIPTION
This rule detects C-style casts in your code.
"Traditional C-style casts raise several concerns. First, they enable most
any
type to be converted to most any other type without any indication of the
reason
for the conversion. Next, the C-style cast syntax: '(type) expression'
is difficult to identify for both reviewers and tools. Consequently,
both the location of conversion expressions as well as the subsequent
analysis
of the conversion rationale proves difficult for C-style casts.
Thus, C++ introduces several new-style casts (const_cast, dynamic_cast,
reinterpret_cast, and static_cast) that address these problems.
Not only are these casts easy to identify, but they also communicate more
precisely the developers intent for applying a cast."

BENEFITS
"Programs that use the new casts are easier to parse
(both for humans and for tools), and they allow compilers
to diagnose casting errors that would otherwise go undetected."

EXAMPLE
void foo1(){
int i, j;
double d = (double)i/j;
}

// Violation

class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = (Derived*)b;

// Violation

REPAIR
void foo1(){
int i, j;
double d = static_cast<double>(i)/j;
}

// OK

class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = dynamic_cast<Derived*>(b);
}

// OK

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Basics", Item 2
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 95
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 185

Put classes that are used as base classes and classes that are used as member variables into
separate include files [CODSTA-CPP-12-3]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- classes that are used as base classes,
- classes that are used as member variables,
See also: CODSTA-CPP-15, CODSTA-CPP-14, CODSTA-CPP-13

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class A {};
class B : public A {
A* a;
};

// Violation
// Violation

REPAIR
// header.h
class A {};
// source.cpp
#include "header.h"
class B : public A {
A* a;
};

// OK

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 8

Put classes that are used as function return type into separate include files [CODSTA-CPP-133]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- classes that appear as return types
See also: CODSTA-CPP-15, CODSTA-CPP-14, CODSTA-CPP-12

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class A {};
A* moo( );
class B {
A* foo( );
};

// Violation
// Violation

REPAIR
// header.h
class A {};
// source.cpp
#include "header.h"
A* moo( );
class B {
A* foo( );
};

// OK
// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 8

Put classes that are used as argument types in function prototypes into separate include files
[CODSTA-CPP-14-3]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- classes that appear as argument types in function/member
function prototypes.
See also: CODSTA-CPP-15, CODSTA-CPP-13, CODSTA-CPP-12

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class A {};
void moo( A* a );
class B {
void foo( A* a );
};

// Violation
// Violation

REPAIR
// header.h
class A {};
// source.cpp
#include "header.h"
void moo( A* a );
class B {
void foo( A* a );
};

// OK
// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.4 Include Files - Rule 8

Put functions that are used in the body of inline member function into separate include file
[CODSTA-CPP-15-3]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- function prototypes for function/member function used in inline member
function are defined in the file."
See also: CODSTA-CPP-14, CODSTA-CPP-13, CODSTA-CPP-12

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void moo( );
class A
{
inline void foo( )
{
moo( );
}
};

// Violation

REPAIR
// header.h
void moo( );
// source.cpp
#include "header.h"
class A
{
inline void foo( )
{
moo( );
}
};

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 8

When two operators are opposites (such as == and !=), it is appropriate to define both
[CODSTA-CPP-16-3]
DESCRIPTION
"When a client of a class is allowed to apply an operator against a class,
it also expects to be able to apply the negation of that operator against
a class. A good example is the operator==; its semantic opposite is the
operator!=, which should also be defined if operator== was defined."
Rule prevents using:
- '==' operator without '!=' operator
- '<=' operator without '>=' operator
- '<' operator without '>' operator
- '++' operator without '--' operator
- '+' operator without '-' operator
- '<<' operator without '>>' operator
- '&&' operator without '||' operator

BENEFITS
Rule improves readability and maintainability of code and
prevents misunderstanding the meaning of an overloaded operator.

EXAMPLE
class C { // Violation
public:
bool operator<=( C& c );
};

REPAIR
class C { // OK
public:
bool operator<=( C& c );
bool operator>=( C& c );
};

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.7 Operator Overloading - Rec. 36
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 85
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not use the 'struct' keyword to declare a variable in C++ [CODSTA-CPP-17-3]


DESCRIPTION
This rule checks whether your C++ code uses struct keywords to declare
a variable. This rule applies only to the C++ programming language.

BENEFITS
Not using the struct keyword to declare a variable improves code
readability.

EXAMPLE
struct Position_t {};
struct Position_t Pos;

// Violation

REPAIR
struct Position_t {};
Position_t Pos;

// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Encapsulate global variables and constants, enumerated types, and typedefs in a class
[CODSTA-CPP-18-5]
DESCRIPTION
"Encapsulate global variables and constants, enumerated types, and
typedefs
in a class. Static variables in a class should be used instead of global
variables and constants, enumerated data types, and typedefs."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
enum Days {yesterday};
typedef int myint;
myint glob;

// Violation
// Violation
// Violation

REPAIR
class A {
public:
enum Days {yesterday};
typedef int MyInt;
static MyInt glob;
};

// OK
// OK
// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 5 Assigning Names - Rec. 19
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 207
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff

Document issued on: January 11, 2002


4. ISO/DIS 26262
point 8.4.4

Declare at least one constructor to prevent the compiler from doing so [CODSTA-CPP-19-2]
DESCRIPTION
If you do not write at least one constructor in a class, the compiler will
write a public constructor for you by default. This rule detects if you
do not declare at least one constructor.
See also: MRM-05, MRM-38, MRM-40, MRM-48, OOP-27, OOP-30, OOP-34

BENEFITS
Readability. If you follow this rule, you will make class initialization
explicit and prevent the compiler from initializing members improperly,
especially pointer members.

EXAMPLE
class A {
};

// Violation

REPAIR
class A {
A(){}
};

// OK

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 5

If you'd like to support mixed-mode operations make operators a non-member functions


[CODSTA-CPP-20-3]
DESCRIPTION
This rule checks declared two-argument operators to make sure they are
proper
for the class type used. You know you'd like to support arithmetic
operations
like addition, subtraction, multiplication, etc., but you're unsure
whether
you should implement them via a member function, a non-member function.
If class contains a conversion operators or constructors allowing implicit
conversion you should define operators global because it makes operations
commutative. operator>> and operator<< are never members. If f is
operator>>
or operator<<, make f a non-member function. Here the goal is a natural
calling
syntax; earlier we were concerned about implicit type conversions.

BENEFITS
Differentiating among functions leads to more object-oriented code
with behavior that is more intuitive to use and maintain.

EXAMPLE
#include <iostream>
using namespace std;
class A{
public:
A(int x=0);
A& operator+(A& a); // Violation (could be global)
};
class B{
public:
istream& operator>>(istream& input);

// Violation
// should be

global
ostream& operator<<(ostream& output) { as = "aaaa"; }; // Violation

// should be
friend
private:
char* as;
};

REPAIR
class A{
public:
A(int x=0);
};
A& operator+(A& a, A& b); // OK
class B{
public:
friend ostream& operator<<(ostream& output, B& out);
private:
char* as;
};
istream& operator>>(istream& input,const B& in);
ostream& operator<<(ostream& output, B& out) {
out.as = "aaaa";
return output;
};

// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Design and Declaration", Item 19
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Assignment operator must return const reference [CODSTA-CPP-21-5]


DESCRIPTION
"An assignment operator ought to return a const reference to the assigning
object."
See also: CODSTA-CPP-02, CODSTA-CPP-24, MRM-04, MRM-37, MRM-40, MRM-47,
OOP-27,
OOP-30, OOP-34

NOTES
The rule became obsolete because of new standard (Herb Sutter,Andrei
Alexandrescu, "C++ Coding Standards," Addison-Wesley, (C) 2005 Pearson
Education, Inc. Chapter: "Construction, Destruction, and Copying", Rule 55
)
which is implemented in CODSTA-CPP-24

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class MyClass {
public:
void operator=( const MyClass& );
};

// Violation

REPAIR
class MyClass {
public:
const MyClass& operator=( const MyClass& ); // OK
};

REFERENCES
Ellemtel Coding Standards

http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 7 Classes - 7.6 Assignment Operators - Rec. 34

Prefer non-member non-friend functions to member functions [CODSTA-CPP-22-3]


DESCRIPTION
"The non-member approach is thus better than a member function in many
ways.
The member function actually yields less encapsulation than the nonmember.
Furthermore, offering the non-member function allows for greater packaging
flexibility, related functionality, and that, in turn, yields fewer
compilation
dependencies and an increase extensibility.
Friends have the same access to a class's private members that member
functions
have, hence the same impact on encapsulation. From an encapsulation point
of view, the choice isn't between member and non-member functions, it's
between
member functions and non-member non-friend functions."
Rule reports violation on the member functions which call public functions
and don't have the access to private and protected members.

SINCE
v7.0

BENEFITS
Rule ensures greater flexibility and safety of code.

EXAMPLE
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
void clearEverything();
};
void WebBrowser::clearEverything()
{

// Violation

clearCache();
clearHistory();
removeCookies();
}

REPAIR
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
};
void clearEverything(WebBrowser& wb)
{
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 23
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Whenever a global function is referenced, use the :: operator [CODSTA-CPP-23-5]


DESCRIPTION
Whenever a global function is used, use the :: operator.
This rule detects if you do not use the :: operator whenever a global
function
is used. Using the :: operator in these situations will make it easier
to determine which variable is being used.

BENEFITS
Readability and maintainability. Using the :: operator helps the
maintainer of
code clearly identify used function.

EXAMPLE
namespace N {
void globalFoo1( );
}
void globalFoo1( ) {
}
void globalFoo2( ) {
globalFoo1( );
N::globalFoo1( );
}

// Violation
// Violation

REPAIR
namespace N {
void globalFoo1( );
}
void globalFoo1( ) {
}
void globalFoo2( ) {
::globalFoo1( );

// OK

::N::globalFoo1( ); // OK
}

REFERENCES
Recommended by ParaSoft

Avoid making any assignment operator virtual. Do not return const T& from assignment
operator [CODSTA-CPP-24-3]
DESCRIPTION
"Avoid making any assignment operator virtual."
If you need virtual assignment, prefer to provide a named function
instead (e.g. virtual void Assign(const &T)). "Don't return const T&.
Although this has the benefit of preventing odd code like (a=b)=c, it has
the
drawback that you wouldn't be able to put T objects into standard
library containers; the containers require that assignment return plain
T&."
See also: CODSTA-CPP-02, CODSTA-CPP-21, MRM-04, MRM-37, MRM-40, MRM-47,
OOP-27,
OOP-30, OOP-34

BENEFITS
Rule prevents lack of error safety and improves good programming style.

EXAMPLE
class A {
public:
virtual int& operator=(const int&); // Violation
const A& operator=(const A&);
// Violation
};
template<class T> class B {
public:
virtual T& operator=(const T&);
const B<T>& operator=(B<T>&);
};

// Violation
// Violation

template<class T> class C {


public:
const C<T>& operator=(const C<T>&); // Violation
virtual T& operator=(T&);
// Violation
};

REPAIR
class A {
public:
const int& operator=(const int&);
A& operator=(const A&);
};
template<class T> class B {
public:
T& operator=(const T&);
B<T>& operator=(B<T>&);
};
template<class T> class C {
public:
C<T>& operator=(const C<T>&);
T& operator=(T&);
};

// OK
// OK

// OK
// OK

// OK
// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 55
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Consider making virtual functions nonpublic, and public functions nonvirtual [CODSTA-CPP25-3]
DESCRIPTION
"Prefer to make public functions nonvirtual.
Prefer to make virtual functions private,
or protected if derived classes need to be able to call the base
versions."

EXCEPTIONS
"Rule doesn't apply to destructors because of their special
order of execution."

BENEFITS
Rule helps keeping good class encapsulation, makes the base class robust
in the face of change, allows each interface to take its natural shape.

EXAMPLE
class A{
public:
virtual void foo(); // Violation
void goo();
};

REPAIR
class B{
public:
void goo();
private:
virtual void foo(); // OK
};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 39
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Keep types and functions in separate namespaces unless they're specifically intended to work
together [CODSTA-CPP-26-3]
DESCRIPTION
"We've all had those days, and the odds are decent that the mystery
culprit was
some form of the aforementioned problem, where ADL pulled in names from
other
namespaces inappropriately just because types from those namespaces were
being
used nearby.
This problem is not unique to uses of the standard library. It can and
does
happen in C++ with the use of any type that is defined in the same
namespace
as functions - especially templated functions, and most especially
operators that aren't specifically related to that type. Don't do that.
The easiest way to avoid this whole category of problems is to in general
avoid
putting nonmember functions that are not part of the interface of a type X
into
the same namespace as X, and especially never ever put templated functions
or
operators into the same namespace as a user-defined type."

SINCE
v7.0

BENEFITS
This rule prevents from mysterious and incomprehensible compiler errors,
mainly when the standard library is used.

EXAMPLE
namespace NS1 {
class Class {};
void foo01( );

// Violation

void foo02( int x );


// Violation
void foo03( Class x ); // OK
void foo04( Class* x ); // OK
}

REPAIR
namespace NS1 {
class Class {};
void foo03( Class x );
void foo04( Class* x );
}
namespace NS2 {
void foo01( );
void foo02( int x );
}

// OK
// OK

// OK
// OK

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 58

Keep a type and its nonmember function interface in the same namespace [CODSTA-CPP-273]
DESCRIPTION
"Nonmember functions that are designed to be a part of the interface of
a class X (operators and helper functions) must be defined in the same
namespace as the X in order to be called correctly."

BENEFITS
Rule improves efficiency and readability of code.

EXAMPLE
namespace N{
class X{
public:
void foo();
};
}
N::X operator+(const N::X&, const N::X&); // Violation

REPAIR
namespace N{
class X{
public:
void foo();
X operator+(const X&);
};
}

// OK

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 57

When binary arithmetic operators are defined ( + , - , * , / , ^ , % , | , & , >> , << ), assignment
versions should be provided too [CODSTA-CPP-28-3]
DESCRIPTION
When binary arithmetic operators are defined
( + , - , * , / , ^ , % , | , & , >> , << ), assignment versions
should be provided too.
This rule warns you whenever it finds binary operator without
canonical assignment version.
See also: CODSTA-CPP-29

BENEFITS
Assignment versions of operator are more efficient than standalone versions.

EXAMPLE
class A{};
A operator+( A& a, A& b );
class B{
B operator+( B& a );
};

// Violation operator+ without operator+=

// Violation operator+ without operator+=

REPAIR
class A{};
A operator+( A& a, A& b ); // OK
A operator+=( A& a, A& b ); // OK
class B{
B operator+( B& a );
B operator+=( B& a );
};

// OK
// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-

Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 27
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer the canonical forms of arithmetic and assignment operators [CODSTA-CPP-29-3]


DESCRIPTION
Define binary operator @ (where @ is + , - , * , / , ^ , % , | , & , >> ,
<< )
in terms of its assignment version @= so a@=b and a=a@b
have the same meaning. The canonical way of achieving this goal
is to define @ in terms of @=, as follows:
T& T::operator@=(const T&){
// implementation
return *this;
}
T operator@( const T& lhs, const T& rhs){
T templ(lhs);
return temp @= rhs;
}
Where possible make operator @= a nonmember function.
Also it is desired to have operator@ accepting its first
parameter by value and returning a const value.
Rule checks if declared binary operators @, @= adhere to presented
above conventions.
See also: CODSTA-CPP-28, CODSTA-CPP-52

BENEFITS
If operator@ is made a nonmember function, it will have the desirable
property
of accepting the same implicit conversions on its left-hand side and
right-hand
side parameters. By having operator@ accepting its first parameter by
value,
you arrange for compiler itself to perform the copy for you implicitly,
and this
can give the compiler more leeway in applying optimizations.
Making the operator@ returning a const value has the advantage that it
disables
nonsensical code such as a + b = c, but it does so at the cost of
disabling some

potentially useful constructs such as a = (b + c).replace(pos, n, d)


- expressive code that, in one shot, concatenates strings b, c, replaces
some
characters, and assigns the final result t a.

EXAMPLE
class A{
public:
A( const A& );
A operator+=( A& a ){}
A operator-=( A& a ){}
A& operator-( A& a ){}

global
A operator*=( A& a ){}
should

// Violation - Operator method should result


//
class as a direct type
//
- Operator method should be
// Violation - The function's return type
//
//

be a reference to class
- The last operation of "*="

function
//

should be return *this

};
A operator+( A& a, A& b ){
// Violation - No return statement...
return a.operator+=( a );//
- Declare and initialize
temporary
//
local variable by first
parameter
};
A operator*( A& a, A& b ){
example

// Violation - Code does not match with


//

A tmp(a);
return tmp += b;
return tmp *= b;
};

REPAIR
class A{
public:

code from rule description

// Violation - Incorrect operation name

A& operator+=( A& a ){ // OK


// ... implementation ...
return *this;
}
A& operator-=( A& a ){ // OK
// ... implementation ...
return *this;
}
A& operator*=( A& a ){ // OK
// ... implementation ...
return *this;
}
};
A operator-( A& a, A& b ){
A tmp(a);
return tmp -= b;
}

// OK
// OK
// OK

A operator+( A& a, A& b ){


A tmp(a);
return tmp += b;
};

// OK
// OK
// OK

A operator*( A& a, A& b ){


A tmp(a);
return tmp *= b;
};

// OK
// OK
// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 27
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer non-member operators than member ones to support mixed-mode arithmetic [CODSTACPP-30-3]
DESCRIPTION
"Declare non-member functions when type conversions should apply to all
parameters."

SINCE
v7.0

BENEFITS
Declaration of non-member functions allows compilers to perform implicit
type
conversions on all arguments and supports mixed mode arithmetic.

EXAMPLE
class complex {
double re, im;
public:
complex( double r, double i ) : re( r ), im( i ) {}
complex operator+ ( complex );
complex operator+=( complex );
};

REPAIR
class complex {
double re, im;
public:
complex( double r, double i ) : re( r ), im( i ) {}
complex& operator+=( complex a );
};
complex operator+( complex a, complex b ) {
complex r = a;
return r += b;

// OK

// Violation

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 24
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not use the keyword 'explicit' for a constructor [CODSTA-CPP-31-5]


DESCRIPTION
This rule checks if you use the keyword `explicit' for a constructor.
See also: CODSTA-CPP-04

BENEFITS
Prevents using the keyword `explicit'.

EXAMPLE
class A {
public:
explicit A( int );
explicit A( double ) {}
};

REPAIR
class A {
public:
A( int );
A( double ) {}
};

// OK
// OK

REFERENCES
Recommended by ParaSoft

// Violation
// Violation

Member functions shall not be defined within the no-template class definition [CODSTA-CPP32-3]
DESCRIPTION
Functions defined within the class definition are implicitly inline;
however,
defining member functions within a class definition also makes the class
definition less compact and harder to read. This rule detects if you
define
member functions in the class definition.
See also: CODSTA-CPP-33

BENEFITS
This rule ensure better data hiding by separating interface and
implementation.

EXAMPLE
class A {
public:
int foo( ) {};
inline int bar( );
};

// Violation

inline int A::bar( ) {


return 0;
};

REPAIR
class A {
public:
int foo( );
inline int bar( );
};
int A::foo( ) {};
inline int A::bar( ) {
return 0;

// OK

};

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 21
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 109

Member functions shall not be defined within the template class definition [CODSTA-CPP-333]
DESCRIPTION
Functions defined within the class definition are implicitly inline;
however,
defining member functions within a class definition also makes the class
definition less compact and harder to read. This rule detects if you
define
member functions in the class definition.
See also: CODSTA-CPP-32

BENEFITS
This rule ensure better data hiding by separating interface and
implementation.

EXAMPLE
template <class T>
class A {
public:
void foo( ) {}
};

// Violation

REPAIR
template <class T>
class A {
public:
void foo( );
};
template <class T> void A<T>::foo( ) {}

REFERENCES
Recommended by ParaSoft

// OK

Avoid using static_cast on pointers [CODSTA-CPP-34-3]


DESCRIPTION
"Pointers to dynamic objects don't static_cast: Safe alternatives range
from using dynamic_cast to refactoring to redesigning. Consider replacing
uses of static_cast with its more powerful relative dynamic_cast, and then
you won't have to remember when static_cast is safe and when it's
dangerous."

BENEFITS
Rule improves safety and reliability of code.

EXAMPLE
class B {};
class D : public B {};
void foo( B* pb, D* pd ) {
B* pb2 = static_cast<B*>( pd );
}

// Violation

REPAIR
class B {};
class D : public B {};
void foo( B* pb, D* pd ) {
B* pb2 = dynamic_cast<B*>( pd );
}

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 93

2. ISO/DIS 26262
point 8.4.4

Avoid dynamic_casts [CODSTA-CPP-35-3]


DESCRIPTION
"This example also demonstrates that if you find yourself wanting to cast,
it's a sign that you could be approaching things the wrong way. This is
especially the case if your want is for dynamic_cast. Avoid casts whenever
practical, especially dynamic_casts in performance-sensitive code."

SINCE
v7.0

NOTES
Rule disallows usage of dynamic_casts.

BENEFITS
"(...) Many implementations of dynamic_cast can be quite slow. For
example,
at least one common implementation is based in part on string comparisons
of class names. If you're performing a dynamic_cast on an object in
a single-inheritance hierarchy four levels deep, each dynamic_cast under
such an implementation could cost you up to four calls to strcmp to
compare
class names."

EXAMPLE
#include <vector>
#include <boost/tr1/memory.hpp>
using namespace std;
class Window {
virtual void onResize( );
};
class SpecialWindow : public Window {

public:
virtual void onResize( );
void blink( );
};
void foo( )
{
typedef vector<std::tr1::shared_ptr<Window> > VPW;
VPW winPtrs;
for (VPW::iterator iter = winPtrs.begin( ); iter != winPtrs.end( );
++iter)
{
if (SpecialWindow *psw =
dynamic_cast<SpecialWindow*>( iter->get( ) ))
//
Violation
psw->blink( );
}
}

REPAIR
#include <vector>
#include <boost/tr1/memory.hpp>
using namespace std;
class Window {
virtual void onResize( );
};
class SpecialWindow : public Window {
public:
virtual void onResize( );
void blink( );
};
void foo( ) {
typedef std::vector<std::tr1::shared_ptr<SpecialWindow> > VPSW;
VPSW winPtrs;
for (VPSW::iterator iter =
winPtrs.begin( ); iter != winPtrs.end( );++iter)
(*iter)->blink( );

// OK
}

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 27

Avoid using global variables, global functions, and class in file outside namespaces
[CODSTA-CPP-36-3]
DESCRIPTION
This rule detects the use of global variables, classes,
and global functions outside of namespaces.

BENEFITS
Prevents the use of global variables, classes, and global functions
outside namespaces. All data and functions in a file should be inside
one or more namespaces.

EXAMPLE
int var = 0;

// Violation

void globalfoo( ) { // Violation


}
class A {
int i;
void foo( );
};

// Violation

REPAIR
namespace name1 {
int var = 0;

// OK

void globalfoo( ) { // OK
}
class A {
int i;
void foo();
};
}

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.11 Namespaces, AV Rule 98
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-3-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
4. ISO/DIS 26262
point 8.4.4

Do not define class/struct/union inside function implementation [CODSTA-CPP-37-3]


DESCRIPTION
Do not define class/struct/union inside function implementation.

BENEFITS
If you define a struct/class in a function (as opposed
to declaring it), then it becomes a local type, which
- cannot be reused by the compiler
- can result in non-compatible definitions for the same declared type.

EXAMPLE
void foo(){
class A { // Violation
// ...
};
// ...
}

REPAIR
class A { // OK
// ...
};
void foo(){
// ...
}

REFERENCES
Recommended by ParaSoft

Conversion operator, operator->, operator(), operator[] should be const [CODSTA-CPP-38-3]


DESCRIPTION
Conversion operator, operator->, operator(), operator[] should be const.
See also: CODSTA-CPP-03, CODSTA-CPP-43, CODSTA-CPP-44,
MISRA-104, MISRA2004-16_7, OPT-21

BENEFITS
C++ powerful const property should be enforced as appropriate,
to provide additional checks on the correct behavior of the code.
The semantics of operators "()", "[]", "->", and cast operators
presumes that they do not change the internals of the object they
are called on. Therefore, it is a good practice to declare them const.

EXAMPLE
class A
{
public:
A& operator()( int x ); // Violation
A& operator[]( int x ); // Violation
A& operator->( );
// Violation
operator int( );
// Violation
};

REPAIR
class A
{
public:
A& operator()( int x ) const;
A& operator[]( int x ) const;
A& operator->( ) const;
operator int( ) const;
};

REFERENCES

//
//
//
//

OK
OK
OK
OK

Scott Meyers, "Effective C++: 55 Specific Ways to Improve


Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3

Don't write namespace usings in a header file or before an #include [CODSTA-CPP-39-3]


DESCRIPTION
"Namespace usings are for your convenience, not for you to inflict on
others:
Never write a using declaration or a using directive before #include
directive. In header files, don't write namespace-level using directives
or using declarations; instead, explicitly namespace-qualify all names.
The second rule follows from the first, because headers can never know
what other header #includes might appear after them."

EXCEPTIONS
This rule doesn't apply to writing class member using declarations to
bring
in base class member names as needed.

BENEFITS
Prevents writing usings directives in header files which are meant
to be included in an unbounded number of implementation files.
Rule also prevents messing with the meaning of code in someone else's
header.

EXAMPLE
// file1.cpp
#include <stdio.h>
using namespace std;
#include <stddef.h>
// file.h
#include <stdio.h>
using namespace std;
// file2.cpp
#include "file.h"
#include <stddef.h>

// Violation

// Violation

REPAIR
// file.cpp
#include <stdio.h>
#include <stddef.h>
using namespace std;

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 59
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Limiting the number of objects of a class [CODSTA-CPP-40-5]


DESCRIPTION
This rule detects the need to limit the number of objects in a class.

BENEFITS
Limiting the number of objects in a class can reduce code complexity.

EXAMPLE
class Base {
// Violation
public:
class X {}; // exception definition
Base( ) {
// limit missing
// constructor stuff here
++numObjects;
}
~Base( ) {
--numObjects;
// destructor stuff here
}
private:
static int numObjects;
};

REPAIR
class Base {
// OK
public:
class X {}; // exception definition
Base( ) {
if (numObjects >= 1) throw X( );
// constructor stuff here
++numObjects;
}
~Base( ) {
--numObjects;
// destructor stuff here

}
private:
static int numObjects;
};

REFERENCES
Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Techniques", Item 26

Do not use the 'enum' keyword to declare a variable in C++ [CODSTA-CPP-41-3]


DESCRIPTION
This rule checks whether your C++ code uses enum keywords to declare
variables.
'enum' keyword is unnecessary in C++ when declaring a variable.
This rule applies only to the C++ programming language.

BENEFITS
Readability.

EXAMPLE
enum Colors { RED, BLUE, GREEN };
enum Colors c;
// Violation

REPAIR
enum Colors { RED, BLUE, GREEN };
Colors c;
// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not declare member variables with the 'mutable' keyword [CODSTA-CPP-42-3]


DESCRIPTION
This rule checks if you declare member variables with the 'mutable'
keyword.
This rule applies only to the C++ programming language.

BENEFITS
Prevents using the keyword `mutable'.

EXAMPLE
class Date{
public:
int getMonth( ) const;
private:
mutable int month;
// Violation
int year;
int day;
};
int Date::getMonth( ) const {
month++;
return month;
}

REPAIR
Do not declare member variables with the 'mutable' keyword

REFERENCES
Recommended by ParaSoft

Declare reference parameters as const references whenever possible [CODSTA-CPP-43-3]


DESCRIPTION
This rule checks if you declared your reference parameters as const
references.
When your function is not going to modify the argument it is referencing,
you
should use const to protect variables from unintended modifications when
the
function returns.
See also: CODSTA-CPP-03, CODSTA-CPP-38, CODSTA-CPP-44,
MISRA-104, MISRA2004-16_7, OPT-21

NOTES
The rule does not report violations on virtual functions.

BENEFITS
Declaring parameters which are not modified as const reference instead of
reference improves legibility. It also prevents future revisions from
unintentional changing the caller's data.

EXAMPLE
struct Foo {
int x;
int y;
};
int Bar( Foo &f ) {
return f.x;
}

// Violation

int FooBar( Foo &f ) { // OK


return f.x++;
}

REPAIR
struct Foo {
int x;
int y;
};
int Bar( const Foo &f ) {
return f.x;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Have the non-const version call the const version of member function instead of duplicating
the const version definition [CODSTA-CPP-44-3]
DESCRIPTION
"When const and non-const member functions have essentially identical
implementations, code duplication can be avoided by having the non-const
version call the const version."
See also: CODSTA-CPP-03, CODSTA-CPP-38, CODSTA-CPP-43,
MISRA-104, MISRA2004-16_7, OPT-21

SINCE
v7.0

BENEFITS
"Decrease compilation time, maintenance, and code-bloat headaches."

EXAMPLE
#include <iostream>
#include <string.h>
using namespace std;
class TextBlock {
public:
const char& operator[]( size_t position ) const
// do bounds checking
// log access data
// verify data integrity
return text[ position ];
}
char& operator[]( size_t position ) {
// do bounds checking
// log access data
// verify data integrity
return text[ position ];
}
private:

{ // OK

// Violation

string text;
};

REPAIR
#include <iostream>
#include <string.h>
using namespace std;
class TextBlock {
public:
const char& operator[]( size_t position ) const { // OK
// some code
return text[ position ];
}
char& operator[]( size_t position ) {
// OK
return const_cast<char&>(
static_cast<const TextBlock&>(*this)[ position ] );
}
private:
string text;
};

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3

In the private section of a class items shall be declared in the following order: Constructors,
Destructor, Member Functions, Member Operator Function, Enumerations and others
[CODSTA-CPP-45-3]
DESCRIPTION
Following the above ordering convention makes it easier for those
unfamiliar
with a class to figure out its functionality.
See also: CODSTA-CPP-46, CODSTA-CPP-47, CODSTA-CPP-48, CODSTA-CPP-49

BENEFITS
Rule makes source code more readable.

EXAMPLE
class A
// Violation
{
private:
A( );
int foo( );
~A( );
};

REPAIR
class A
// OK
{
private:
A( );
~A( );
int foo( );
};

REFERENCES
Recommended by ParaSoft

Order of scopes in class: public before all others [CODSTA-CPP-46-3]


DESCRIPTION
Public section must be before protected and private sections.
See also: CODSTA-CPP-45, CODSTA-CPP-47, CODSTA-CPP-48, CODSTA-CPP-49

BENEFITS
Readability and maintainability.

EXAMPLE
class Test {
protected:
void foo2(
private:
void foo3(
public:
void foo1(
};

// Violation
);
);
);

REPAIR
class Test {
public:
void foo1(
protected:
void foo2(
private:
void foo3(
};

// OK
);
);
);

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.9 Style, AV Rule 57

Order of scopes in classes: protected before private [CODSTA-CPP-47-3]


DESCRIPTION
Protected section must be before private section.
See also: CODSTA-CPP-45, CODSTA-CPP-46, CODSTA-CPP-48, CODSTA-CPP-49

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class Test {// Violation
public:
void foo1( );
private:
void foo3( );
protected:
void foo2( );
};

REPAIR
class Test {// OK
public:
void foo1( );
protected:
void foo2( );
private:
void foo3( );
};

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.9 Style, AV Rule 57

In the protected section of a class items shall be declared in the following order:
Constructors, Destructor, Member Functions, Member Operator Function, Enumerations and
others [CODSTA-CPP-48-3]
DESCRIPTION
Following the above ordering convention makes it easier for those
unfamiliar
with a class to figure out its functionality.
See also: CODSTA-CPP-45, CODSTA-CPP-46, CODSTA-CPP-47, CODSTA-CPP-49

BENEFITS
Rule makes source code more readable.

EXAMPLE
class A
// Violation
{
protected:
A( );
int foo( );
~A( );
};

REPAIR
class A
// OK
{
protected:
A( );
~A( );
int foo( );
};

REFERENCES
Recommended by ParaSoft

In the public section of a class items shall be declared in the following order: Constructors,
Destructor, Member Functions, Member Operator Function, Enumerations and others
[CODSTA-CPP-49-3]
DESCRIPTION
Following the above ordering convention makes it easier for those
unfamiliar
with a class to figure out its functionality.
See also: CODSTA-CPP-45, CODSTA-CPP-46, CODSTA-CPP-47, CODSTA-CPP-48

BENEFITS
Readability.

EXAMPLE
class A { // Violation
public:
A( );
int foo( );
~A( );
};

REPAIR
class A { // OK
public:
A( );
~A( );
int foo( );
};

REFERENCES
Recommended by ParaSoft

Do not use static keyword except inside functions and classes [CODSTA-CPP-50-3]
DESCRIPTION
Do not use static keyword except inside functions and classes (C++ only).
Note that static keyword is perfectly legal in C files at the file scope.
"By deprecating a feature, the standards committee expresses the wish that
the feature would go away. However, the committee does not have a mandate
to
remove a heavily used feature however redundant or dangerous it may be.
Thus, a deprecation is a strong hint to the users to avoid the feature.
The keyword s t a t i c , which usually means statically allocated,
can be
used to indicate that a function or an object is local to a translation
unit.
For example:
// file1:
static int glob ;
// file2:
static int glob ;
This program genuinely has two integers called g l o b . Each g l o b is
used
exclusively by functions defined in its translation unit. The use of
static to
indicate "local to translation unit" is deprecated in C++. Use unnamed
namespaces instead."

SINCE
v7.0

BENEFITS
Rule prevents using deprecated language structures.

EXAMPLE
static int glob;

// Violation

static int goo( );


namespace N {
static int c;
}
static struct S {
int a;
static int b;
} S_var;

// Violation

// Violation

// Violation
// Violation

REPAIR
namespace{
static int glob;
}

// OK

class A {
static void foo( ); // OK
};
void zoo( ) {
static int c;
}
class B {
public:
static struct S {
int a;
static int b;
} S_var;
};

// OK

// OK
// OK

REFERENCES
1. Stroustroup C++ Programming Language 3rd Edition. 9.2, p200.
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not define inline functions in source files [CODSTA-CPP-51-3]


DESCRIPTION
Do not define inline functions in source files - inline functions
must be defined identically in every translation unit they are used.
Therefore, inline functions should be defined only in the header
or .i files.

SINCE
v7.0

EXCEPTIONS
Static inline functions and inline functions defined in anonymous
namespace
are permitted.

BENEFITS
Rule helps to prevent unpredictable behaviour of program.

EXAMPLE
inline int foo( ) {
return 10;
}
class LocalClass {
public:
int bar( ) {
return 20;
}
};

// Violation

// Violation

int test( ) {
LocalClass lc;
return foo() + lc.bar();
}

REPAIR
static inline int foo( ) {
return 10;
}
namespace {
class LocalClass {
public:
int bar( ) {
return 20;
}
};
}

// OK

// OK

int test( ) {
LocalClass lc;
return foo() + lc.bar();
}

REFERENCES
1. Stroustroup C++ Programming Language 3rd Edition. 9.2, p199.
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Consider using the natural relationship between the assignment version of an operator and
the stand-alone version [CODSTA-CPP-52-3]
DESCRIPTION
"A good way to ensure that the natural relationship between the assignment
version of an operator (e.g., operator+=) and the stand-alone version
(e.g., operator+) exists is to implement the latter in terms of the
former.
For example:"
class Rational {
public:
Rational& operator+=(const Rational& rhs);
};
const Rational operator+(const Rational& lhs,
const Rational& rhs)
{
return Rational(lhs) += rhs;
}

SINCE
v7.0

BENEFITS
"In this example, operators += is implemented (elsewhere) from scratch,
and
operator+ calls them to provide their own functionality. With this design,
only
the assignment version of these operator need to be maintained.
Furthermore,
assuming the assignment versions of the operators are in the class's
public
interface, there is never a need for the stand-alone operators to be
friends
of the class."
See also: OOP-11, CODSTA-CPP-29

EXAMPLE
class A {
public:
A operator+=( A& b );
A operator-=( A& b );
A operator*=( A& b );
friend A operator*( A& a, A& b );
};

// Violation

A operator+( A& a, A& b ){


return A( a );
}

// Violation

A operator-( A& a, A& b ){


return A( a );
}

// Violation

A operator*( A& a, A& b ){


return A( a ) *= b;
}

// OK

REPAIR
class A {
public:
A operator+=( A& b );
A operator-=( A& b );
A operator*=( A& b );
// OK - removed friend declaration
};
A operator+( A& a, A& b ){
return A( a ) += b;
}

// OK

A operator-( A& a, A& b ){


A result( a );
return result -= b;
}

// OK

A operator*( A& a, A& b ){

// OK

return A( a ) *= b;
}

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 22
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declare parameters or local variable as const whenever possible [CODSTA-CPP-53-3]


DESCRIPTION
This rule checks if you declared your parameters or local variables as
const.
Immutable values are easier to understand, track, and reason about, so
prefer
constants over variables whenever it is sensible and make const your
default
choice when you define a value.
See also: CODSTA-CPP-43, MISRA2004-16_7

SINCE
v7.0

NOTES
For parameters and variables of pointer type the const qualifier
should be applied to the pointer, not to the pointed object.

BENEFITS
It's safe, it's checked at compile time, and it's integrated
with C++'s type system. It also prevents future revisions
from unintentional changing the caller's data.

EXAMPLE
int foo1(int param1,
int* param2,
const int* param3)

// Violation
// Violation
// Violation - const is applied to the
// pointed object, not to the pointer

{
int var1 = 0;
// Violation
return param1 + *param2 + *param3 + var1;
}
int foo2(int param1,

// OK - param1 is modified

int* param2,
const int* param3)

// OK - param2 is modified
// OK - param3 is modified

{
int var1 = 0;
// OK - var1 is modified
param1++;
param2++;
param3++;
var1 = param1 + *param2 + *param3;
return var1;
}

REPAIR
// Fixed violations - const added
int foo1(const int param1,
int* const param2,
const int* const param3)

// OK
// OK - const is applied to the pointer
// OK - const is applied to the pointed
// object and to the pointer

{
const int var1 = 0;
// OK
return param1 + *param2 + *param3 + var1;
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc., Chapter: "Coding Style", Rule 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Member functions shall be declared const whenever possible [CODSTA-CPP-54-3]


DESCRIPTION
"Const-correctness is worthwhile, proven, effective, and highly
recommended.
Understanding how and where a program's state changes is vital, and const
documents that directly in code where the compiler can help to enforce it.
If you find it impossible to make a member function const, you usually
gain
a better understanding of the ways in which that member function might
modify
an object's state."
See also: CODSTA-CPP-78

SINCE
v7.1

BENEFITS
"Writing const appropriately helps you gain a better understanding of your
design and makes your code sturdier and safer."

EXAMPLE
class A
{
int foo(int a)
{
return a;
}
};

// Violation

REPAIR
class A
{
int foo(int a) const
{

// OK

return a;
}
};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 15
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 69
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Arrays shall not be used in interfaces [CODSTA-CPP-55-2]


DESCRIPTION
Array parameters should not be used in public methods.
Instead, the Array class should be used.

SINCE
v7.1

NOTES
Rule defines an interface as a public method.

BENEFITS
Arrays degenerate to pointers when passed as parameters.
This "array decay" problem has long been known to be a source of errors.

EXAMPLE
class Sample
{
public:
void foo(int a[]); // Violation
};

REPAIR
class Array
{
/* Array implementation*/
};

class Sample
{
public:

void goo(Array a); // OK


};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 97

A class, structure, or enumeration will not be declared in the definition of its type [CODSTACPP-56-3]
DESCRIPTION
A class, structure, or enumeration will not be declared in the definition
of its type.

SINCE
v7.1

BENEFITS
Rule improves readability.

EXAMPLE
enum
{
up,
down
} direction;

// Violation

REPAIR
enum direction_e
{
up,
down
};
direction_e direction; // OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 141

Namespaces will not be nested more than two levels deep [CODSTA-CPP-57-3]
DESCRIPTION
Namespaces will not be nested more than two levels deep.

SINCE
v7.1

BENEFITS
Simplicity and clarity.
Deeply nested namespaces can be difficult to comprehend and use correctly.

EXAMPLE
namespace A
{
namespace B
{
namespace C
{
namespace D // Violation
{
}
}
}
}

REPAIR
namespace A
{
namespace B
{
namespace C // OK
{
}
namespace D // OK

{
}
}
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.11 Namespaces, AV Rule 99

The value returned by a function having a non-void return type that is not an overloaded
operator shall always be used [CODSTA-CPP-58-3]
DESCRIPTION
"In C++ it is possible to call a function without using the return value,
which may be an error. The return value of a function shall always be
used."

SINCE
v7.2

EXCEPTIONS
"The return value of a function may be discarded by use of a (void) cast.
Overloaded operators are excluded, as they should behave in the same way
as built-in operators."

BENEFITS
Rule improves readability of code

EXAMPLE
short func ( short para1 )
{
return para1;
}
void discarded ( short para2 )
{
func ( para2 );
// Violation
}

REPAIR
short func ( short para1 )
{

return para1;
}
void discarded ( short para2 )
{
(void)func ( para2 );
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-7

The C library shall not be used [CODSTA-CPP-59-3]


DESCRIPTION
"Some C++ libraries (e.g. <cstdio>) also have corresponding C versions
(e.g. <stdio.h>). This rule requires that the C++ version is used."
The following standard C library headers are detected:
<assert.h>
<ctype.h>
<errno.h>
<float.h>
<iso646.h>
<limits.h>
<locale.h>
<math.h>
<setjmp.h>
<signal.h>
<stdarg.h>
<stddef.h>
<stdio.h>
<stdlib.h>
<string.h>
<time.h>
<wchar.h>
<wctype.h>

SINCE
v7.2

BENEFITS
Rule prevents undefined and implementation-defined behaviour.

EXAMPLE
#include <stdio.h> // Violation

REPAIR

#include <cstdio>

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Only those escape sequences that are defined in ISO/IEC 14882:2003 shall be used [CODSTACPP-60-3]
DESCRIPTION
"Only those escape sequences that are defined in ISO/IEC 14882:2003
shall be used. The defined escape sequences (ISO/IEC 14882:2003) are:
\n, \t, \v, \b, \r, \f, \a, \\, \?, \', \", \<Octal Number>,
\x<Hexadecimal Number>"

SINCE
v7.2

BENEFITS
The use of an undefined escape sequence leads to undefined behaviour.

EXAMPLE
#include <stdio.h>
void foo( ) {
printf("ABCD\u1111");
printf("abcd\hgf");
printf("\k");
}

// Violation
// Violation
// Violation

REPAIR
Do not use escape sequences not defined in the ISO/IEC 14882:2003
standard.

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-1
2. General Principles of Software Validation;

Final Guidance for Industry and FDA Staff


Document issued on: January 11, 2002

Objects or functions with external linkage shall be declared in a header file [CODSTA-CPP-613]
DESCRIPTION
"Placing the declarations of objects and functions with external linkage
in a header file documents that they are intended to be accessible from
other
translation units. If external linkage is not required, then the object or
function shall either be declared in an unnamed namespace or declared
static."

SINCE
v7.2

EXCEPTIONS
This rule does not apply to main, or to members of unnamed namespaces.

BENEFITS
Rule reduce the visibility of objects and functions.

EXAMPLE
// file.cpp
int a1 = 0;
void fun(){}

// Violation
// Violation

REPAIR
// file.h
extern int a1;
extern void fun();
// file.cpp
#include "file.h"
int a1 = 0;
// OK

// OK
// OK

void fun(){}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-3-1

NULL shall not be used as an integer value [CODSTA-CPP-62-3]


DESCRIPTION
"In C++, the literal 0 is both an integer type and the null-pointerconstant.
To meet developer expectations, NULL should be used as the
null-pointer-constant, and 0 for the integer zero."

SINCE
v7.2

BENEFITS
"As a result of this rule, NULL is considered to have pointer type."

EXAMPLE
#include <cstddef>
void f1( int );
void foo( )
{
f1( NULL ); // Violation
}

REPAIR
void f1( int );
void foo( )
{
f1( 0 ); // OK
}

REFERENCES

1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Literal zero (0) shall not be used as the null-pointer-constant [CODSTA-CPP-63-3]


DESCRIPTION
"In C++, the literal 0 is both an integer type and the null-pointerconstant.
To meet developer expectations, NULL should be used as the
null-pointer-constant, and 0 for the integer zero."

SINCE
v7.2

BENEFITS
"As a result of this rule, NULL is considered to have pointer type."

EXAMPLE
#include <cstddef>
void f1( int* );
void foo( )
{
f1( 0 ); // Violation
}

REPAIR
#include <cstddef>
void f1( int* );
void foo( )
{
f1( NULL ); // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-2

The condition of an if-statement and the condition of an iteration-statement shall have type
bool [CODSTA-CPP-64-3]
DESCRIPTION
"If an expression with type other than bool is used in the condition
of an if-statement or iteration statement, then its result will be
implicitly converted to bool."

SINCE
v7.2

NOTES
Rule does not report violations if the condition expression is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.

EXCEPTIONS
"A condition of the form type-specifier-seq declarator is not required
to have type bool."

BENEFITS
"The condition expression shall contain an explicit test (yielding a
result
of type bool) in order to clarify the intentions of the developer."

EXAMPLE
void foo()
{
int i;
if (i){} // Violation
}

REPAIR
void foo()
{
int i;
if (i != 0){} // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-13

The first operand of a conditional-operator shall have type bool [CODSTA-CPP-65-1]


DESCRIPTION
"The first operand of a conditional-operator shall have type bool.
If an expression with type other than bool is used as the first operand
of a conditional-operator, then its result will be implicitly converted
to bool."

SINCE
v7.2

BENEFITS
"The first operand shall contain an explicit test (yielding a result of
type
bool) in order to clarify the intentions of the developer."

EXAMPLE
void foo(int i, int j, int k, int l)
{
i = j ? k : l;
// Violation
}

REPAIR
void foo(int i, int j, int k, int l)
{
i = (j != 0) ? k : l;
// OK
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-14

2. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

C-style casts (other than void casts) and functional notation casts (other than explicit
constructor calls) shall not be used [CODSTA-CPP-66-3]
DESCRIPTION
"C-style (cast notation), and functional notation casts that do not invoke
a converting constructor are capable of performing casts between unrelated
types."

SINCE
v7.2

EXCEPTIONS
"A C-style cast to void may be used to signify that the return value
for a non-void function call is being ignored"

BENEFITS
C++ casts are more specific than C casts and are much easier to locate
and read.

EXAMPLE
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD2 = (Derived *) pB;

// Violation

REPAIR
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD1 = dynamic_cast<Derived*>( pB );
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-4

Each operand of the ! operator, the logical && or the logical || operators shall have type bool
[CODSTA-CPP-67-3]
DESCRIPTION
"The use of operands with types other than bool with these operators is
unlikely to be meaningful (or intended). This rule allows the detection of
such uses, which often occur because the logical operators (&&, || and !)
can be easily confused with the bitwise operators (&, | and ~)."

SINCE
v7.2

NOTES
Rule does not report violations if the operand is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.

BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.

EXAMPLE
/* examples of incorrect code */
void foo(int a, int b, int c, int d, int* ptr)
{
if ( 1 && ( c < d ) ) {}
// Violation
if ( ( a < b ) && ( c + d ) ){} // Violation
if ( a || ( c + d ) ) {}
// Violation
if ( !ptr ) {}
// Violation
}

REPAIR
/* examples of correct code */

void foo(int a, int b, int c, int d)


{
if ( ( a < b ) && ( c < d ) ){}
// OK
if ( ( a == b ) || ( c != d ) ){} // OK
if ( !false ) {}
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-1

The unary & operator shall not be overloaded [CODSTA-CPP-68-3]


DESCRIPTION
"Taking the address of an object of incomplete type where the complete
type
contains a user declared operator & leads to undefined behaviour"

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
class A
{
public:
A * operator & ( );
};

// Violation

REPAIR
Do not overload the unary '&' operator

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-3

A for loop shall contain a single loop-counter which shall not have floating type [CODSTACPP-69-3]
DESCRIPTION
"A for loop without exactly one loop-counter is simply a while loop.
If this is the desired behaviour, then a while loop is more appropriate."

SINCE
v7.2

NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.

BENEFITS
Rule helps to ensure deterministic loop termination.

EXAMPLE
void foo()
{
int x = 0;
int y;
y = 0;
for (x = 0; x < y; x = y++){} // Violation
}

REPAIR
void foo3()
{

int x = 0;
int y;
y = 0;
x = 0;
while(x < y) // OK
{
x = y++;
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-1

If loop-counter is not modified by -- or ++, then, within condition, the loop-counter shall only
be used as an operand to <=, <, > or >= [CODSTA-CPP-70-3]
DESCRIPTION
"When the loop-counter is modified using an operator other than -- or ++,
then == and != shall not be used, as loop termination may not occur,
which may be inconsistent with developer expectations."

SINCE
v7.2

NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.

BENEFITS
Rule helps to ensure deterministic loop termination.

EXAMPLE
void foo()
{
int i;
for ( i = 1; i != 10; i += 2 ){} // Violation
}

REPAIR
void foo()
{
int i;

for ( i = 1; i <= 10; i += 2 ){} // OK


for ( i = 1; i != 10; ++i ){}
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-2

The loop-counter shall be modified by one of: --, ++, -=n, or +=n; where n remains constant for
the duration of the loop [CODSTA-CPP-71-3]
DESCRIPTION
"The loop-counter shall be modified by one of: --, ++, -=n, or +=n;
where n remains constant for the duration of the loop"

SINCE
v7.2

NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.

BENEFITS
Rule helps to ensure deterministic loop termination.

EXAMPLE
void foo()
{
int x;
for ( x = 0; x < 10; x = x + 1 ){} // Violation
}

REPAIR
void foo()
{
int x;
for ( x = 0; x < 10; ++x ){} // OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-4

A loop-control-variable other than the loop-counter shall not be modified within condition or
expression [CODSTA-CPP-72-3]
DESCRIPTION
"A loop-control-variable other than the loop-counter shall
not be modified within condition or expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
loop-control-variables are either the loop-counter, or flags used for
early
loop termination. The code is easier to understand if these are not
modified
within condition or expression."

SINCE
v7.2

NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.

BENEFITS
Rule improves readability of code.

EXAMPLE
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; flag = test(++x) ) {}
}

// Violation

REPAIR
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; ++x ) // OK
{
flag = test(x);
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-5

A loop-control-variable other than the loop-counter which is modified in statement shall have
type bool [CODSTA-CPP-73-3]
DESCRIPTION
"A loop-control-variable other than the loop-counter which is modified
in statement shall have type bool.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
loop-control-variables are typically used to terminate a for loop early.
The code is easier to understand if this is done with the use
of Boolean values"

SINCE
v7.2

NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && ( u8a != 3U ); ++x )
{
u8a = 5;
// Violation
}
}

REPAIR
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && flag; ++x )
{
u8a = 5;
// OK
flag = u8a != 3U;
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-6

There shall be no unnamed namespaces in header files [CODSTA-CPP-74-3]


DESCRIPTION
"An unnamed namespace will be unique within each translation unit.
Any declarations appearing in an unnamed namespace in a header will refer
to different entities in each translation unit, which may not be
consistent
with developer expectations."

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
// file.hpp
namespace // Violation
{
extern int x;
}

REPAIR
Do not define unnamed namespaces in header files

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

using-directives shall not be used [CODSTA-CPP-75-3]


DESCRIPTION
"using-directives add additional scopes to the set of scopes searched
during
name lookup. All identifiers in these scopes become visible, increasing
the
possibility that the identifier found by the compiler does not meet
developer
expectations.
using-declarations or fully qualified names restricts the set of names
considered to only the name explicitly specified, and so are safer
options."

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using namespace NS1; // Violation
void f ()
{
++j1;
}

REPAIR
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using NS1::j1;
// OK
void f ()
{
++j1;
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-4

Multiple declarations for an identifier in the same namespace shall not straddle a usingdeclaration for that identifier [CODSTA-CPP-76-3]
DESCRIPTION
"The set of identifiers introduced by a using-declaration does not include
any
declarations that may be added by a subsequent declaration in the
namespace.
Any subsequent declarations will not be found through the usingdeclaration,
which may not be consistent with developer expectations."

SINCE
v7.2

BENEFITS
Rule prevents unexpected behaviour.

EXAMPLE
namespace NS
{
void foo( unsigned short );
}
using NS::foo;
namespace NS
{
void foo( unsigned int );
}
void some()
{
foo( 0U );
}

// Violation

REPAIR
namespace NS
{
void foo( unsigned short );
}
namespace NS
{
void foo( unsigned int );
}

// OK

using NS::foo;
void some()
{
foo( 0U );
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-5

Const member functions shall not return non-const pointers or references to class-data
[CODSTA-CPP-77-3]
DESCRIPTION
"When an object is declared with const class type, only const member
functions
can be invoked on that object. The common expectation of const member
functions
is that the state of the object may not be modified when invoking the
functions. However, returning a non-const pointer or reference to classdata
from a const function allows a modification to the conceptual state of an
object."
See also: CODSTA-CPP-06, OOP-12, OOP-36

NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.

BENEFITS
Rule prevents exposing internal state of the object to clients, so they
won't
uncontrollably modify the state of the object. Enforces data encapsulation
that
is a cornerstone of Object Oriented programming. Improves code
maintainability.
Helps const functions act const.

EXAMPLE
class Test
{
public:
Test(int & p) : _i(p)

{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1() const
{
return &_i; // Violation
}
protected:
int& GetI2() const
{
return _i; // Violation
}
int * GetI3() const
{
return _k; // Violation
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
GetI2() = 0; // Modification of possibly-const object
*(GetI3()) = 0; // Modification of possibly-const object
}
private:
int z;
};
void bar()
{
const Child c;
*(c.GetI1()) = 0; // Modification of possibly-const object
}

REPAIR
class Test

{
public:
Test(int & p) : _i(p)
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1() const
{
return &_i; // OK
}
protected:
const int& GetI2() const
{
return _i; // OK
}
const int * GetI3() const
{
return _k; // OK
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
// GetI2() = 0; // Not compilable - can't modify const object
// *(GetI3()) = 0; // Not compilable - can't modify const
object
}
private:
int z;
};
void bar()
{
const Child c;
// *(c.GetI1()) = 0; // Not compilable - can't modify const object
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 9-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

If a member function can be made static then it shall be made static, otherwise if it can be
made const then it shall be made const [CODSTA-CPP-78-3]
DESCRIPTION
"Declaring a member function static or const limits its access
to the non-static data members."
See also: CODSTA-CPP-54

SINCE
v7.2

BENEFITS
Rule prevents unintentional modification of the data.

EXAMPLE
class A
{
public:
int foo1 ()
{
return m_s;
}
int foo2 ()
{
return m_i;
}
private:
int m_i;
static int m_s;
};

REPAIR
class A
{

// Violation - can be static

// Violation - can be const

public:
static int foo1 ()
{
return m_s;
}
int foo2 () const
{
return m_i;
}

// OK

// OK

private:
int m_i;
static int m_s;
};

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Array elements shall be accessed by the array operator [ ] [CODSTA-01-3]


DESCRIPTION
This rule checks whether array elements are accessed by the array operator
[].

BENEFITS
Array elements shall be accessed by the array operator [] rather than
the dereference operator '*'. Access to array by the dereference operator
'*' is cryptic and hides the real intention.

EXAMPLE
void foo()
{
int array[2];
*(array+1) = 0; // Violation
*array = 0;
// Violation
}

REPAIR
void foo()
{
int array[2];
array[1] = 0; // OK
}

REFERENCES
Motorola Coding Standards R-46

Do not declare member variables as bit-fields [CODSTA-02-5]


DESCRIPTION
This rule is purely informational.
It will report a message when a bitfield is declared.

BENEFITS
Prevents error prone code.
The ordering of bits in memory varies from compiler to
compiler. In addition, many popular compilers generate
inefficient code for reading and writing bit members,
and there are potentially severe thread safety issues
relating to bit fields (especially on multiprocessor
systems) due to the fact that most machines cannot
manipulate arbitrary sets of bits in memory, but must
instead load and store whole words.

EXAMPLE
struct A
{
int iVarBitField : 8;
int iVar;
};

REPAIR
Do not declare bitfield.

REFERENCES
Recommended by Parasoft

// Violation

Do not define constants via #define [CODSTA-03-3]


DESCRIPTION
"Constants are to be defined using const or enum; never using #define. The
preprocessor performs a textual substitution for macros in the source code
which is then compiled. This has a number of negative consequences. For
example, if a constant has been defined using #define, the name of the
constant is not recognized in many debuggers. If the constant is
represented
by an expression, this expression may be evaluated differently for
different
instantiations, depending on the scope of the name. In addition, macros
are,
at times, incorrectly written."
See also: MISRA2004-19_7, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40

BENEFITS
Code is easier to debug. Prevents incorrectly macro writing.

EXAMPLE
#define PI 3.1416

// Violation

REPAIR
const float PI = 3.1416; // OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 10 Constants - Rule 36

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.6 Pre-Processing Directives, AV Rule 30

Do not declare local variables with the 'static' keyword [CODSTA-04-5]


DESCRIPTION
This rule is purely informational and will report a message when a
variable
declaration is found with the 'static' keyword.

BENEFITS
Makes code more readable.

EXAMPLE
void Foo()
{
int static iVar = 9; // Violation
return;
}

REPAIR
int iVar = 9; // OK
void Foo()
{
iVar++;
return;
}

REFERENCES
Recommended by ParaSoft

Pointers to pointers should be avoided whenever possible [CODSTA-05-3]


DESCRIPTION
This rule detects if code uses pointers to pointers.
"Pointers to pointers should whenever possible be avoided.
By improving the readability of code, the probability of failure is
reduced."

EXCEPTIONS
"One exception to this rule is represented by functions which provide
interfaces to other languages (such as C). These are likely to only allow
pre-defined data types to be used as arguments in the interface, in which
case pointers to pointers are needed. Another example is the second
argument
to the main function, which must have the type char*[]."

BENEFITS
Rule improves the readability of the code and encourages data abstraction.

EXAMPLE
void foo() {
int** a; // Violation
}

REPAIR
Instead, declare a class that has
a member variable of the pointer type.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#12
From: 12 Pointers and References - Rec. 48

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.22 Pointers & References, AV Rule 169
3. ISO/DIS 26262
point 8.4.4

Avoid using the '?:' operator [CODSTA-06-3]


DESCRIPTION
This rule detects if you use the '?:' operator.

BENEFITS
Readability. The '?:' operator is difficult to read
and leads to code obfuscation.

EXAMPLE
int main( )
{
return (1 ? 1 : 0); // Violation
};

REPAIR
int main( )
{
if (1)
return 1;
else
return 0;
};

// OK

REFERENCES
Recommended by ParaSoft

If a function has no parameters, use ( ) instead of ( void ) [CODSTA-07-3]


DESCRIPTION
This rule detects if you use (void) instead of () if a function
has no parameters. Maintaining this consistency of declarations
results in easier code readability.

NOTES
The rule is enabled only for C++ language.

BENEFITS
The rule improves readability of code.

EXAMPLE
typedef void (*fpt)(void);
typedef void TD_void;
void f1(void);
void f1(void){
}

// Violation

// Violation
// Violation

void foo2(TD_void); // Violation


void (*fp1)(void);

// Violation

REPAIR
typedef void (*fpt)();
typedef void TD_void;
void f1();
void f1(){
}

// OK
// OK

TD_void foo2(); // OK

// OK

void (*fp1)();

// OK

REFERENCES
Recommended by ParaSoft

Do not use break in for loops [CODSTA-08-2]


DESCRIPTION
This rule checks if there are breaks in for loops. Breaks which
are in direct context of do/while, while and switch are skipped.

BENEFITS
Avoiding breaks in the for loop makes your code easier to follow.

EXAMPLE
void func()
{
for (int j = 0; j < 10; j++) {
if (j==5)
{
break;
// Violation
}
break;
// Violation
}
}

REPAIR
void func()
{
for (int j = 0; j < 10; j++) {
while (true)
{
break;
// OK - 'break' in while context
}
}
}

REFERENCES
Recommended by ParaSoft

Do not cast pointers to functions to pointers to primitive types [CODSTA-09-3]


DESCRIPTION
This rule detects if code casts pointers to functions to pointers
to primitive types. Using a pointer cast in this manner can cause
problems.

BENEFITS
Casting pointer to function to pointer to primitive
type can make code error prone.

EXAMPLE
void Foo(char *ptrC)
{
*ptrC = 0;
return;
}
void f()
{
void *ptrV = 0;
void (*funPtr) (char*) = 0;
funPtr = &Foo;
ptrV = (void*)funPtr;
return;
}

// Violation

REPAIR
Remove all function pointer to primitive type pointer casts.

REFERENCES
1. ISO/DIS 26262
point 8.4.4

Storage type modifiers shall be associated with the type, not the variable or the function
[CODSTA-10-3]
DESCRIPTION
This rule checks whether storage type modifiers
are associated with the type, not the variable.

BENEFITS
Improves the readability of code.

EXAMPLE
int static i; // Violation

REPAIR
static char j; // OK

REFERENCES
Motorola Coding Standards R-1

Assert liberally to document internal assumptions and invariants [CODSTA-11-5]


DESCRIPTION
This rule checks that code asserts liberally to document internal
assumptions and invariants.
"Use assert or an equivalent liberally to document assumptions internal
to a module. Never write expressions with side effects in assert
statement.
Avoid assert(false) and prefer assert(!"informational message").
Most compilers will helpfully emit the string in their error output."

BENEFITS
Rule improves efficiency and prevents error-prone code.

EXAMPLE
#include <assert.h>
void foo( ) {
int i = 0;
assert( i++ != 0 ); // Violation
assert(i=5);
// Violation
assert(false);
// Violation
}

REPAIR
#include <assert.h>
void foo( ) {
int i = 0;
assert(i != 0);
// OK
assert(!"informational message"); // OK
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.

Chapter: "Error Handling and Exceptions", Rule 68


2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions & References, AV Rule 204
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid using shift operations instead of arithmetic operations [CODSTA-12-3]


DESCRIPTION
This rule detects code that uses shift operations instead of arithmetic
operations. "Avoid using shift operations instead of arithmetic
operations."

BENEFITS
Rule improves readability and maintainability and prevents confusion.

EXAMPLE
void foo() {
int c = 8 << 2;
}

// Violation

REPAIR
Avoid using shift operations.

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.8
From: 18 Portable Code - 18.8 Pointer Arithmetic - Port. Rec. 17

Avoid pointer arithmetic [CODSTA-13-3]


DESCRIPTION
This rule detects code that uses pointer arithmetic.
"Avoid pointer arithmetic. Pointer arithmetic can be portable.
The operators == and != are defined for all pointers of the same type,
while the use of the operators <, >, <=, >= are portable
only if they are used between pointers which point into the same array."

BENEFITS
Prevents confusion of types (e.g., in comparison).

EXAMPLE
int* returnptr();
void foo() {
int* a;
char* b;
if (a == b) {}// Violation
if (returnptr( ) >= b) {}// Violation
if (b < returnptr( )) {}// Violation
}

REPAIR
Do not use pointer arithmetic.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.8
From: 18 Portable Code - 18.8 Pointer Arithmetic - Port. Rec. 18
2. ISO/DIS 26262
point 8.4.4

Never convert consts to non-consts [CODSTA-14-3]


DESCRIPTION
Cast away const on an object whose original definition was const may prove
to
undefined behaviour. Compilers can put constant data into ROM or writeprotected
RAM pages and casting away const from such a const object often causes
a memory fault.
The rule detects casts that remove a const qualification from the type
addressed
by a pointer or reference.
Besides it detects an implicit cast from a string literal to char*.

BENEFITS
The rule prevents undefined behaviours.

EXAMPLE
void foo( const int a, const int* b ) {
int x;
int* y;
(int&) a = x;
// Violation
y = (int*) b;
// Violation
*y = 10;
}

REPAIR
Avoid casting away const.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 13 Type Conversions - Rule 46
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-

Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 94

Do not declare the size of an array when the array is passed into a function as a parameter
[CODSTA-15-2]
DESCRIPTION
This rule detects if the size of an array is declared when the array
is passed into a function as a parameter. Do not declare the
magnitude of a single dimensional array in the argument declaration.
The 'C' language will pass an array argument as a pointer to the first
element in the array.In fact, different invocations of the function
may pass array arguments with different magnitudes. Therefore,
specifying the magnitude of an array in a function argument definition
might complicate software maintenance.

BENEFITS
Prevents potential loss of data.

EXAMPLE
void foo2(int ii[30])
// Violation
{
}
void foo3(char a,int ii[30][30][30]) // Violation
{
}

REPAIR
void foo1(int ii[])
{
}
void foo4(char a,int ii[][30][30])
{
}

REFERENCES
Motorola Coding Standards R-7

// OK

// OK

Do not declare the size of an array when the array is initialized [CODSTA-16-2]
DESCRIPTION
This rule detects if the size of an array is declared when the array
is initialized. When global arrays are initialized in the definition,
their magnitude shall be set by initialization. By allowing the
magnitude of an array to be set automatically during definition,
changes to the number of elements in the initialization list do not
require corresponding changes to the explicit array size.

BENEFITS
Makes code easier to maintain.

EXAMPLE
#define SIZE 4
int tab1[SIZE] = {1,2,3}; // Violation

REPAIR
int tab2[]={1,2,3};

// OK

REFERENCES
Motorola Coding Standards, R-6

Do not compare a pointer to NULL or assign NULL to a pointer; use 0 instead [CODSTA-17-3]
DESCRIPTION
This rule detects code that compares a pointer to NULL or assigns NULL
to a pointer. "Do not compare a pointer to NULL or assign NULL to a
pointer; use 0 instead."

BENEFITS
According to the ANSI-C standard, NULL is defined either as (void*)0 or as
0.
If this definition remains in ANSI-C++, problems may arise.
If NULL is defined to have the type void*, it cannot be assigned an
arbitrary
pointer without an explicit type conversion.

EXAMPLE
#include <stddef.h>
void foo( ) {
int *lp = NULL; // Violation
}

REPAIR
#include <stddef.h>
void foo( ) {
int *lp = 0; // OK
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rule 42
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 175

Prefer while statements over do statements [CODSTA-18-5]


DESCRIPTION
This rule checks that code prefers "while" statements over "do"
statements.

BENEFITS
Using do statements can lead to errors and confusion.
Using while statements instead of do statements can
make code clearer and help prevent errors.

EXAMPLE
void func( )
{
int i = 0;
do
// Violation
{
i++;
} while ( i < 10);
}

REPAIR
void func( )
{
int i = 0;
while (i < 10)
{
i++;
}
}

// OK

REFERENCES
Recommended by ParaSoft

Use the ctype.h facilities for character test [CODSTA-19-3]


DESCRIPTION
This rule checks that code uses the ctype.h facilities for character test.
The ctype.h facilities for character tests and upper-lower conversions
(isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint, ispunct,
isspace, isupper, isxdigit, tolower, toupper) are portable across
different
character code sets, are usually very efficient, and promote international
flexibility. However, other similarly named functions
(such as _tolower, _toupper, _isascii) are not universally portable.

BENEFITS
Using function from ctype.h for char testing makes
code more portable across different character code sets.

EXAMPLE
#include <ctype.h>
void test(char c) {
if( 'a' <= c && c <= 'z') {
}

// Violation

while( 'A' <= c && c <= 'Z') {// Violation


}
}

REPAIR
#include <ctype.h>
void test(char c) {
if(islower(c))
{
}
while(isupper(c))
{
}
}

// OK

// OK

REFERENCES
http://www.gnu.org/software/libc/manual/html_node/Character-Handling.html

EOS should be used to terminate a string rather than NULL [CODSTA-20-2]


DESCRIPTION
This rule checks that EOS is used to terminate a string.
EOS should be used to terminate a string rather than NULL,
since NULL is not guaranteed to be defined as zero.

BENEFITS
Promotes the use of defined constants rather than hard coded values.

EXAMPLE
#include <stddef.h>
#define EOS '\0'
void foo( ) {
char str[30] = "Sample text.";
str[7] = NULL;
}

// Violation

REPAIR
#include <stddef.h>
#define EOS '\0'
void foo( ) {
char str[30] = "Sample text.";
str[7] = EOS;
}

REFERENCES
Motorola Coding Standards G-11

// OK

When using enum, the values of each member should be explicitly declared [CODSTA-21-5]
DESCRIPTION
When using enum, the values of each member should be explicitly declared.

BENEFITS
Explicit declarations of each members values is valuable documentation
when using an emulator, logic analyzer or other debugging device.

EXAMPLE
enum my_enum1
{
a,
// Violation
};

REPAIR
enum my_enum2
{
a = 0 // OK
};

REFERENCES
Motorola Coding Standards G-15

Local variable or parameter names and class member variable or parent class/struct member
variable names shall differ by more than a single character [CODSTA-22-1]
DESCRIPTION
This rule checks that local variable or parameter names and
class member variable or parent class/struct member variable
names differ by more than a single character.

NOTES
Case insensitive check is performed.
Names that are one character in length are skipped.

BENEFITS
Rule improves readability and prevents writing ambiguous code.

EXAMPLE
class Base {
void foo( ) {
float memberF;
// Violation
}
int foo1( );
short foo2( ) {
for( int _var2 = 0; _var2 < 10; _var2++ ) {
}
return Var3;
}
public:
int Member;
float Var1;
float Var2;
short Var3;
};
int Base::foo1( ) {
int _var1 = 6;
return _var1;
}

// Violation

// Violation

class A : public Base {


void foo( ) {
float memberF;
// Violation
}
int foo1( );
short foo2( ) {
for( int _var2 = 0; _var2 < 10; _var2++ ) {
}
return Var3;
}
};
int A::foo1( ) {
int _var1 = 6;
return _var1;
}

// Violation

// Violation

REPAIR
class Base {
void foo( ) {
float fLocal;
// OK
}
int foo1( );
int x;
short foo2( ) {
int y;
// OK
for( int iValue = 0; iValue < 10; iValue++ ) {
}
return Var3;
}
public:
int Member;
float Var1;
float Var2;
short Var3;
};
int Base::foo1( ) {
int iValue = 6;
return iValue;
}

// OK

// OK

class A : public Base {


void foo( ) {
float fLocal;
// OK
}
int foo1( );
int x;
short foo2( ) {
int y;
// OK
for( int iValue = 0; iValue < 10; iValue++ ) {
}
return Var3;
}
};
int A::foo1( ) {
int iValue = 6;
return iValue;
}

REFERENCES
Recommended by ParaSoft

// OK

// OK

All 'if' statements should have an 'else' clause [CODSTA-23-3]


DESCRIPTION
The rule reports a violation on 'if' statement without an 'else'
statement.
See also: MISRA2004-14_10

BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.

EXAMPLE
int foo(int a, int b) {
if(a > b){
// Violation
return a - b;
}
if(a < b){
return b - a;
}

// Violation

if(a == b)
return 1;

// Violation

REPAIR
int foo(int a, int b) {
if(a > b){
// OK
return a - b;
} else if(a < b){
// OK
return b - a;
} else {
return 1;
}
}

REFERENCES
1. Recommended by ParaSoft

If FALSE is to be defined, and is not already defined, #define FALSE should be 0 [CODSTA-245]
DESCRIPTION
This rule checks whether you defined FALSE as 0.
See also: CODSTA-25

BENEFITS
Any use of FALSE-- other than defining FALSE as 0-- is misleading
and will not be guaranteed to work predictably.

EXAMPLE
#define FALSE 1 // Violation
#undef FALSE
#define FALSE
// Violation

REPAIR
#define FALSE 0 // OK

REFERENCES
http://www.research.att.com/~bs/glossary.html#Gfalse

If FALSE is to be defined, and is not already defined, enum value FALSE should be 0
[CODSTA-25-5]
DESCRIPTION
This rule checks if FALSE is defined as 0.
See also: CODSTA-24, CODSTA-43

BENEFITS
Any use of FALSE-- other than defining FALSE as 0-- is misleading
and will not be guaranteed to work predictably.

EXAMPLE
#ifndef FALSE
typedef enum
{
TRUE = 1,
FALSE = -1
} BOOL ;
#endif

// Violation

REPAIR
#ifndef FALSE
typedef enum
{
TRUE = 1,
FALSE = 0
} BOOL ;
#endif

// OK

REFERENCES
http://www.research.att.com/~bs/glossary.html#Gfalse

Avoid magic numbers [CODSTA-26-3]


DESCRIPTION
Avoid spelling literal constants in code. They are not self-explanatory.
Use symbolic values instead.
See also: CODSTA-29

NOTES
We excluded using literal constants in initialization.
We also skip usage of 0 or 1 because they are equivalent of true or false.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void boo(int);
int foo( int a[], int b ) {
int e;
int f = 0;
a[5] = 56; // Violation
e= 8;
// Violation
boo(56);
// Violation
return 8; // Violation
}

REPAIR
const int MAX = 8;

// OK

void boo(int);
int foo( float a[], float b ) {
int e;
int f = 0;
// OK
int i = 5;
// OK

a[i] = MAX;
e = MAX;
boo(a[5]);
return MAX;

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151

Avoid functions that modify global variables [CODSTA-27-3]


DESCRIPTION
The rule reports a violation if in function is modified:
- a global variable, or
- a member variable of global object, or
- an element of global array

BENEFITS
In multithread environment using global
variables makes code extremely error prone.

EXAMPLE
struct S {
int a;
}g_struct;
int g_i;
int g_arr[10];
void foo(){
g_i++;
g_struct.a = 10;
g_arr[3] += 2;
}

// Violation
// Violation
// Violation

REPAIR
Do not modify global variables.

REFERENCES
http://charm.cs.uiuc.edu/manuals/html/tcharm/2_1.html

Define fields for union declarations [CODSTA-28-5]


DESCRIPTION
This rule is purely informational and will report a message
when a union declaration is found which has no field defined.

BENEFITS
Prevents form incomplete code.

EXAMPLE
union UNKNOWN
{
};

// Violation

REPAIR
union KNOWN// OK
{
int a;
};

REFERENCES
Recommended by ParaSoft

"#define" or enum constants should be used instead of hard coded values whenever possible
[CODSTA-29-3]
DESCRIPTION
This rule checks whether you are avoiding using hard coded values. Using
#define
or enum constants rather than hard coded values promotes the
maintainability
of 'C' code by creating a localized area for changes.
See also: CODSTA-26

NOTES
Rule active for C code only.

BENEFITS
Readability and maintainability.

EXAMPLE
void foo( ) {
int tabColors[256];
if (tabColors[2] == 1) {
/*...*/
}
}

REPAIR
#define buff 256
#define OK 1
enum color {
RED = 0,
BLUE = 1,
GREEN = 2
/*...*/
};

// Violation
// Violation

void foo( ) {
int tabColors[buff];
// OK
if (tabColors[RED] == OK) { // OK
/*...*/
}
}

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 10 Constants - Rule 37

Avoid returning handles to function parameters [CODSTA-30-3]


DESCRIPTION
A function must never return a pointer or reference to a parameter,
it could make your code non-deterministic. If a function returns
a reference or a pointer to a parameter, the memory to which it refers
will already have been deallocated, when this reference or pointer
is used. The compiler may or may not give a warning for this.

BENEFITS
Rule prevents non-deterministic behaviour.

EXAMPLE
int* foo1( int x ){
return &x;
// Violation
}
int& foo2( int x ){
return x;
// Violation
}

REPAIR
int foo1( int x ){
return x;
}

// OK

int foo2( int x ){


return x;
}

// OK

REFERENCES
Recommended by ParaSoft

Never use explicit type conversions (casts) [CODSTA-31-3]


DESCRIPTION
"Never use explicit type conversions (casts)."

NOTES
Rule is limited to primitive types only.

EXCEPTIONS
Explicit type conversions may be used to convert a pointer to a base class
to a pointer of a derived class.
Explicit type conversion must be used to convert an anonymous bit-stream
to an object.
Generally, explicit type conversions are needed for reading an external
representation of an object.

BENEFITS
Rule improves clarity and maintainability of code.

EXAMPLE
void foo( ) {
const int ci = 0;
int i;
i = (int) ci;
// Violation
i = (int) &i;
// Violation
}

REPAIR
Do not use casts.

REFERENCES

1. Ellemtel Coding Standards


http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 13 Type Conversions - Rule 43
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 183

Do not write logical expressions of the type if(test) or if(!test) when test is a pointer [CODSTA32-3]
DESCRIPTION
"Do not write logical expressions of the type if(test) or if(!test)
when test is a pointer.(...)
We do not recommend logical tests such as if(pointer)
if pointer is a variable of pointer-type.
The only reason is readability, many programmers find it difficult to read
such code."

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo( ) {
int* ptr;
if (ptr) { // Violation
}
if (!ptr) { // Violation
}
}

REPAIR
void foo( ) {
int* ptr;
if (ptr == 0) { // OK
}
}

REFERENCES
Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rec. 55

Do not use operator ++ or -- in the conditional expression of if, while, or switch [CODSTA-33-3]
DESCRIPTION
Using the operator ++ or -- in the conditional part of if, while or switch
can
make code difficult-to-read and error-prone.

BENEFITS
Makes code more readable.

EXAMPLE
int Foo (int iVar)
{
if (iVar-- && iVar<10)
{
iVar += 10;
}
else
{
iVar -= 10;
}
return iVar;
}

REPAIR
int Foo (int iVar)
{
if (iVar<10) // OK
{
iVar += 10;
}
else
{
iVar -= 10;
}
return iVar;
}

// Violation

REFERENCES
Recommended by ParaSoft

Use a typedef to simplify program syntax when declaring function pointers [CODSTA-34-3]
DESCRIPTION
"Use a typedef to simplify program syntax when declaring function
pointers."

BENEFITS
"Another reason to use typedef is that the readability of the code is
improved.
If pointers to functions are used, the resulting code can be almost
unreadable.
By making a type declaration for the function type, this is avoided."

EXAMPLE
void (*p)();

// Violation

REPAIR
typedef void (*PTF)();
PTF p;

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rec. 49
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 176

Always provide a default branch for switch statements [CODSTA-35-3]


DESCRIPTION
"A switch statement must always contain a default branch
which handles unexpected cases."
This rule detects if you fail to provide a default branch
for switch statements. If all desired cases are handled
outside of default, then default can be used for error
checking.
See also: MISRA2004-15_3

BENEFITS
Rule prevents possibility of erroneous code.

EXAMPLE
void foo( ) {
int tag;
switch ( tag ) {// Violation
case 0: {
break;
}
case 1: {
foo( );
break;
}
}
}

REPAIR
void foo( ) {
int tag;
switch ( tag ) {// OK
case 0: {
break;
}
case 1: {
foo( );

break;
}
default: break;
}
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 48
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 194

Pass built-in-types by value unless you are modifying them [CODSTA-36-3]


DESCRIPTION
This rule checks if your code passes arguments of built-in types by value,
unless they should be modified by functions.

BENEFITS
Passing arguments of built-in types by value improves the efficiency
of your code.

EXAMPLE
int Foo(int i, int &j)
{
return i + j;
}
int Bar(int &i, int j)
{
j += i;
return j;
}

// Violation

// Violation

REPAIR
int Foo(int i, int j)
{
return i + j;
}
int Bar(int i, int j)
{
j += i;
return j;
}

// OK

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,

(C) 2005 Pearson Education, Inc. Chapter: "Take Parameters Appropriately


by Value, (Smart) Pointer, or Reference", Rule 25
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions (Value, Pointer or Reference), AV Rule 116

Do not use a #define that prevents the compiler from checking types except ones used only in
#ifs and #elifs conditions [CODSTA-37-3]
DESCRIPTION
This rule checks whether you use a #define that the compiler cannot check
type.
Using a #define prevents the compiler from checking the type .
See also: MISRA2004-19_7, CODSTA-03, CODSTA-38

NOTES
Rule skips #defines which are used only in #ifs and #elifs conditions.
Rule works only within file scope.
It means that each source and header files are parsed one by one.

BENEFITS
By following this rule, you prevent the compiler from disabling type
checking.

EXAMPLE
#define V1 20
#define V2 1
#if V2
#endif

// Violation
// OK

REPAIR
const int V1 = 20; // OK
#define V2 1
// OK
#if V2
#endif

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,

(C) 2005 Pearson Education, Inc., Chapter 1, Item 2

Do not use a #define that prevents the compiler from checking types [CODSTA-38-3]
DESCRIPTION
This rule checks whether you use a #define that the compiler cannot check
type.
Using a #define prevents using unchecked types.
See also: MISRA2004-19_7, CODSTA-03, CODSTA-37

BENEFITS
By following this rule, you prevent the compiler from disabling type
checking.

EXAMPLE
#define MAX_COMPUTERNAME_LENGTH
10
#define MACHINE_NAME_LEN
MAX_COMPUTERNAME_LENGTH + 2

// Violation

REPAIR
const int MAX_COMPUTERNAME_LENGTH = 10;
const int MACHINE_NAME_LEN = MAX_COMPUTERNAME_LENGTH + 2; // OK

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2

Avoid internal or external name conflict with a C++ reserved word [CODSTA-39-1]
DESCRIPTION
Internal or external name conflicts with a C++ reserved word will cause
problems
if program is compiled with a C compiler. Most C compilers do not detect
naming
conflicts, and they can lead to unpredictable program behavior.

BENEFITS
Avoid unpredictable program behavior.

EXAMPLE
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int

bool = 0;// Violation


catch = 0;// Violation
class = 0;// Violation
const_cast = 0;// Violation
delete = 0;// Violation
dynamic_cast = 0;// Violation
explicit = 0;// Violation
export = 0;// Violation
false = 0;// Violation
friend = 0;// Violation
mutable = 0;// Violation
namespace = 0;// Violation
new = 0;// Violation
operator = 0;// Violation
private = 0;// Violation
public = 0;// Violation
protected = 0;// Violation
reinterpret_cast = 0;// Violation
static_cast = 0;// Violation
template = 0;// Violation
this = 0;// Violation
throw = 0;// Violation
true = 0;// Violation
try = 0;// Violation
typeid = 0;// Violation
typename = 0;// Violation

int using = 0;// Violation


int virtual = 0;// Violation
int wchar_t = 0;// Violation

REPAIR
// Avoid using reserved word as variable name

REFERENCES
Recommended by ParaSoft

'void' should be used when a function is passed or returns no values [CODSTA-40-3]


DESCRIPTION
In many compiler implementations, functions which do not declare return
type are automatically assigned int return type. This will conflict with
semantics of function implementation.
The empty parameter list in a function declarator that is not part of
a definition of that function specifies that no information about
the number or types of the parameters is supplied. The special case
of an unnamed parameter of type void as the only item in the list
specifies that the function has no parameters.
Explicitly specifying parameter and return types as void clearly conveys
the function intent.
The rule reports a violation if:
- a function is declared or defined with an empty parameter list or
- a function does not have an explicit return type and does not contain
return statement with a value
The rule is enabled only for C language.
See also: MISRA2004-8_2_a, MISRA2004-16_5

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
void foo1();
*/
void foo1() {}
*/

/* Violation - there is no 'void' in parameter list


/* Violation - there is no 'void' in parameter list

foo2(void);
/* Violation - there is no 'void' in return type */
foo2(void) {}
/* Violation - there is no 'void' in return type */
foo3(void) {return;} /* Violation - there is no 'void' in return type */

REPAIR
void foo1(void);

/* OK */

void foo1(void) {}

/* OK */

void foo3(void) {return;} /* OK */


foo4(void){ return 0;} /* OK - the 'return' statement with a value in
function */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 76

Avoid switch statements with only one case [CODSTA-41-4]


DESCRIPTION
A switch statement should not be used with only one case statement in its
body.
Such a switch statement can be described using an if statement.
See also: CODSTA-54, MISRA2004-15_5

BENEFITS
Avoids improper use of switch.

EXAMPLE
void foo (int i)
{
switch(i)
{
case 0:
break;
default:
break;
}
}

// Violation

REPAIR
void foo (int i)
{
if(i == 0)
{
// ...
} else {
// ...
}
}

REFERENCES

// OK

Recommended by ParaSoft

If TRUE is to be defined, and is not already defined, #define TRUE should be 1 [CODSTA-42-5]
DESCRIPTION
This rule checks whether preprocessor
definition of TRUE is 1. Any other use of TRUE is
misleading and cannot be guaranteed to work
predictably.
See also: CODSTA-43

BENEFITS
Readability and maintainability.

EXAMPLE
#define TRUE 0 // Violation
#undef TRUE
#define TRUE
// Violation
#undef TRUE

REPAIR
#define TRUE 1 // OK

REFERENCES
http://www.research.att.com/~bs/glossary.html#Gtrue

If TRUE is to be defined, and is not already defined, enum value TRUE should be 1 [CODSTA43-5]
DESCRIPTION
This rule checks whether you defined const enum TRUE as 1. Any
other use of TRUE is misleading and cannot be
guaranteed to work predictably.
See also: CODSTA-42, CODSTA-25

BENEFITS
Readability and maintainability.

EXAMPLE
#ifndef TRUE
typedef enum
{
FALSE = 0,
TRUE = 3
} BOOL ;
#endif

// Violation

REPAIR
#ifndef TRUE
typedef enum
{
FALSE = 0,
TRUE = 1
} BOOL ;
#endif

// OK

REFERENCES
http://www.research.att.com/~bs/glossary.html#Gtrue

Local variables and variables of class/parent classes/parent structs should have different
name [CODSTA-44-1]
DESCRIPTION
Rule checks if local variables and variables of class/parent classes/
/parent structs have the same name (case sensitive).
If so, then it reports violation message.
See also: CODSTA-45

BENEFITS
Rule improves readability and prevents writing ambiguous code.

EXAMPLE
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( ) {
float member;
}
short foo2( ) {
for( int var2 = 0; var2 < 10; var2++ ) {
}
return var3;
}

// Violation

// Violation

};

class A : public Base {


void foo( ) {
float member;
}
int foo1( );
};

// Violation

REPAIR
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( ) {
float member2;
}
short foo2( ) {
for( int var4 = 0; var4 < 10; var4++ ) {
}
return var3;
}

// OK

// OK

};
class A : public Base {
void foo( ) {
float member2;
}
int foo1( );
};

REFERENCES
Recommended by ParaSoft

// OK

Parameters and variables of class/parent classes/parent structs should have different name
[CODSTA-45-1]
DESCRIPTION
Rule checks if parameters and variables of class/parent classes/
/parent structs have the same name (case sensitive).
If so, then it reports violation message.
See also: CODSTA-44

BENEFITS
Rule improves readability and prevents writing ambiguous code.

EXAMPLE
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( double var3 ) {
float member;
}

// Violation

};

REPAIR
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( double var4 ) {
float member;
}
};

// OK

REFERENCES
Recommended by ParaSoft

Use positive logic rather than negative logic whenever practical [CODSTA-46-5]
DESCRIPTION
Use positive logic rather than negative logic whenever practical.
The use of many logical nots "!" within an expression makes
the expression difficult to understand and maintain.

BENEFITS
Makes source code more readable.

EXAMPLE
void foo( int *j)
{
if(j!=0){
// Violation
(*j)++;
}
}

REPAIR
void foo( int *j)
{
if(j==0){
} else {
// OK
(*j)++;
}
}

REFERENCES
Motorola Coding Standards G-13

All structures should have typedefs [CODSTA-47-3]


DESCRIPTION
In C language, a structure declaration looks similar to a variable
declaration of the struct type. Using a typedef for each structure
makes variable declarations of struct types similar to those for
built in types, which improves readability of code. Additionally,
using typedefs prevents programming errors due to possible typos in
variable declarations.

EXCEPTIONS
This rule applies only to C code. In C++, the keyword struct defines
a type, and no typedefs are necessary, or should be used.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
struct A {
int i;
};

// Violation - no typedef

struct B {
int i;
};

// Violation - no typedef

REPAIR
typedef struct A {
int i;
} A_t;
struct B {
int i;
};
typedef struct B B_t;

// OK

// OK

REFERENCES
Customer guidelines

The following digraphs will not be used <%, %>, <:, :>, %:, %:%: [CODSTA-48-3]
DESCRIPTION
The following digraphs will not be used <%, %>, <:, :>, %:, %:%:
The use of digraphs listed in this rule can obscure the meaning
of otherwise simple constructs.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
int a <: 2 :> <: 2 :> = <%<%0,1%>,<%2,3%>%>; // Violation

REPAIR
int a[2][2] = { {0,1}, {2,3} };

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-5-1

Null initialize or increment expressions in for loops will not be used; a while loop will be used
instead [CODSTA-49-3]
DESCRIPTION
Null initialize or increment expressions in for loops
will not be used; a while loop will be used instead.
Rule reports a violation message if 'for' statement
misses init or increment section.

SINCE
v7.1

BENEFITS
A while loop provides a more natural representation.

EXAMPLE
void foo()
{
for(int i=0; i< 10;) // Violation
{
/* ... */
}
int j = 0;
for(; j< 10;)
{
/* ... */
}
}

REPAIR
void foo()
{
int i = 0;

// Violation

while(i< 10)
{
/* ... */
}

// OK

int j = 0;
while(j< 10)
{
/* ... */
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 200

Hexadecimal constants will be represented using all uppercase letters [CODSTA-50-3]


DESCRIPTION
Hexadecimal constants will be represented using all uppercase letters.
See also: CODSTA-51

SINCE
v7.1

BENEFITS
Improved readability and maintenance.

EXAMPLE
int i = 0x3fff;

// Violation

REPAIR
int i = 0x3FFF;

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 150
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4

Literal suffixes shall use uppercase rather than lowercase letters [CODSTA-51-2]
DESCRIPTION
Literal suffixes shall use uppercase rather than lowercase letters.
See also: CODSTA-50

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo(long param = 64l) // Violation
{
const long a = 64l; // Violation
}

REPAIR
void foo(long param = 64L) // OK
{
const long a = 64L;
// OK
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4

The initialization expression in a for loop will perform no actions other than to initialize the
value of a single for loop parameter [CODSTA-52-3]
DESCRIPTION
The initialization expression in a for loop will perform no actions other
than
to initialize the value of a single for loop parameter.
Note that the initialization expression may invoke an accessor that
returns
an initial element in a sequence:
for (Iter_type p = c.begin() ; p != c.end() ; ++p) // Good
{
// ...
}

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo()
{
int k = 0;
/* ... */
for(; k>0; k--){}
for(int i=0, k=2; k>0; k--){}
for(int i = k+2-10; k>0; k--){}
for(k--; k>0; k--){}
}

REPAIR

//
//
//
//

Violation
Violation
Violation
Violation

class A
{
public:
int i;
int moo();
};
void foo()
{
int k = 0;
A obj;
/* ... */
for(k=2; k>0; k--){}
for(int i =0; i>0; i--){}
for(k = obj.i; k>0; k--){}
for(k = obj.moo(); k>0; k--){}
}

//
//
//
//

OK
OK
OK
OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 198

The increment expression in a for loop will perform no action other than to change a single
loop parameter to the next value for the loop [CODSTA-53-3]
DESCRIPTION
The increment expression in a for loop will perform no action other
than to change a single loop parameter to the next value for the loop

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo()
{
int k = 0;
for(;k>0; ){}
// Violation
for(int i=0; k>0; k--, i++){} // Violation
for(k--; k>0; k+1){}
// Violation
}

REPAIR
void zoo(){}
class A
{
public:
int i;
};
void foo()
{
int k = 0;

A obj;
for(int i = k+2-10; k>0; zoo()){}
for(k=2; k>0; k--){}
for(int i =0; i>0; i=i-1){}
for(k = obj.i; k>0; k-=1){}

//
//
//
//

OK
OK
OK
OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 199

Every switch statement will have at least two cases and a potential default [CODSTA-54-3]
DESCRIPTION
Every switch statement will have at least two cases and a potential
default.
See also: CODSTA-41, MISRA2004-15_5

SINCE
v7.1

BENEFITS
An if statement provides a more natural representation.

EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}

// Violation

REPAIR
void foo(int i)
{
switch(i)
{
case 1:
break;
case 2:
break;
default:
;
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 196

Enumeration types shall be used instead of integer types (and constants) as case labels
[CODSTA-55-2]
DESCRIPTION
Enumeration types shall be used instead of integer types (and constants)
to
select from a limited series of choices. Rule reports a violation message
if integer types (constants) are used as case labels.

SINCE
v7.1

EXCEPTIONS
This rule is not intended to exclude character constants (e.g. 'A', 'B'
etc.)
from use as case labels.

BENEFITS
Enhances debugging, readability and maintenance.
Note that a compiler flag (if available) should be set to generate a
warning
if all enumerators are not present in a switch statement.

EXAMPLE
void foo(int color)
{
switch(color)
{
case 1:
break;
case 2:
break;
case 3:
break;

// Violation
// Violation
// Violation

default:
break;
}
}

REPAIR
enum color
{
RED = 1,
BLUE = 2,
GREEN = 3
};
void foo(int color)
{
switch(color)
{
case RED:
break;
case BLUE:
break ;
case GREEN:
break;
default:
break;
}
}

// OK
// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 148

All 'case' and 'default' labels of 'switch' statement should have an explicit 'break' or a 'return'
statement, or 'fall through' comment [CODSTA-56-3]
DESCRIPTION
All 'case' and 'default' labels of 'switch' statement should have:
- an explicit unconditional 'break' or a 'return' statement or
- at the end a 'fall through' comment containing "fall through" phrase
(checked case insensitive).

SINCE
v7.2

EXCEPTIONS
Rule does not report a violation message for empty labels.

BENEFITS
Rule prevents unpredictable program behaviour.

EXAMPLE
void MyFunction(int i, int j)
{
switch(i)
{
case 1:
// Violation
i++;
case 2:
case 3:
// Violation
i++;
/* wrong comment */
case 4:
// Violation - 'break' and 'return' are nested
if(j > 5){
i--;
break;
} else {
return i;

}
default:
;
}

// Violation

REPAIR
void MyFunction(int i, int j)
{
switch(i)
{
case 1:
// OK
i++;
break;
case 2:
// OK - empty label
case 3:
// OK
i++;
/* fall through */
case 4:
// OK
if(j > 5){
i--;
break;
} else {
return i;
}
break;
default:
// OK
break;
}
}

REFERENCES
Recommended by ParaSoft

Suspicious use of semicolon [CODSTA-57-4]


DESCRIPTION
Rule reports a violation message if the semicolon constituting
the statement body is placed in the same line as closing ")"
parentheses (e.g., if(e); or while(e); or for(e;e;e);.

SINCE
v7.2

EXCEPTIONS
Rule does not report a violation message if the ';' is placed
in different line than the ')'.

BENEFITS
Rule prevents accidental termination of 'if', 'while', or 'for'
constructs.

EXAMPLE
void foo(int param)
{
if (param);
// Violation
for(;;)

// Violation

while(param); // Violation
{
}
}

REPAIR
void foo(int param)

{
if (param)
{
}

// OK

for(;;)
;

// OK

while(param)
{

// OK

}
}

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Cast to void is not allowed [CODSTA-58-4]


DESCRIPTION
Avoid casts to void. A (void) cast operator does not cause a value
to be converted to void - it just creates a void expression and
suppresses warnings.

SINCE
v7.2

BENEFITS
Rule prevents silencing compiler and static analysis tools warnings.

EXAMPLE
int someFunction();
void foo()
{
/* ... */
(void)someFunction();
}

// Violation

REPAIR
int someFunction();
void foo()
{
/* ... */
if(someFunction())
{
/* ... */
} else{
/* ... */
}
}

// OK

REFERENCES
Recommended by ParaSoft

Hardcoded array declarations and 'malloc' calls should not be used [CODSTA-59-4]
DESCRIPTION
Hardcoded calls to malloc and hardcoded array declarations decrease
readability and maintainability of code. Macros should be used instead
of these calls, so that all instances of hardcoded size could be changed
by a single code update.

SINCE
v7.2

EXCEPTIONS
Expressions such as [ARRAY_SIZE + 1] are allowed
in array declarations for type char.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
#include <stdlib.h>
void myFunction()
{
int array[10];
malloc(20);
}

REPAIR
#include <stdlib.h>
#define ARRAY_SIZE 10
#define MALLOC_SIZE 20

// Violation
// Violation

void myFunction()
{
int array[ARRAY_SIZE];
malloc(MALLOC_SIZE);
}

REFERENCES
Recommended by ParaSoft

// OK
// OK

Avoid comparing values with TRUE macro/enum constant using equality operators ("==", "!=")
[CODSTA-60-3]
DESCRIPTION
Avoid checking "== TRUE" and "!= TRUE".
Such checks should be avoided because true can have many possible values
(any non-zero value can be true), but the TRUE macro or enum constant is
defined, for example, as 1.

SINCE
v7.2

BENEFITS
Checking "== TRUE" or "!= TRUE", can be dangerous if
e.g., variable is true but not 1.

EXAMPLE
#define TRUE 1
void foo()
{
int a = 10;
if(a==TRUE)
{
/* ... */
}
}

REPAIR
#define TRUE 1
void foo()
{

// Violation

int a = 10;
if(a)
{
/* ... */

// OK

}
}

REFERENCES
Recommended by ParaSoft

The final clause of a switch statement shall be the default-clause [CODSTA-61-3]


DESCRIPTION
"The final clause of a switch statement shall be the default-clause.
The requirement for a final default-clause is defensive programming.
This clause shall either take appropriate action, or else contain a
suitable
comment as to why no action is taken."

SINCE
v7.2

EXCEPTIONS
"If the condition of a switch statement is of type enum, and all the
enumerators are listed in case labels, then the default-clause is not
required
as the rules associated with enums are intended to ensure that the enum
cannot
be assigned values outside of its set of enumerators."

BENEFITS
Rule improves readability and maintainability of 'switch' statement.

EXAMPLE
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;

// Violation

}
switch( colour )
{
case RED:
break;
case GREEN:
break;

// Violation

}
}

REPAIR
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
default:
break;
}
switch( colour )
{
case RED:
break;
case BLUE:
break;
case GREEN:
break;
}
}

// OK

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3

A cast shall not convert a pointer to a function to any other pointer type, including a pointer to
function type [CODSTA-62-3]
DESCRIPTION
"Conversion of a function pointer to a non-function pointer type causes
undefined behaviour. Undefined behaviour may arise if a function call is
made using a pointer that is the result of a function pointer conversion."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
void f ( int )
{
reinterpret_cast< void (*)( ) >( &f ); // Violation
reinterpret_cast< void * >( &f );
// Violation
}

REPAIR
Do not cast a pointer to a function to any other pointer type.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-6

Bitwise operators shall only be applied to operands of unsigned underlying type [CODSTA-633]
DESCRIPTION
"Bitwise operations (~, <<, <<=, >>, >>=, &, &=, ^, ^=, | and |=) are not
normally meaningful on signed integers or enumeration constants.
Additionally, an implementation-defined result is obtained if a right
shift
is applied to a negative value."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & s1;

// Violation

REPAIR
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & (unsigned short)s1;
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-21

An unconditional throw or break statement shall terminate every non-empty switch-clause


[CODSTA-64-3]
DESCRIPTION
"An unconditional throw or break statement shall terminate every non-empty
switch-clause. If a developer fails to add a break statement to the end of
a switch-clause, then control flow "falls" into any following switchclause.
Whilst this is sometimes intentional, it is often an error. To ensure that
such errors can be detected, the last statement in every switch-clause
shall
be a break statement, or if the switch-clause is a compound statement,
then the
last statement in the compound statement shall be a break statement. A
special
case exists if the switch-clause is empty, as this allows groups of
clauses
requiring identical statements to be created."

SINCE
v7.2

BENEFITS
Prevents unpredictable program behaviour.

EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)

// Violation

// Violation

{
i = 5;
break;
}
case 2 :
{

// Violation
i = 3;

}
default:
i = 8;

// Violation

}
}

REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
throw;
}
}

// OK

// OK

// OK

// OK - empty case
// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3

An object with integer type or pointer to void type shall not be converted to an object with
pointer type [CODSTA-65-3]
DESCRIPTION
"An object with integer type or pointer to void type shall
not be converted to an object with pointer type"

SINCE
v7.2

BENEFITS
In general, converting from an integral type or a pointer to void type
to a pointer to an object leads to unspecified behaviour.

EXAMPLE
struct S
{
int i;
int j;
};
void f ( void * v, int i )
{
S * s1 = reinterpret_cast< S * >( v ); // Violation
S * s2 = reinterpret_cast< S * >( i ); // Violation
}

REPAIR
Do not cast an object with integer type or pointer to void type
to an object with pointer type

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems
Chapter 6, Section 5, Rule 5-2-8

Non-constant operands to a binary bitwise operator shall have the same underlying type
[CODSTA-66-3]
DESCRIPTION
"Non-constant operands to a binary bitwise operator shall have the same
underlying type. The term 'underlying type' is defined as describing
the type that would be obtained from evaluating an expression if it were
not for the effects of integral promotion."

SINCE
v7.2

BENEFITS
"Using operands of the same underlying type documents that it is the
number
of bits in the final (promoted and balanced) type that are used, and not
the number of bits in the original types of the expression."

EXAMPLE
void foo()
{
unsigned char mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// Violation
}

REPAIR
void foo()
{
unsigned short mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-20

The types used for an object, a function return type, or a function parameter shall be tokenfor-token identical in all declarations and re-declarations [CODSTA-67-3]
DESCRIPTION
"If a re-declaration has compatible types but not types which are
token-for-token identical, it may not be clear to which declaration
that re-declaration refers."

SINCE
v7.2

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
typedef int INT;
INT i;
extern int i;

// Violation

void foo(const int i);


void foo(int i){}
// Violation

REPAIR
typedef int INT;
INT i;
extern INT i;

// OK

void foo(const int i);


void foo(const int i){} // OK

REFERENCES

MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-9-1

A "U" suffix shall be applied to all octal or hexadecimal integer literals of unsigned type
[CODSTA-68-3]
DESCRIPTION
"The type of an integer is dependent on a complex combination of factors
including:
- The magnitude of the constant;
- The implemented sizes of the integer types;
- The presence of any suffixes;
- The number base in which the value is expressed.
For example, the value 0x8000 is of type unsigned int in a 16-bit
environment,
but of type (signed) int in a 32-bit environment. If an overload set
includes
candidates for an unsigned int and an int, then the overload that would be
matched by 0x8000 is therefore dependent on the implemented integer size.
Adding a "U" suffix to the value specifies that it is unsigned."

SINCE
v7.2

BENEFITS
Rule improves portability and prevents undefined behaviour.

EXAMPLE
unsigned long var = 02;

// Violation

REPAIR
unsigned long var = 02U; // OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems

Chapter 6, Section 2, Rule 2-13-3

Expressions with type (plain) char and wchar_t shall not be used as operands to built-in
operators other than =, ==, != and the unary & operator [CODSTA-69-3]
DESCRIPTION
"Expressions with type (plain) char and wchar_t shall not be used as
operands
to built-in operators other than the assignment operator =, the equality
operators == and !=, and the unary & operator."

SINCE
v7.2

EXCEPTIONS
Exceptionally, the following operators may be used if the associated
restriction is observed:
- The binary + operator may be used to add an integral
value in the range 0 to 9 to 0;
- The binary operator may be used to subtract character 0;
- The relational operators <, <=, >, >= may be used to determine
if a character (or wide character) represents a digit.
(Rule does not report a violation if a character constant is compared
with a variable of type plain char)

BENEFITS
"Manipulation of character data may generate results that are contrary
to developer expectations."

EXAMPLE
void foo()
{
char ch = 't';
// OK
if ( ( ch >= 'a' ) && ( ch <= 'z' ) ) // Violation
{
//...
}

REPAIR
void foo()
{
char ch = 't';
// OK
if ( ch == 't' ) // OK
{
//...
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-3

Expressions with type enum shall not be used as operands to built-in operators other than [ ],
=, ==, !=, <, <=, >, >=, and the unary & operator [CODSTA-70-3]
DESCRIPTION
"Expressions with type enum shall not be used as operands to built-in
operators other than the subscript operator [ ], the assignment operator
=,
the equality operators == and !=, the unary & operator, and the relational
operators <, <=, >, >=."

SINCE
v7.2

BENEFITS
"Enumerations have implementation-defined representation
and so should not be used in arithmetic contexts."

EXAMPLE
/* Examples of incorrect code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 + COLOUR_1 ) == colour ){} // Violation
}

REPAIR
/* Examples of correct code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 < colour) && (COLOUR_3 > colour ) ){} // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-2

Named bit-fields with signed integer type shall have a length of more than one bit [CODSTA71-3]
DESCRIPTION
"Named bit-fields with signed integer type shall have a length of more
than one
bit. The values which may be represented by a bit-field of length one may
not
meet developer expectations. Anonymous signed bit-fields of any length are
allowed."

SINCE
v7.2

NOTES
Rule reports violations only for explicitly signed types

BENEFITS
Rule prevents the potential pitfalls and erroneous code.

EXAMPLE
struct MyStruct
{
signed int si01 : 1;
signed int si02 : 1;
};

// Violation
// Violation

REPAIR
struct MyStruct
{
signed int si01 : 2;
signed int : 1;
};

// OK
// OK

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-4

Assembler instructions shall only be introduced using the asm declaration [CODSTA-73-3]
DESCRIPTION
"The asm declaration is available to all C++ implementations, allowing
a consistent mechanism to be used. However, the parameters to asm are
still implementation-defined."
Rule reports a violation if '#pragma asm', '#pragma endasm' or an
assembler instruction that form is different than "asm" is found.

SINCE
v7.2

BENEFITS
Rule improves consistency of the code.

EXAMPLE
void foo()
{
#pragma asm
"NOP";
#pragma endasm
}

// Violation
// Violation

REPAIR
void foo()
{
asm ( "NOP" ); // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-4-2

Bit-fields shall not have enum type [CODSTA-74-3]


DESCRIPTION
"The use of enum as a bit-field type is prohibited as ISO/IEC 14882:2003
does
not explicitly define the underlying representation as signed or unsigned.
It is therefore not possible to determine the exact number of bits
required
to represent all values in the enumeration."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
enum Color{RED, BLUE, BLACK};
struct S
{
Color n : 2;
/* ... */
};

// Violation

REPAIR
struct S
{
unsigned int n: 2 // OK
/* ... */
};

REFERENCES

MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-3

Bit-fields shall be either bool type or an explicitly unsigned or signed integral type [CODSTA75-3]
DESCRIPTION
"Bit-fields shall be either bool type or an explicitly unsigned or signed
integral type Using int is implementation-defined because bit-fields of
type
int can be either signed or unsigned. The use of wchar_t as a bit-field
type
is prohibited as ISO/IEC 14882:2003 does not explicitly define the
underlying
representation as signed or unsigned."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
/* Examples of incorrect code */
struct S
{
char c : 2;
// Violation
short f : 3;
// Violation
int : 0;
// Violation
};

REPAIR
/* Examples of correct code */
struct S
{
unsigned char c : 2;
// OK
signed short f : 3;
// OK
unsigned int : 0;
// OK

bool b : 4

// OK

};

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-2

The identifier main shall not be used for a function other than the global function main
[CODSTA-76-3]
DESCRIPTION
"main (or its equivalent) is usually the entry point to the program and is
the
only identifier which must be in the global namespace. The use of main for
other functions may not meet developer expectations."

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
namespace
{
int main ( ){} // Violation
}

REPAIR
int main ( ){}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-2

The goto statement shall jump to a label declared later in the same function body [CODSTA77-3]
DESCRIPTION
"Unconstrained use of goto can lead to programs that are extremely
difficult
to comprehend, analyse and, for C++, can also lead to the program
exhibiting
unspecified behaviour. However, in many cases a total ban on goto requires
the introduction of flags to ensure correct control flow, and it is
possible
that these flags may themselves be less transparent than the goto they
replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. "Back" jumps are
prohibited
as they can be used to create iterations without using the well-defined
iteration statements supplied by the core language."

SINCE
v7.2

BENEFITS
Prevents unspecified behaviour.

EXAMPLE
void foo(int j)
{
L1:
++j;
goto L1; // Violation - jumps backward
++j;
}

REPAIR
void foo(int j)
{
++j;
goto L1; // OK ++j;
L1:
}

jumps forward

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-2

Any label referenced by a goto statement shall be declared in the same block, or in a block
enclosing the goto statement [CODSTA-78-3]
DESCRIPTION
"Any label referenced by a goto statement shall be declared in the same
block,
or in a block enclosing the goto statement. Unconstrained use of goto can
lead to programs that are extremely difficult to comprehend, analyse and,
for C++, can also lead to the program exhibiting unspecified behaviour.
However, in many cases a total ban on goto requires the introduction of
flags to ensure correct control flow, and it is possible that these flags
may themselves be less transparent than the goto they replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. Jumping in to nested
blocks is
prohibited as it may lead to complex flow graphs."

SINCE
v7.2

BENEFITS
Prevents unspecified behaviour.

EXAMPLE
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
L1: // Violation
j;
}
}

REPAIR
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
}
L1: // OK
j;
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-1

For any iteration statement there shall be no more than one break or goto statement used for
loop termination [CODSTA-79-3]
DESCRIPTION
"For any iteration statement there shall be no more than one break or goto
statement used for loop termination."

SINCE
v7.2

BENEFITS
"Restricting the number of exits from a loop is done in the interests of
good
structured programming. One break or goto statement is acceptable in a
loop
since this allows, for example, for dual outcome loops or optimal coding."

EXAMPLE
void foo( ) {
int a;
for (a = 0; a < 10; a++) { // Violation
if (a == 5) {
break;
}
if (a == 7) {
break;
}
}
}

REPAIR
void foo( ) {
int a;

for (a = 0; a < 10; a++) { // OK


if (a == 5 || a == 7) {
break;
}
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-4

The continue statement shall only be used within a well formed for loop [CODSTA-80-3]
DESCRIPTION
"Over-use of the continue statement can lead to unnecessary complexity
within
the code. This complexity may impede effective testing as extra logic must
be
tested. The required testing may not be achievable due to control flow
dependencies."

SINCE
v7.2

EXCEPTIONS
Rule does not report a violation if the 'continue' is used within 'for'
loop.

BENEFITS
Rule eliminates unnecessary complexity within the code.

EXAMPLE
void foo()
{
int x = 0;
int y;
y = 10;
while(x < y)
{
x++;
/* ... */
continue;
}

// Violation

REPAIR
Do not use 'continue' statement outside 'for' loop.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-3

If a function has internal linkage then all redeclarations shall include the static storage class
specifier [CODSTA-81-3]
DESCRIPTION
"If the declaration of a function includes the static storage class
specifier,
then it has internal linkage. A re-declaration of such a function is not
required to have the static keyword, but it will still have internal
linkage.
However, this is implicit and may not be obvious to a developer. It is
therefore
good practice to apply the static keyword consistently so that the linkage
is explicitly stated."
See also: MISRA2004-8_11

SINCE
v7.2

BENEFITS
Rule improves good programming style and readability.

EXAMPLE
static void f1 ( );
void f1 ( ) { }

// Violation

REPAIR
static void f1 ( );
static void f1 ( ) { }

// OK

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-3-2

Avoid infinite loops [CODSTA-82-3]


DESCRIPTION
Infinite loops are usually caused by user error and result in resource
exhaustion or program termination.
The rule reports a violations if an iteration statement (while, do while,
for)
does not have a termination point. Only loops with empty or simple
constant
conditions are checked.
The rule assumes that a loop can be terminated if it contains:
- break
- return
- goto to a label outside of the loop
- throw that is not caught by try/catch inside of the loop
- calls to standard functions: exit, abort or _Exit

SINCE
v7.3

NOTES
The rule does not check called functions - if there's a termination point
in a function called from within the loop, which is used to stop the loop,
the rule will still report a violation.
The rule does not check if the termination point is reachable (e.g.
'break'
inside of an 'if' statement is considered to be valid regardless of the
'if'
condition).
The rule does only limited checking of 'catch' handlers.

BENEFITS
Finds possible infinite loops that could result in unwanted program
termination,
resource exhaustion or computer "freezing".

EXAMPLE
void foo(char *s) {
for (;;) {
switch (*s++) {
case 'a': continue;
case '\0': break;
}
}
while(true) {
if (!s) {
// return;
}
++s;
}
do {
char * ptr = s;
for(; ptr; ++ptr) {
if (!*ptr) {
goto END_LOOP;
}
}
END_LOOP:
} while(1);
}

// Violation - infinite loop

// The break is for 'switch'!

// Violation - infinite loop


// Code commented out by mistake

// Violation - infinite loop

// Jump does not end 'do while' loop

REPAIR
void foo(char *s) {
for (;;) {
switch (*s++) {
case 'a': continue;
case '\0': break;
}
break;
}
while(true) {
if (!s) {
return;
}
++s;
}
do {

// OK

// OK

// OK

char * ptr = s;
for(; ptr; ++ptr) {
if (!*ptr) {
goto END_LOOP;
}
}
} while(1);
END_LOOP:
}

REFERENCES
Recommended by ParaSoft

All loops must have a fixed upper or lower bound [CODSTA-83-3]


DESCRIPTION
"The absence of recursion and the presence of loop bounds prevents runaway
code. This rule does not, of course, apply to iterations that are meant to
be
non-terminating (e.g., in a process scheduler)."
"One way to support the rule is to add an explicit upper bound to all
loops that
have a variable number of iterations (e.g., code that traverses a linked
list).
When the upper bound is exceeded an assertion failure is triggered,
and the function containing the failing iteration returns an error."
The rule reports a violation if:
- a loop is non-infinite and does not contain in condition single
relational
expression 'variable < FB', 'variable <= FB', 'FB > variable',
'FB >= variable' where FB is a constant or a const variable or parameter.
- a loop contains proper condition with upper bound but does not contain
incrementation of checked variable 'variable++', '++variable',
'variable += PV', 'variable = variable + PV', 'variable = PV + variable'
- a loop contains proper condition with lower bound but does not contain
decrementing of checked variable 'variable--', '--variable',
'variable -= PV', 'variable = variable - PV'
where PV is:
- a constant higher than 0,
- a const variable with known initializer higher than 0,
- parameter/variable/expression of unsigned type.

SINCE
v7.3

BENEFITS
Rule prevents writing endless loops.

EXAMPLE
void foo(int p){

int i = 0;
while(i == 5){
i = i + 2;
}
while(i < p){
i++;
}
while(i < 7){
loop
// ...
}

// Violation - no relational operator in condition

// Violation - variable is not compared with constant

// Violation - no incrementation of variable inside

for(i = 10; i <= 7; i--){ // Violation - no incrementation in loop


}
while(i > 7){
// ...
}

// Violation - no decrementing of variable inside loop

for(i = 10; i >= 7; i++){ // Violation - no decrementing in loop


}
}

REPAIR
void foo(const int p){
int i = 0;
while(i < 5){
i = i + 2;
}

// OK

while(i < p){


i++;
}

// OK

while(i < 7){


i++;
}

// OK

for(i = 10; i <= 7; i++){ // OK


}

while(i > 7){


--i;
}

// OK

for(i = 10; i >= 7; i--){ // OK


}
}

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 2

Avoid exit points within infinite loops [CODSTA-85-3]


DESCRIPTION
"This rule applies to iterations that are meant to be non-terminating
(e.g., in a process scheduler). It should be statically provable that
the iteration cannot terminate."
The rule reports a violations if an iteration statement (while, do while,
for)
has a termination point. Only loops with empty or simple constant
conditions
are checked.
The rule assumes that a loop can be terminated if it contains:
- break
- return
- goto to a label outside of the loop
- throw that is not caught by try/catch inside of the loop
- calls to standard functions: exit, abort or _Exit

SINCE
v7.3

NOTES
The rule does not check called functions - if there's a termination point
in a function called from within the loop, which is used to stop the loop,
the rule won't report a violation.

BENEFITS
The rule prevents unexpected termination of loop that can not terminate.

EXAMPLE
void foo(){
for(;;){
// code
break;
}

// Violation

while(1){
// code
return;
}

// Violation

REPAIR
void foo(){
for(;;){
// code
}
while(1){
// code
}

// OK

// OK

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 2

The validity of parameters must be checked inside each function [CODSTA-86-3]


DESCRIPTION
"The validity of parameters must be checked inside each function."
The rule reports a violation if a parameter is not checked before the
first
use inside function.

SINCE
v7.3

NOTES
The rule assumes that the parameter is validated if it is used inside
condition of statements: if, switch or ternary operator.

BENEFITS
The rule prevents use incorrect value of parameter.

EXAMPLE
int foo3(int p, int q){
p++;
q++;
return p + q;
}

// Violation

REPAIR
int foo4(int p, int q){
if(p == 0 || q == 0){
return 0;
}
p++;
q++;
return p + q;

// OK

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 7

Use no more than one level of dereferencing [CODSTA-87-3]


DESCRIPTION
"The use of pointers should be restricted. Specifically, no more than one
level
of dereferencing is allowed."

SINCE
v7.3

BENEFITS
"Pointers are easily misused, even by experienced programmers. They can
make it
hard to follow or analyze the flow of data in a program, especially by
tool-based
static analyzers."

EXAMPLE
void foo(){
int** p;
int** q;
int i;
**p = 1; // Violation
i = **q; // Violation
}

REPAIR
Do not use more than one level of dereferencing.

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.

Rule 9

Function pointers are not permitted [CODSTA-88-3]


DESCRIPTION
"The use of pointers should be restricted. Function pointers are not
permitted.
Pointers are easily misused, even by experienced programmers. They can
make it
hard to follow or analyze the flow of data in a program, especially by
tool-based
static analyzers."

SINCE
v7.3

BENEFITS
The rule improves readability of code and causes that the code can be
easier
checked by static analyzers.

EXAMPLE
typedef void (*FP)();
extern FP x[];
/* Violation - variable x */
void foo1(FP * y) {
/* Violation - param x */
int (*z)(void) = 0;
/* Violation - variable z */
foo1(y);
/* OK - usage is ignored */
}
void foo2(FP) {}
/* OK - unnamed parameter ignored */
void foo3(FP p);
/* OK - function declarations are ignored */

REPAIR
Do not declare pointers to functions.

REFERENCES

1. The Power of Ten - Rules for Developing Safety Critical Code.


Rule 9
2. ISO/DIS 26262
point 8.4.4

The declaration should not contain more than one level of pointer indirection [CODSTA-89-3]
DESCRIPTION
Use of more than one level of pointer indirection can seriously impair
the ability to understand the behaviour of the code, and should therefore
be avoided.

SINCE
v7.3

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int** INTPTR; /* Violation */
int** ptr;
/* Violation */
int* a[];
/* Violation */
struct S{
int** s;
/* Violation */
};
struct S** ps;
int** foo();
int(**pfunc1)();
int**(*pfunc2)();
void fun( int** par,
INTPTR par_t
)
{
int* a[10];
/*
int ** ptr;
INTPTR ptr_t = 0;
}

/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */

Violation */
/* Violation */
/* Violation */

REPAIR
Do not declare more than one level of pointer indirection.

REFERENCES
1. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 9
2. ISO/DIS 26262
point 8.4.4

Each operand of a logical '&&' or '||' shall be a postfix-expression [CODSTA-90-3]


DESCRIPTION
The rule reports a violation if an operand other than a single identifier,
constant or function call is not parenthesised.
"Parentheses are important in this situation both for readability
of code and for ensuring that the behaviour is as the developer intended."
See also: MISRA2004-12_1_e, MISRA2004-12_5

SINCE
v7.3

EXCEPTIONS
"Where an expression consists of either a sequence of only logical '&&'
or a sequence of only logical '||', extra parentheses are not required.

BENEFITS
"The effect of this rule is to require that operands are appropriately
parenthesized."

EXAMPLE
int foo( int x, int y, int z )
{
if ( x || y && z );
// Violation
if ( x && !y );
// Violation
return 0;
}

REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
if ( x && ( !y ) );

// OK
// OK

return 0;
}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-1
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 158

A function shall have at most one exit point [CODSTA-91-3]


DESCRIPTION
Every function should have at most one exit point.
Calls of functions exit, abort, and _Exit from standard library stdlib.h
are detected by rule as exit points.

SINCE
v7.3

EXAMPLE
int foo(int i)
{
if (i == 0) {
return 0;
/* Violation */
} else if (i == 1) {
return 1;
/* Violation */
} else {
return 2;
/* Violation */
}
}
void foo2(int* a)
{
if (a == 0) {
return; /* Violation - second exit point at the end of function */
}
*a = 10;
}

REPAIR
int foo(int i)
{
int result = 0;
if (i == 0) {
result = 0;
} else if (i == 1) {

result
} else
result
}
return

= 1;
{
= 2;
result;

/* OK */

}
void foo2(int* a)
{
if (a != 0) {
*a = 10;
}
}

/* OK */

REFERENCES
1. HIS Source Code Metriken, version 1.3.1
Metrik "RETURN"
2. ISO/DIS 26262
point 8.4.4

The names of standard library macros and objects shall not be reused [CODSTA-92-3]
DESCRIPTION
"Where the developer uses new versions of standard library macros or
objects
(e.g. to enhance functionality or add checks of input values), the
modified
macro or object shall have a new name.
This is to avoid any confusion as to whether a standard macro or object,
or a modified version of them, is being used."
Rule checks if the following reserved names are used:
- macro and typedef names from C standard library headers: assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- identifiers that begin with the underscore character
See also: NAMING-33, MISRA2004-20_2, CODSTA-93

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#define NULL ( a > b )
#define _NULL ( a > b )

// Violation
// Violation

REPAIR
#define MY_NULL ( a > b ) // OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-2

The names of standard library functions shall not be overridden [CODSTA-93-5]


DESCRIPTION
"Where the developer uses new versions of standard library functions
(e.g. to enhance functionality or add checks of input values), the
modified
function shall have a new name. However, it is permissible to overload
the name to add new parameter types if the functionality is consistent
with those of the original. This ensures that the behaviour associated
with the name remains consistent. So, for example, if a new version of the
sqrt
function is written to check that the input is not negative, the new
function
shall not be named "sqrt", but shall be given a new name. It is
permissible
to add a new sqrt function for a type not present in the library."
Rule checks if the following reserved names are used:
- function names from C standard library headers: assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- function names that begin with the underscore character
See also: NAMING-33, MISRA2004-20_2, CODSTA-92

BENEFITS
Rule prevents undefined behaviour.

DRAWBACKS
It is not possible in static analysis to check if the functionality is
consistent
with those of the original. So, rule reports violations on all declared
functions
which names are reserved. The user should himself check if the modified
function
has the same functionality and could overload a function from standard
library.
Rule also does not have exception that permits overloading functions with

types not present in the standard library.


EXAMPLE
int printf ( int a, int b )
{
return ( ( a > b ) ? a : b );
}

// Violation

REPAIR
int my_printf ( int a, int b )
{
return ( ( a > b ) ? a : b );
}

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not declare pointer or array type [CODSTA-94-3]


DESCRIPTION
Through pointer you can access the memory directly, but if you do not use
pointers properly there is a possibility that your program might crash.
Because pointers deal with memory dynamically, they come with certain
dangers and disadvantages despite their necessity.
Rule reports violation on any declarations of functions or variables that
use
pointers or arrays. It is not allowed to declare function that returns
pointer
to any type, or takes pointer or array as a parameter, nor to declare
global
or local variable with pointer or array type.
Function pointers are not allowed as well.
See also: CODSTA-95

SINCE
v9.0

BENEFITS
The rule prevents memory leaks, dereferencing a null pointers,
buffer overflows, memory corruptions and undefined behaviours.

EXAMPLE
typedef int* INT_P; /* OK - no violation on typedef */
INT_P x;
/* Violation */
int* foo();
/* Violation */
void (*FP)();
/* Violation */
void bar(int*)
/* Violation */
{
int tab[10];
/* Violation */
int *tab1[10];
/* Violation */
}

REPAIR
Pointers and arrays should not be used.

REFERENCES
Recommended by ParaSoft

Do not declare pointer type [CODSTA-95-3]


DESCRIPTION
Through pointer you can access the memory directly, but if you do not use
pointers properly there is a possibility that your program might crash.
Because pointers deal with memory dynamically, they come with certain
dangers and disadvantages despite their necessity.
Rule reports violation on any declarations of functions or variables
that use pointers. It is not allowed to declare function that returns
pointer to any type, or takes pointer as a parameter, nor to declare
global
or local variable with pointer type.
Function pointers are not allowed as well.
See also: CODSTA-94

SINCE
v9.0

BENEFITS
The rule prevents memory leaks, dereferencing a null pointers,
buffer overflows, memory corruptions and undefined behaviours.

EXAMPLE
typedef int* INT_P; /* OK - no violation on typedef */
INT_P x;
/* Violation */
int* foo();
/* Violation */
void (*FP)();
/* Violation */
void bar(int*)
/* Violation */
{
int tab[10];
/* OK - no violation on simple array */
int *tab1[10];
/* Violation */
}

REPAIR

Pointers should not be used.

REFERENCES
Recommended by ParaSoft

COMMENT
Comments
RULES
Prefer C++ style comment [COMMENT-01-3]
Provide copyright information [COMMENT-02-3]
Comment every file [COMMENT-03-3]
Comment every function [COMMENT-04-3]
Each variable declaration should be commented [COMMENT-05-3]
Each typedef should be commented [COMMENT-06-3]
Each enumeration value should be commented [COMMENT-07-3]
Each structure member variable should be commented [COMMENT-08-3]
All usage of assembler shall be documented [COMMENT-09-3]
Use of floating-point arithmetic shall be documented [COMMENT-10-3]

Prefer C++ style comment [COMMENT-01-3]


DESCRIPTION
Use // for comments. Do not use /* and */.
"C++, however, does not allow comments to be nested using /* */."

BENEFITS
Rule improves readability and maintainability. If the characters // are
consistently used for writing comments, then the combination /* */ may be
used
to make comments out of entire sections of code during the development and
debugging phases.

EXAMPLE
/* Violation */

REPAIR
// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 9
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 126

Provide copyright information [COMMENT-02-3]


DESCRIPTION
"All files must include copyright information, that is to say a line
starting
with: // Copyright"

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
// Violation - no copyright information

REPAIR
// Copyright

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 5
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133

Comment every file [COMMENT-03-3]


DESCRIPTION
"Every file that contains source code must be documented with an
introductory
comment that provides information on the file name and its contents."

NOTES
C and C++ style comments are allowed.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
// No comment "File:"

// Violation - no introductory comment

REPAIR
// File: <short description of the file>

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133

Comment every function [COMMENT-04-3]


DESCRIPTION
"Write some descriptive comments before every function."
Rule reports a violation message on:
1) function prototype if no function definition is visible and prototype
is
not preceded with a comment,
2) function definition if:
- there is no prototype and function definition is not preceded with a
comment
- there is visible prototype but neither prototype nor function
definition is
preceded with a comment

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo1();

// Violation

int foo2(int x){ // Violation


return x++;
}
int foo3(int x);
int foo3(int x){ // Violation
return x++;
}

REPAIR
// Comment with description for the function.
void foo1();
// Comment with description for the function.

int foo2(int x){


return x++;
}
// Comment with description for the function.
int foo3(int x);
int foo3(int x){
return x++;
}
int foo4(int x);
// Comment with description for the function.
int foo4(int x){
return x++;
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 134

Each variable declaration should be commented [COMMENT-05-3]


DESCRIPTION
Each variable declaration should be commented.
Rule reports a violation message if there is no comment
placed in line of variable declaration nor in previous line.

SINCE
v7.1

NOTES
Rule checks only declarations of local and global variables.

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo()
{
int var1;
// Violation
int var2;
// Violation
}

REPAIR
void foo()
{
int var1; // comment - OK
// comment - OK
int var2;

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

Each typedef should be commented [COMMENT-06-3]


DESCRIPTION
Each typedef should be commented.
Rule reports a violation message if there is no comment in line
of typedef declaration and in previous line.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
typedef int int32;
// Violation

REPAIR
typedef int int32; // OK - comment

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

Each enumeration value should be commented [COMMENT-07-3]


DESCRIPTION
Each enumeration value should be commented.
Rule reports a violation message if there is no comment
in line of enumeration value declaration and in previous line.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
enum {
ENUM1 = 2,
// Violation
};

REPAIR
enum {
ENUM1 = 2, // OK - comment
};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

Each structure member variable should be commented [COMMENT-08-3]


DESCRIPTION
Each structure member variable should be commented.
Rule reports a violation message if there is no comment
in line of structure member declaration and in previous line.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
struct S
{
char* c;
// Violation
};

REPAIR
struct S
{
char* c; // comment - OK
};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

All usage of assembler shall be documented [COMMENT-09-3]


DESCRIPTION
"All usage of assembler shall be documented. Assembly language code
is implementation-defined and therefore is not portable."

SINCE
v7.2

NOTES
Rule assumes that the usage of assembler is documented if there is
a comment in the same line as 'asm' instruction or in line directly
before 'asm' instruction.

BENEFITS
Rule improves readability of code.

EXAMPLE
// Violation in line with 'asm' instruction
void foo( void )
{
asm ( "NOP" );
}

REPAIR
void foo( void )
{
// OK - comment before 'asm' instruction
asm ( "NOP" );
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-4-1

Use of floating-point arithmetic shall be documented [COMMENT-10-3]


DESCRIPTION
"If floating-point is to be used, then the following issues need to be
covered
as part of the deviation process:
- A justification explaining why floating-point is the appropriate
or only solution.
- Demonstrate that appropriate skills are available.
- Demonstrate that an appropriate process is being applied.
- Document the floating-point implementation."
Rule checks if in previous or the same line as floating-point arithmetic
expression there is a comment.

SINCE
v7.2

BENEFITS
"The safe use of floating-point arithmetic requires a high level of
numerical
analysis skills and indepth knowledge of the compiler and target
hardware."

EXAMPLE
// Violation in line: double d = d1 + d2;
double add(double d1, double d2)
{
double d = d1 + d2;
}

REPAIR
double add(double d1, double d2)
{
double d = d1 + d2; // OK - floating point arithmetic
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-4-2

EXCEPT
Exceptions
RULES
Never allow an exception to be thrown from a destructor, deallocation, and
swap [EXCEPT-01-1]
Throw by value, catch by reference [EXCEPT-02-1]
Do not throw from within destructor [EXCEPT-03-1]
All exceptions should be rethrown or logged with standard logger [EXCEPT04-2]
C++ exceptions shall not be used (i.e. throw, catch and try shall not be
used.) [EXCEPT-05-2]
There should be at least one exception handler to catch all otherwise
unhandled exceptions [EXCEPT-06-3]
An empty throw (throw;) shall only be used in the compound-statement of a
catch handler [EXCEPT-07-3]
Exceptions shall be raised only after start-up and before termination of
the program [EXCEPT-08-3]
An exception object should not have pointer type [EXCEPT-09-3]
Control shall not be transferred into a try or catch block using a goto or
a switch statement [EXCEPT-10-3]
The assignment-expression of a throw statement shall not itself cause an
exception to be thrown [EXCEPT-11-1]
NULL shall not be thrown explicitly [EXCEPT-12-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point [EXCEPT13-3]
Where a function's declaration includes an exception-specification, the
function shall only be capable of throwing exceptions of the indicated
type(s) [EXCEPT-14-3]
A class type exception shall always be caught by reference [EXCEPT-15-3]
Handlers of a function-try-block implementation of a class constructor or
destructor shall not reference nonstatic members from this class or its
bases [EXCEPT-16-3]
Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases, the
handlers shall be ordered most-derived to base class [EXCEPT-17-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point [EXCEPT18-3]

Never allow an exception to be thrown from a destructor, deallocation, and swap [EXCEPT-011]
DESCRIPTION
"Never allow an error to be reported from a destructor, a resource
deallocation
function (e.g., operator delete), or a swap function. These are key
functions
that must not fail because they are necessary for the two key operations
in transactional programming: to back out work if problems are encountered
during processing, and to commit work if no problems occur."
The rule reports a violation if from a destructor, an operator delete
or a swap function is thrown an exception or is called a function
that can throw exceptions.
See also: EXCEPT-03

NOTES
Function can not throw any exceptions if has external 'C' linkage
or in a declaration uses an empty exception specification throw().

BENEFITS
Rule prevents propagation of exceptions out of the destructor,
operator delete and swap function.

EXAMPLE
class Exceptions{};
class A{
A();
~A();
void operator delete(void*);
};
A::~A(){
throw Exceptions();
}

// Violation

void A::operator delete(void*){


throw Exceptions();
}

// Violation

class B {
public:
B();
~B();
void operator delete(void*);
void foo();
// can throw exceptions
static void soo(); // can throw exceptions
};
B::~B(){
foo();
}

// Violation

void B::operator delete(void*){


soo();
}

// Violation

REPAIR
class A{
A();
~A();
void operator delete(void*);
void foo() throw();
// can not throw exceptions
static void soo() throw(); // can not throw exceptions
};
A::~A(){
foo();
}

// OK

void A::operator delete(void*){


soo();
}

// OK

class B {
public:
B();
~B();

void operator delete(void*);


void foo();
// can throw exceptions
static void soo(); // can throw exceptions
};
B::~B(){
try{
foo();
} catch (...){
}
}
void B::operator delete(void*){
try{
soo();
} catch (...){
}
}

// OK

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 51
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 8
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Throw by value, catch by reference [EXCEPT-02-1]


DESCRIPTION
Exceptions should be thrown by value (not pointer) and caught by reference
(usually to const). This is the combination that meshes best with
exception
semantics, avoiding issues related to memory management of exceptions.
When rethrowing the same exception, prefer just 'throw;' to 'throw
except;'.

BENEFITS
Prevents memory management problems and preserves polymorphism
of the rethrown object.

EXAMPLE
class Exception {
public:
Exception( char* );
};
bool sanityObserved();
void restoreSanity();
void foo_Violation() {
Exception *exp = new Exception("error
if (!sanityObserved()) {
throw exp;
//
}
try {
restoreSanity();
}
catch(Exception* newException) {
//
throw newException;
//
argument
}
}

message");
Violation - throwing a pointer

Violation - caught by pointer


Violation - rethrowing of

REPAIR
class Exception {
public:
Exception( char* );
};
bool sanityObserved();
void restoreSanity();
void foo_OK() {
Exception exp("error message");
if (!sanityObserved()) {
throw exp;
}
try {
restoreSanity();
}
catch(Exception& newException)
{
throw;
}
}

// OK

// OK
// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Error Handling and Exceptions", Rule 73
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Do not throw from within destructor [EXCEPT-03-1]


DESCRIPTION
This rule checks if you throw from within a destructor.
This rule is for C++ programming language only.

BENEFITS
Prevents throwing from within a destructor. It may lead to memory leaks
and improper object destruction.

EXAMPLE
class Foo {
public:
Foo( ) { }
~Foo( ) {
throw;
}
};

// Violation

REPAIR
class Exception {};
class Foo {
public:
Foo( ) { }
~Foo( ) {
try {
// OK
} catch (Exception& e) {
// caught all exceptions
}
}
};

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve

Your Programs and Design", Third Edition, Addison-Wesley,


(C) 2005 Pearson Education, Inc., Chapter 2, Item 8
2. http://www.cs.helsinki.fi/u/vihavain/s03/cpp/items/CppStyleRules2.html
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 15, Rule 15-5-1
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

All exceptions should be rethrown or logged with standard logger [EXCEPT-04-2]


DESCRIPTION
The rule reports a violation if an exception handling does not ensure a
proper
error logging procedure. As a proper error logging procedure is
recognized:
- call of function that begins with 'log' or 'warning' or
- use std::cout, std::cerr, std::clog to generate a log message.

EXCEPTIONS
If an exception is rethrown and could be logged somewhere else, then the
rule
does not report violation.

BENEFITS
An exception is an indication of an abnormal condition during the
application
runtime. When debugging abnormal conditions from the security standpoint,
it is critical to have a proper log of suspicious events.
This rule enforces that proper logging is performed for such exceptions.

EXAMPLE
// example of incorrect code
class Exception { };
void x();
void foo1() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // Violation - no logging
return;
}
}

REPAIR
// examples of correct code
#include <iostream>
class Exception{};
void x();
void log(char* msg); // error logging procedure
void foo1() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
std::cerr << "Error";
return;
}
catch (int * e) { // OK
std::cout << "Error";
return;
}
catch (float e) { // OK
std::clog << "Error";
return;
}
}
void foo2() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
log("Error");
}
}
void foo3() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
throw;

}
}
class MyException { };
void foo4() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
throw MyException();
}
}

REFERENCES
1. http://cwe.mitre.org/data/definitions/391.html
2. http://freshsources.com/HTML/12.07/ALLISON/ALLISON.HTM
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

C++ exceptions shall not be used (i.e. throw, catch and try shall not be used.) [EXCEPT-05-2]
DESCRIPTION
Do not use C++ exceptions.

SINCE
v7.1

BENEFITS
Rule improves portability of the code.

EXAMPLE
#include <iostream>
using namespace std;
int main()
{
char *buf;
try
// Violation
{
buf = new char[512];
if( buf == 0 )
throw "Memory allocation failure!"; // Violation
}
catch( char * str )
// Violation
{
cout << "Exception raised: " << str << '\n';
}
// ...
return 0;
}

REPAIR
#include <iostream>

using namespace std;


int main()
{
char *buf;
buf = new char[512];
if( buf == 0 )
cout<< "Memory allocation failure!";

// OK

return 0;
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.27 Fault Handling, AV Rule 208

There should be at least one exception handler to catch all otherwise unhandled exceptions
[EXCEPT-06-3]
DESCRIPTION
"If a program throws an unhandled exception it terminates
in an implementation-defined manner. In particular, it is
implementation-defined whether the call stack is unwound, before
termination,
so the destructors of any automatic objects may or may not be executed.
By enforcing the provision of a "last-ditch catch-all", the developer can
ensure that the program terminates in a consistent manner."
Rule checks if outermost statement of the 'main' function is a try
statement
with catch-all handler.

SINCE
v7.2

NOTES
Rule check if a try statement with catch-all handler is implemented
directly
in 'main' function. Statements which are implemented in functions that are
called from 'main' function are not detected.

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
class Exception{};
int main( )
{
try // Violation
{
// ...
}

catch ( Exception e )
{
// ...
}
return 0;
}

REPAIR
class Exception{};
int main( )
{
try // OK
{
// ...
}
catch ( Exception e )
{
// ...
}
catch ( ... )
{
// ...
}
return 0;
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-2
2. http://cwe.mitre.org/data/definitions/391.html

An empty throw (throw;) shall only be used in the compound-statement of a catch handler
[EXCEPT-07-3]
DESCRIPTION
"An empty throw re-throws the temporary object that represents an
exception.
Its use is intended to enable the handling of an exception to be split
across
two or more handlers.
However, syntactically, there is nothing to prevent throw; being used
outside
a catch handler, where there is no exception object to re-throw. This may
lead
to an implementation-defined program termination."

SINCE
v7.2

BENEFITS
Rule prevents implementation-defined behaviour.

EXAMPLE
class Exception{};
void foo(int a)
{
Exception E;
if(a)
{
throw;
// Violation
}
}

REPAIR
class Exception{};
void foo(int a)

{
Exception E;
if(a)
{
throw E;
}

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Exceptions shall be raised only after start-up and before termination of the program [EXCEPT08-3]
DESCRIPTION
"Before the program starts executing the body of main, it is in a start-up
phase, constructing and initializing static objects. Similarly, after main
has
returned, it is in a termination phase where static objects are being
destroyed. If an exception is thrown in either of these phases it leads to
the
program being terminated in an implementation-defined manner."

SINCE
v7.2

NOTES
Rule checks only one level of nested function calls.

BENEFITS
"Throwing an exception during start-up or termination results in the
program
being terminated in an implementation-defined manner."

EXAMPLE
class C
{
public:
C ( )
{
throw ( 0 ); // Violation thrown before main starts
}
~C ( )
{
throw ( 0 ); // Violation thrown after main exits
}

};
C c;
int main( ... )
{
// ...
}

REPAIR
Exceptions should not be throwing during start-up or termination phase.

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

An exception object should not have pointer type [EXCEPT-09-3]


DESCRIPTION
"If an exception object of pointer type is thrown and that pointer refers
to a dynamically created object, then it may be unclear which function
is responsible for destroying it, and when."

SINCE
v7.2

BENEFITS
Prevents memory management problems

EXAMPLE
typedef short int16_t;
class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( &a1 ); // Violation pointer type thrown
}
else
{
throw ( a2 ); // Violation pointer type thrown
}
}

REPAIR
typedef short int16_t;

class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( a1 ); // OK
}
else
{
throw ( *a2 ); // OK
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. ISO/DIS 26262
point 8.4.4

Control shall not be transferred into a try or catch block using a goto or a switch statement
[EXCEPT-10-3]
DESCRIPTION
"A program is ill-formed if control is transferred into a try or catch
block
using a goto or switch statement; however, not all compilers issue
a diagnostic message."

SINCE
v7.2

BENEFITS
Rule detects errors not reported by all compilers

EXAMPLE
/* The code is compilable with MSVC 6.0 */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
try
{
Label_10: // Violation
case 2:
// Violation
break;
}
catch ( Exception e )
{
}
}

REPAIR
/* The example of correct code */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
// OK
try
{
// ...
}
catch ( Exception e )
{
}
case 2:
// OK
break;
}
Label_10:
// OK
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The assignment-expression of a throw statement shall not itself cause an exception to be


thrown [EXCEPT-11-1]
DESCRIPTION
"If an exception is thrown when constructing the exception object, or when
evaluating the assignment expression that initializes the exception
object,
it is that exception that propagates in preference to the one that was
about
to be thrown."

SINCE
v7.2

BENEFITS
Rule improves readability of code

EXAMPLE
class E
{
public:
E ( )
{
throw 10;
}
};
int foo1()
{
try
{
if ( 0 )
{
throw E ( ); // Violation
}
}
catch(...)
{

}
}

REPAIR
class E
{
public:
E ( ){ }
};
int foo()
{
try
{
if ( 0 )
{
throw E ( ); // OK
}
}
catch(...)
{
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

NULL shall not be thrown explicitly [EXCEPT-12-3]


DESCRIPTION
"throw(NULL) (equivalent to throw(0)) is never a throw of the
null-pointer-constant and so is only ever caught by an integer handler.
This may be inconsistent with developer expectations, particularly if
the program only has handlers for pointer-to-type exceptions."

SINCE
v7.2

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
#define NULL 0
void foo()
{
try
{
throw ( NULL ); // Violation
}
catch ( int i )
// NULL exception handled here
{
// ...
}
}

REPAIR
#define NULL 0
void foo()
{
try
{
throw ( 0 ); // OK

}
catch ( int i ) // NULL exception handled here
{
// ...
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [EXCEPT-13-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown from body
of function 'main' or from body of function that does not have any
exception
on an exception specification list.
see also: EXCEPT-18

SINCE
v7.2

NOTES
Rule checks only one level of nested function calls.

BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."

EXAMPLE
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{

if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // Violation
}
}
catch ( A const & )
{
}
}

REPAIR
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // OK
}
}
catch ( A const & )
{
}
catch ( B const & )
{
}
}

REFERENCES

1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Where a function's declaration includes an exception-specification, the function shall only be


capable of throwing exceptions of the indicated type(s) [EXCEPT-14-3]
DESCRIPTION
"If a function declared with an exception-specification throws an
exception
of a type not included in the specification, the function unexpected()
is called. The behaviour of this function can be overridden within a
project,
but by default causes an exception of std::bad_exception to be thrown.
If std::bad_exception is not listed in the exception-specification,
then terminate() will be called, leading to implementation-defined
termination of the program."

SINCE
v7.2

NOTES
Rule checks only two levels of nested function calls

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception )
{
foo ( );
}

// Violation

REPAIR
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception, int ) // OK
{
foo ( );
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A class type exception shall always be caught by reference [EXCEPT-15-3]


DESCRIPTION
"If a class type exception object is caught by value, slicing occurs. That
is,
if the exception object is of a derived class and is caught as the base,
only the base classs functions (including virtual functions) can be
called.
Also, any additional member data in the derived class cannot be accessed."
Rule detects class or struct type exception object that is caught by
value.

SINCE
v7.2

BENEFITS
"If the exception is caught by reference, slicing does not occur."

EXAMPLE
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase b ) // Violation - derived type objects will be
// caught as the base type
{
}
}

REPAIR
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase &b ) // OK - exceptions caught by reference
{
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Handlers of a function-try-block implementation of a class constructor or destructor shall not


reference nonstatic members from this class or its bases [EXCEPT-16-3]
DESCRIPTION
Accessing a non-static member of a class or a base class in the
handler (i.e. the catch part) of a function-try-block of a class
constructor/destructor is not allowed.

SINCE
v7.2

BENEFITS
"The effect of accessing a non-static member of a class or a base class in
the
handler (i.e. the catch part) of a function-try-block of a class
constructor/destructor is undefined. For example, if a memory allocation
exception is thrown during creation of the object, the object will not
exist
when the handler attempts to access its members. Conversely, in the
destructor,
the object may have been successfully destroyed before the exception is
handled, so again will not be available to the handler. By contrast, the
lifetime of a static member is greater than that of the object itself, so
the
static member is guaranteed to exist when the handler accesses it."

EXAMPLE
typedef int int32_t;
class C
{
public:
int32_t x;
C( )
try
{
// Action that may raise an exception
}

catch ( ... ) // Violation


{
if ( 0 == x ) // Non-compliant x may not exist at this point
{
// Action dependent on value of x
}
}
~C ( )
try
{
// Action that may raise an exception
}
catch ( ... ) // Violation
{
if ( 0 == x ) // Non-compliant x may not exist at this point
{
// Action dependent on value of x
}
}
};

REPAIR
Do not use non-static member of a class or a base class in the handler
of a function-try-block of a class constructor/destructor

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Where multiple handlers are provided in a single try-catch statement or function-try-block for
a derived class and some or all of its bases, the handlers shall be ordered most-derived to
base class [EXCEPT-17-3]
DESCRIPTION
"Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases,
the handlers shall be ordered most-derived to base class.
When testing to see if the type of an exception matches the type of a
handler,
a derived class exception will match with a handler for its base class.
If the base class handler is found before the handler for the derived
class,
the base class handler will be used. The derived class handler is
unreachable
code and can never be executed."

SINCE
v7.2

BENEFITS
Rule prevents writing unreachable code.

EXAMPLE
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( B &b )
{
// ...

}
catch ( D &d ) // Violation
{
// ...
}
}

REPAIR
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( D &d ) // OK - Derived class caught before base class
{
// ...
}
catch ( B &b ) // OK - Base class caught after derived class
{
// ...
}
}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [EXCEPT-18-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown while
a non-local object is declared or initialized.
see also: EXCEPT-13

SINCE
v7.2

NOTES
Rule checks only one level of nested function calls.

BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."

EXAMPLE
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10 )
{

throw A ( );
}
else
{
throw B ( );
}
}
catch ( A const & )
{
}
}
};
A a; // Violation - unhandled exception of class B

REPAIR
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10
{
throw A
}
else
{
throw B
}
}
catch ( A const
{
}
catch ( B const
{
}
}
};
A a; // OK

)
( );

( );

& )

& )

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4

FORMAT
Formatting
RULES
Tabs that do not use ASCII spaces shall not be used [FORMAT-01-5]
Place an opening brace '{' on its own line [FORMAT-02-3]
Place a closing brace '}' on its own line [FORMAT-03-3]
Physical lines should be less than eighty characters [FORMAT-04-3]
The length of a macro should not exceed 10 lines [FORMAT-05-3]
Only one statement shall be allowed per line [FORMAT-06-3]
There shall be a single ASCII space character preceding assignment
operators [FORMAT-07-3]
There shall be a single ASCII space character following assignment
operators [FORMAT-08-3]
There shall be a single ASCII space character preceding bitwise operators
[FORMAT-09-3]
There shall be a single ASCII space character following bitwise operators
[FORMAT-10-3]
There shall be a single ASCII space character preceding and following
bitwise operator '&' [FORMAT-11-3]
There shall be a single ASCII space character between a conditional
statement keyword and its opening parenthesis [FORMAT-12-3]
There shall be a maximum of 1 ASCII space character following the opening
parenthesis in conditional statements [FORMAT-13-3]
There shall be a single ASCII space character preceding ternary
conditional operator [FORMAT-14-3]
There shall be a single ASCII space character following ternary
conditional operator [FORMAT-15-3]
There shall be a single ASCII space character preceding and following
relational and equality operators [FORMAT-16-3]
There shall be no white space following '.' or '->' operator [FORMAT-17-3]
There shall be no white space preceding '.' or '->' operator [FORMAT-18-3]
There shall be a single ASCII space character following all commas
[FORMAT-19-3]
There shall be a single ASCII space character following all semicolons
[FORMAT-20-3]
There shall be no white space between a prefix unary operator and its
operand [FORMAT-21-3]
There shall be no white space between a postfix unary operator and its
operand [FORMAT-22-3]
There shall be no white spaces between the "return" or "sizeof "
statements and its opening parenthesis [FORMAT-23-3]
There shall be no white spaces surrounding "return" or "sizeof "
statements argument or expression [FORMAT-24-3]

Parenthesis shall be used with the "return" and "sizeof" statements


[FORMAT-25-3]
There shall be a single ASCII space character preceding and following
logical operators [FORMAT-26-3]
Line should be indented by a multiple of four spaces [FORMAT-27-3]
In a function definition, the return type of the function should be
written on a separate line directly above the function name [FORMAT-28-3]
Multiple variable declarations shall not be allowed on the same line
[FORMAT-29-3]
Place left parenthesis directly after function name [FORMAT-30-3]
Separate logical tests in conditional expressions [FORMAT-31-3]
The dereference operator `*' and the address-of operator `&' should be
directly connected with the type names [FORMAT-32-3]
Each variable should be declared in a separate declaration statement
[FORMAT-33-3]
Braces "{}" which enclose a block should be placed in the same column
[FORMAT-34-3]
When declaring functions, the leading parenthesis and the first argument
are to be written on the same line as the function name [FORMAT-35-3]
Sibling statement lines should be indented to the same level [FORMAT-36-3]
First line in control statement body should be indented more than control
statement keyword [FORMAT-37-3]
When declaring functions with more than 2 parameters, the leading
parenthesis and the first argument are to be written on the same line as
the function name, each additional argument will be written on a separate
line [FORMAT-38-3]
Sort #include directives in alphabetical order [FORMAT-39-4]
White spaces after the opening square bracket '[' and before its closing
square bracket ']' shall be used in consistent way [FORMAT-40-5]
There shall be no space between '[' opening square bracket and preceding
token [FORMAT-41-5]

Tabs that do not use ASCII spaces shall not be used [FORMAT-01-5]
DESCRIPTION
This rule checks whether you are using only ASCII white spaces as tabs.
Different operating systems, display devices, and editors handle tabs
in different ways. Code containing tabs will likely be indented
incorrectly
if ported to another environment.

BENEFITS
Rule prevents inconsistent display of code containing tabs
in different environments.

EXAMPLE
void foo()
{
int i; // Violation
}

REPAIR
void foo()
{
int j; // OK
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 43

Place an opening brace '{' on its own line [FORMAT-02-3]


DESCRIPTION
The rule reports a violation if an opening brace '{' is not placed
on separate line.
See also: FORMAT-03, FORMAT-34

EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//

initializations and empty blocks.


OK
OK
OK

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class A1
{ int a;
};
struct S1 {
int a;
};

// Violation

// Violation

REPAIR
class A1
{
int a;
};
struct S1
{
int a;
};

// OK

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61

Place a closing brace '}' on its own line [FORMAT-03-3]


DESCRIPTION
The rule reports a violation if a closing brace '}' is not placed
on separate line.
See also: FORMAT-02, FORMAT-34

EXCEPTIONS
Rule does not adhere to enums, initializations and empty blocks.
It is allowed to place tokens after '}' in the same line if:
- '}' ends 'do-while' construct
- '}' ends declaration of class/structure/union/enum

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
int goo(int i)
{
if (i == 0) { return i; }
// Violation
do { i++; } while (i < 10); // Violation
}
struct S{ int i; float f; }ss;

REPAIR
int goo(int i)
{
if (i == 0)
{
return i;
}
// OK
do
{
i++;

// Violation

} while (i < 10); // OK - Exception


}
struct S
{
int i;
float f;
}ss;

// OK - Exception

enum E {EN1 = 2, EN2 = 1};


int array[] = {1,2,3,4,5};
class FooBar{};

// OK - Exception
// OK - Exception
// OK - Exception

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61

Physical lines should be less than eighty characters [FORMAT-04-3]


DESCRIPTION
This rule checks that physical lines are less than eighty characters. This
rule
promotes readability across various editors. Additionally, some printers
will
not print columns greater than 80 columns. Tab is counted as one
character.

BENEFITS
Rule improves readability of code.

EXAMPLE
const int MAXIMUM_LIMIT = 100;
void foo()
{
int someLocalVariableHoldingTheLimit = (MAXIMUM_LIMIT * 10) (MAXIMUM_LIMIT/2); // Violation
}

REPAIR
const int MAXIMUM_LIMIT = 100;
void foo()
{
int someLocalVariableHoldingTheLimit = (MAXIMUM_LIMIT * 10) (MAXIMUM_LIMIT/2); // OK
}

REFERENCES
Recommended by ParaSoft

The length of a macro should not exceed 10 lines [FORMAT-05-3]


DESCRIPTION
This rule checks whether the length of a macro exceeds 10 lines.
Macros over 10 lines are hard to read.

BENEFITS
Readability.

EXAMPLE
// Violation
#define SUM(\
PARAMETER_1,\
PARAMETER_2,\
PARAMETER_3,\
PARAMETER_4)\
(\
PARAMETER_1+\
PARAMETER_2+\
PARAMETER_3+\
PARAMETER_4\
)
void main()
{
int val = SUM(1,1,1,1);
}

REPAIR
// OK
#define SUM( PARAMETER_1, PARAMETER_2, PARAMETER_3, PARAMETER_4)\
(\
PARAMETER_1 + PARAMETER_2 + PARAMETER_3 + PARAMETER_4\
)
void main()
{

int val = SUM(1,1,1,1);


}

REFERENCES
Recommended by ParaSoft

Only one statement shall be allowed per line [FORMAT-06-3]


DESCRIPTION
This rule checks that there is only one statement per line.

BENEFITS
This rule promotes readability and maintainability by reducing code
complexity.

EXAMPLE
void foo()
{
int i; char c; // Violation
}

REPAIR
void foo()
{
int ii; // OK
char cc;
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 42

There shall be a single ASCII space character preceding assignment operators [FORMAT-07-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character preceding assignment operators.
See also: FORMAT-08

BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.

EXAMPLE
int y =
int z=1;

1; // Violation
// Violation

REPAIR
int x = 1; // OK

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character following assignment operators [FORMAT-08-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character following assignment operators.
See also: FORMAT-07

BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.

EXAMPLE
int y =
int z=1;

1; // Violation
// Violation

REPAIR
int x = 1; // OK

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character preceding bitwise operators [FORMAT-09-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character preceding bitwise operators.
See also: FORMAT-10, FORMAT-11

BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.

EXAMPLE
void foo()
{
int z = 73;
int y=0;
y=z|0x0f; // Violation
y=z | 0x0f; // Violation
}

REPAIR
void foo()
{
int z = 73;
int y=0;
y=z | 0x0f; // OK
}

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character following bitwise operators [FORMAT-10-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character following bitwise operators.
See also: FORMAT-09, FORMAT-11

BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.

EXAMPLE
void foo()
{
int z = 73;
int y=0;
y=z|0x0f; // Violation
y=z | 0x0f; // Violation
}

REPAIR
void foo()
{
int z = 73;
int y=0;
y=z | 0x0f; // OK
}

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character preceding and following bitwise operator '&'
[FORMAT-11-3]
DESCRIPTION
This rule checks whether there is a single ASCII space character
preceding and following bitwise operator &.
See also: FORMAT-09, FORMAT-10

SINCE
v7.0

BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.

EXAMPLE
void Space( ) {
int z = 73;
int y = 0;
y
y
y
y
y

=
=
=
=
=

z & y;
z & y;
z& y;
z &y;
z&y;

//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
void Space( ) {
int z = 73;
int y = 0;
y = z & y;
}

// OK

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character between a conditional statement keyword and
its opening parenthesis [FORMAT-12-3]
DESCRIPTION
The rule reports a violation if between a conditional statement keyword
and its opening parenthesis:
- there is no space
- there is more than one space
- there is a tab or comment
or the opening parenthesis is not in the same line as conditional
statement
keyword.
As conditional statement keywords are recognized: if, for, switch, while
See also: FORMAT-13

BENEFITS
The rule improves readability of code.

EXAMPLE
void foo(int x, int y)
{
if(x < y){}
/* Violation
if (x > y){}
/* Violation
for(;;);
/* Violation while
(x < 10)
/* Violation
x++;
do{ /* .. */ }while(y > 1); /* Violation
}

REPAIR
void foo(int x, int y)
{
if (x < y){}
if (x > y){}
for (;;);
while (x < 10)

/*
/*
/*
/*

OK
OK
OK
OK

*/
*/
*/
*/

- no space */
- two spaces */
tab is used */
*/
*/

x++;
do{ /* .. */ }while (y > 1); /* OK */
}

REFERENCES
Recommended by ParaSoft

There shall be a maximum of 1 ASCII space character following the opening parenthesis in
conditional statements [FORMAT-13-3]
DESCRIPTION
This rule checks whether there is a maximum of 1 ASCII space
character following the opening parenthesis in conditional
statements: for, if, switch, while.
See also: FORMAT-12

BENEFITS
A maximum of 1 ASCII space after the opening
parenthesis improves readability.

EXAMPLE
void foo()
{
int x=1;
int y=1;
if(
{
}

x == y

) // Violation

REPAIR
void foo()
{
int x=1;
int y=1;
if (x == y) // OK
{
}
if ( x == y ) // OK
{
}

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character preceding ternary conditional operator
[FORMAT-14-3]
DESCRIPTION
This rule checks that there is a single ASCII space character
preceding ternary conditional operator.
See also: FORMAT-15

BENEFITS
This convention promotes readability by clearly separating
the operands from the operator.

EXAMPLE
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
j = ( i < 0 )?( -i ) : ( i );
}

// Violation
// Violation

REPAIR
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
}

REFERENCES
Recommended by ParaSoft

// OK

There shall be a single ASCII space character following ternary conditional operator
[FORMAT-15-3]
DESCRIPTION
This rule checks whether there is a single ASCII space character
following ternary conditional operator.
See also: FORMAT-14

BENEFITS
This convention promotes readability by clearly separating
the operands from the operator.

EXAMPLE
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
j = ( i < 0 )?( -i ) : ( i );
}

// Violation
// Violation

REPAIR
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
}

REFERENCES
Recommended by ParaSoft

// OK

There shall be a single ASCII space character preceding and following relational and equality
operators [FORMAT-16-3]
DESCRIPTION
This rule checks whether there is a single ASCII space character
preceding and following relational and equality operators.

BENEFITS
This convention promotes readability by clearly separating
the operands from the operator.

EXAMPLE
void foo(int x)
{
if(x==1)
// Violation
{
}
if(x
{
}

>

if(x <=1)
{
}

1)

// Violation

// Violation

REPAIR
void foo(int x)
{
if(x == 1)
// OK
{
}
if(x > 1)
{
}

// OK

if(x <= 1)
{
}

// OK

REFERENCES
Recommended by ParaSoft

There shall be no white space following '.' or '->' operator [FORMAT-17-3]


DESCRIPTION
The rule reports a violation if there is a space or tab character
immediately following '.' or '->' operators.
See also: FORMAT-18

NOTES
The violation is not reported if '.' or '->' is last in line ignoring
white spaces, comments and backslashes. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.

BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.

EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj.
x;
/* Violation */
myObjPtr-> x; /* Violation */
}
#define MACRO a. b /* Violation */

REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {

myObj.x;
/* OK */
myObjPtr->
/* OK: '->' is last in line*/
x;
myObj./*comment*/ x; /* OK: no space immediately after '.' */
}
#define MACRO a. /* OK: '.' is last in line */ \
b
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif

REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

There shall be no white space preceding '.' or '->' operator [FORMAT-18-3]


DESCRIPTION
The rule reports a violation if there is a space or tab character
immediately preceding '.' or '->' operators.
See also: FORMAT-17

NOTES
The Violation is not reported if '.' or '->' is first in line ignoring
white spaces and comments. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.

BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.

EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj
.x;
/* Violation */
myObjPtr ->x; /* Violation */
}
#define MACRO a .b /* Violation */

REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {

myObj.x;
/* OK */
myObjPtr
->x;
/* OK: '->' is first in line*/
myObj /*comment*/.x; /* OK: no space immediately before '.' */
}
#define MACRO a \
.b /* OK: '.' is first in line */
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif

REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

There shall be a single ASCII space character following all commas [FORMAT-19-3]
DESCRIPTION
This rule checks whether there is a single ASCII
space character following all commas.

BENEFITS
Since commas delineate individual statements, a space shall be used
to highlight this fact. This greatly improves the readability of 'C'.

EXAMPLE
void foo()
{
int xx,yy;
// Violation
int xxx, yyy; // Violation
}

REPAIR
void foo()
{
int x, y; // OK
}

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character following all semicolons [FORMAT-20-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character following all semicolons.

BENEFITS
Since semicolons delineate individual statements, a space shall be used
to highlight this fact. This greatly improves the readability of 'C'.

EXAMPLE
void foo()
{
int i;
for ( i = 0;i <= 10;i++) // Violation
{
}
}

REPAIR
void foo()
{
int i;
for ( i = 0; i <= 10; i++) // OK
{
}
}

REFERENCES
Recommended by ParaSoft

There shall be no white space between a prefix unary operator and its operand [FORMAT-21-3]
DESCRIPTION
This rule checks whether there is no white space between a prefix unary
operator
and its operand. This promotes continuity in the relationship between
the operators and their associated operand. These operators act solely on
their
operand and cannot be considered separately from it.

BENEFITS
Improves readability.

EXAMPLE
void foo()
{
int i=0;
-- i; // Violation
}

REPAIR
void foo()
{
int i=0;
--i;
// OK
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

There shall be no white space between a postfix unary operator and its operand [FORMAT-223]
DESCRIPTION
This rule checks whether there is no white space between a postfix unary
operator and its operand. This promotes continuity in the relationship
between the operators and their associated operand. These operators
act solely on their operand and cannot be consider separately from it.

BENEFITS
Improves the readability of code.

EXAMPLE
void foo()
{
int y = 0;
y ++;
}

// Violation

REPAIR
void foo()
{
int y = 0;
y++;
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

There shall be no white spaces between the "return" or "sizeof " statements and its opening
parenthesis [FORMAT-23-3]
DESCRIPTION
This rule checks for white spaces between the "return" and "sizeof"
statements.
See also: FORMAT-24, FORMAT-25

BENEFITS
Improves the readability of code.

EXAMPLE
void foo()
{
sizeof (int); // Violation
}

REPAIR
void foo()
{
sizeof(int); // OK
}

REFERENCES
Recommended by ParaSoft

There shall be no white spaces surrounding "return" or "sizeof " statements argument or
expression [FORMAT-24-3]
DESCRIPTION
This rule checks whether there are no white spaces between
the "return" and "sizeof" statements, arguments, or expressions.
See also: FORMAT-23, FORMAT-25

BENEFITS
Improves the readability of code.

EXAMPLE
void foo()
{
sizeof( int ); // Violation
}

REPAIR
void foo()
{
sizeof(int); // OK
}

REFERENCES
Recommended by ParaSoft

Parenthesis shall be used with the "return" and "sizeof" statements [FORMAT-25-3]
DESCRIPTION
This rule checks whether parentheses are used with
the "return" and "sizeof" statements.
See also: FORMAT-23, FORMAT-24

BENEFITS
Improves the readability of code.

EXAMPLE
#define true 1
#define false 0
int foo()
{
return true; // Violation
}

REPAIR
#define true 1
#define false 0
int goo()
{
return(true); // OK
}
void xoo()
{
return;
}

// OK

REFERENCES
Recommended by ParaSoft

There shall be a single ASCII space character preceding and following logical operators
[FORMAT-26-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character preceding and following logical operators.

BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.

EXAMPLE
void foo()
{
int x = 1;
int y = 1;
if(x||y)
{
}
if(x
{
}

||

// Violation

y) // Violation

REPAIR
void foo()
{
int x = 1;
int y = 1;
if(x || y) // OK
{
}
}

REFERENCES
Recommended by ParaSoft

Line should be indented by a multiple of four spaces [FORMAT-27-3]


DESCRIPTION
Each line should be indented by a multiple of four spaces.
See also: FORMAT-34, FORMAT-36, FORMAT-37

NOTES
- Rule treats tab characters as alignment to correct column indentation.
- Rule does not check indentation for lines which are in context
of "()" or "[]" or line which starts with preprocessor directives.
- Rule can be parameterized by changing values of the following variables
in Python scripts:
- Variable "IndentSize" contains the size of indentation in spaces.
- Variable "TabSize" contains the size of tab character in spaces.
- Both variables are set to 4.

BENEFITS
Improves readability of code.

EXAMPLE
class A {
};
void foo(){
}
class B {
int a;
int b;
};

// Violation
// Violation
// Violation
// Violation
// Violation

/** Violation - Incorrect first line of comment indentation


* ...
*/
void koo( int x){
if (x == 0 ||
x == 1){
// OK - in context of "()"
x = 1;
// Violation

x = 2;

// Violation

}
}

REPAIR
class A {
};
void foo(){
}
class B {
int a;
int b;
};

// OK
// OK
// OK
// OK
// OK

/** OK - Correct first line of comment indentation


* ...
*/
void koo( int x){
if (x == 0 ||
x == 1){
// OK - in context of "()"
x = 1;
// OK
x = 2;
// OK
}
}

REFERENCES
Recommended by ParaSoft

In a function definition, the return type of the function should be written on a separate line
directly above the function name [FORMAT-28-3]
DESCRIPTION
"In function definition, the return type of the function should be written
on a separate line directly above the function name."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
int foo() {
return 0;
}

// Violation

REPAIR
int
foo() {
return 0;
}

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.2 Functions - Rec. 22

Multiple variable declarations shall not be allowed on the same line [FORMAT-29-3]
DESCRIPTION
Rule triggers if some variables are declared on the same line.
See also: FORMAT-33

NOTES
Violation is not reported if variables are declared by macros.

BENEFITS
Rule increases readability and prevents confusion.

EXAMPLE
void foo( ) {
int a, b;
}

// Violation

REPAIR
void foo( ) {
int a;
int b;
}

// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.19 Variables, AV Rule 152

Place left parenthesis directly after function name [FORMAT-30-3]


DESCRIPTION
"Always write the left parenthesis directly after a function name."

BENEFITS
Rule improves readability of code.

EXAMPLE
void
foo () {// Violation
}

REPAIR
void
foo() {// OK
}

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.2 Functions - Rec. 23

Separate logical tests in conditional expressions [FORMAT-31-3]


DESCRIPTION
To aid in readability, explicit logical tests should be separated
in conditional expressions.

BENEFITS
Makes code more readable.

EXAMPLE
void foo( int j, int i) {
if (i != j > 0) {}
}

// Violation

REPAIR
void foo( int j, int i) {
if (i != j && j > 0) {}
}

// OK

REFERENCES
Motorola Coding Standards G-12

The dereference operator `*' and the address-of operator `&' should be directly connected with
the type names [FORMAT-32-3]
DESCRIPTION
"The dereference operator * and the "address-of" operator & should be
directly connected to the type names in declaration and definition."

BENEFITS
Rule makes source code more readable.

EXAMPLE
void foo() {
int k=42;
int *p1;// Violation
int &r1 = k;// Violation
}

REPAIR
void foo() {
int k=42;
int* p2;// OK
int& r2 = k;// OK
}

REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#6.5
from: 6 Style - 6.4 Pointers and References - Rec. 26
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 62

Each variable should be declared in a separate declaration statement [FORMAT-33-3]


DESCRIPTION
"Each variable is to be declared in a separate declaration statement."
Determining the types of variables becomes confusing when pointers and
access
specifiers are used for multiple declarations in the same statement.
See also: FORMAT-29

BENEFITS
Rule prevents confusion and makes source code more readable.

EXAMPLE
void foo( )
{
int* a, b;
}

// Violation

REPAIR
void foo( )
{
int* a;
int b;
}

// OK
// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 39, 6 Style - 6.5 Pointers and References Rec. 26
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-0-1

Braces "{}" which enclose a block should be placed in the same column [FORMAT-34-3]
DESCRIPTION
Rule checks if opening and closing braces are placed in the same column.
See also: FORMAT-02, FORMAT-03

EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//
Rule does not report violation

initializations and empty blocks.


OK
OK
OK
if in line with brace 'tab' is used.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class Foobar {
int a;
};

// Violation

struct S1 {
int a;
};

// Violation

REPAIR
class Foobar
{
int a;
};
struct S1
{
int a;
};

// OK

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 60

When declaring functions, the leading parenthesis and the first argument are to be written on
the same line as the function name [FORMAT-35-3]
DESCRIPTION
"When declaring functions, the leading parenthesis and the first argument
(if any) are to be written on the same line as the function name."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
void foo
( );
void goo(
int a );

// Violation
// Violation

REPAIR
void foo( );

// OK

void goo( int a );

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.2 Functions - Rec. 21

Sibling statement lines should be indented to the same level [FORMAT-36-3]


DESCRIPTION
Two statements in the same block coming one after another should be
indented
to the same level.
See also: FORMAT-27, FORMAT-37

SINCE
v7.1

NOTES
- Rule treats tab characters as an alignment to correct column
indentation.
- Rule does not check indentation for lines which are in context
of "()" or "[]" or lines which start with preprocessor directives.
- Rule can be parameterized by changing value of the "TabSize" variable
in Python scripts (by default it is set to 4 spaces).

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x ) {
if (x == 0) {
}
x = 2;
x = 2;
// Violation
x = 2;
// Violation
x = 2;
// Violation
x = 2;
// Violation
}

REPAIR
void foo( int x ) {
if (x == 0) {
}
x = 2;
// OK
x = 2;
// OK
x = 2;
// OK
x = 2;
// OK
x = 2;
// OK
}

REFERENCES
Recommended by ParaSoft

First line in control statement body should be indented more than control statement keyword
[FORMAT-37-3]
DESCRIPTION
First line in control statement body (if, else, while, do while, for,
switch, try, catch, case, default) should be indented more than
control statement keyword.
See also: FORMAT-27, FORMAT-36

SINCE
v7.1

NOTES
- Rule does not check indentation for lines which starts with preprocessor
directives.
- Rule can be parameterized by changing values of the following variables
in Python scripts:
"MinIndentSize" - the minimum admissible size of indentation in spaces
"MaxIndentSize" - the maximum admissible size of indentation in spaces
"TabSize"
- size of tab character in spaces
All variables are set to 4 by default.
For example: MinIndentSize = 2, MaxIndentSize = 4:
while (x == 0)
x = 1;
// OK - indent size = 2
while (x == 0)
x = 1;
// OK - indent size = 3
while (x == 0)
x = 1;
// OK - indent size = 4

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x ) {
while (x == 0)
x = 1;
// Violation
if (x == 0) {
x++;
// Violation
x++;
}
}

REPAIR
void foo( int x ) {
while (x == 0)
x = 1;
// OK
if (x == 0) {
x++;
// OK
x++;
}
}

REFERENCES
Recommended by ParaSoft

When declaring functions with more than 2 parameters, the leading parenthesis and the first
argument are to be written on the same line as the function name, each additional argument
will be written on a separate line [FORMAT-38-3]
DESCRIPTION
When declaring and defining functions with more than two parameters,
the leading parenthesis and the first argument will be written on
the same line as the function name. Each additional argument will
be written on a separate line (with the closing parenthesis directly
after the last argument).

SINCE
v7.1

BENEFITS
Readability and style.

EXAMPLE
void foo(int a, int b, int c);// Violation
void zoo(
int a, int b,
int c
)
{

// Violation
// Violation
// Violation

REPAIR
void foo(int a,
int b,
int c);
void zoo( int a,
int b,

// OK

int c)

// OK

{
}
void goo(int a, int b); // OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 58

Sort #include directives in alphabetical order [FORMAT-39-4]


DESCRIPTION
Rule checks if #include directives are sorted. A violation is reported
if #include in previous line has name which sorts after #include in
current line.

SINCE
v9.2

NOTES
<header> includes are not compared with "header" includes.
Two includes are compared only if they are in consequent lines.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
#include "zheader2.h"
#include "zheader1.h" // Violation
// this line have no #include
#include "zheader0.h" // ok - previous include not in previous line
#include <iostream> // ok - <header> not compared with "header"
#include <algorithm> // Violation

REPAIR
#include
#include
#include
#include
#include

"zheader0.h"
"zheader1.h"
"zheader2.h"
<algorithm>
<iostream>

White spaces after the opening square bracket '[' and before its closing square bracket ']' shall
be used in consistent way [FORMAT-40-5]
DESCRIPTION
The rule checks if after the opening square bracket '[' and before the
closing
square bracket ']' the white spaces are used in consistent way.
See also: FORMAT-41

SINCE
v9.2

NOTES
It is possible to adapt this rule to standard that allows or disallows to
use
white spaces after '[' and before ']'. The modification can be done in
python
method 'formatRule'. To variable 'format' should be assigned the string
containing the preferred format.
There are three possibilities:
1. format = "[ 1 ] or [1]" (the default)
In this case there are two correct patterns:
- at least one white space both after the opening square brace '[' and
before the closing square brace ']'
- no white space neither after the opening square brace '[' nor before
the closing square brace ']'. For example:
int a1[1];
// OK
int a2[ 1]; // Violation
int a3[1 ]; // Violation
int a4[ 1 ]; // OK
2. format = "[1]"
In this case should be no white space neither after the opening square
brace '[' nor before the closing square brace ']'. For example:
int a1[1];
// OK
int a2[ 1]; // Violation

int a3[1 ]; // Violation


int a4[ 1 ]; // Violation
3. format = "[
In this case
square brace
int a1[1];
int a2[ 1];
int a3[1 ];
int a4[ 1 ];

1 ]"
there should be at least one white space after the opening
'[' and before the closing square brace ']'. For example:
// Violation
// Violation
// Violation
// OK

BENEFITS
The rule improves readability of code.

EXAMPLE
// the default format:
int tab[ 10]; /* Violation */
void foo() {
tab[0 ] = 0; /* Violation */
}

REPAIR
// the default format:
int tab[10];
/* OK - space removed */
void foo() {
tab[ 0 ] = 0; /* OK - space added */
}

REFERENCES
Recommended by Parasoft

There shall be no space between '[' opening square bracket and preceding token [FORMAT-415]
DESCRIPTION
The rule reports a violation if:
- there is a space, tab or comment preceding opening square bracket ('[')
- an opening square bracket ('[') is first token in line.
The intention of this rule is to have the bracket "glued" together
with preceding token.
See also: FORMAT-17, FORMAT-18, FORMAT-40

SINCE
v9.2

EXCEPTIONS
No violation is reported for following code:
const char special[256] = {
[0] = 1, ['?'] = 1,
['x'] = 1 };

BENEFITS
The rule improves readability of code.

EXAMPLE
int tab [10];
/* Violation */
void foo(int param []) {
/* Violation */
char* arr = new char [10]; /* Violation */
tab/*comment*/[0] = 0;
/* Violation */
tab
[0] = 0;
/* Violation */
delete [] arr;
/* Violation */
}

REPAIR
int tab[10];
void foo(int param[]) {
char* arr = new char[10];
tab[0] = 0;
delete[] arr;
}

REFERENCES
Recommended by Parasoft

/* OK */
/* OK */
/* OK */
/* OK */
/* OK */

INIT
Initialization
RULES
Headers should not contain any initialization [INIT-01-3]
Do not initialize unsigned integer variables with signed constants [INIT02-3]
Initialize all variables [INIT-03-3]
Initialize all pointer variables [INIT-04-2]
Do not initialize a reference to an object whose address can be changed
[INIT-05-1]
All member variables should be initialized in constructor [INIT-06-1]
Make class members' initialization explicit by providing user-defined
constructor [INIT-07-3]
User-defined constructor must be provided to ensure the proper
initialization of dynamically allocated class objects [INIT-08-3]
Initialize static class members [INIT-09-1]
List members in an initialization list in the order in which they are
declared [INIT-10-3]
Assign to all data members in operator= [INIT-11-2]
Avoid initialization order problems across translation units [INIT-12-3]
Do not assume that members are initialized in any special order in
constructors [INIT-13-3]
Prefer initialization to assignment in constructors [INIT-14-5]

Headers should not contain any initialization [INIT-01-3]


DESCRIPTION
Header should not contain initialization of anything. Putting
initialization
in header doesn't make clear which function "own" the data; i.e., it
doesn't
localize the "defining instance". Multiple source files each including a
file
containing initializations will, in general, produce "multiply defined"
diagnostics.

NOTES
Rule is designed for C code.

BENEFITS
Rule prevents producing "multiply defined" diagnostics.

EXAMPLE
// header file
int i = 0;// Violation

REPAIR
// header file
int i;// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not initialize unsigned integer variables with signed constants [INIT-02-3]


DESCRIPTION
The rule reports a violation if unsigned integer variable is initialized
by numeric constant with a negative value.
See also: PB-08, MISRA2004_10_1_h

BENEFITS
The rule prevents undesirable implicit conversions.

EXAMPLE
struct S {
unsigned int m_i;
};
void foo()
{
unsigned int y = -21;
S s = {-10};
}

// Violation
// Violation

class A {
public:
A();
private:
unsigned int ai;
};
A::A() : ai(-10){
}

REPAIR
struct S {
unsigned int m_i;
signed int n_i;
};

// Violation

void foo()
{
unsigned int y = 21;
signed int x = -21;
S s = { 10, -10};
}

// OK
// OK
// OK

class A {
public:
A();
private:
unsigned int ai;
signed int si;
};
A::A() : ai(10), si(-10){
}

// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
2. ISO/DIS 26262
point 8.4.4

Initialize all variables [INIT-03-3]


DESCRIPTION
"A variable must always be initialized before use. Normally, the compiler
gives
a warning if a variable is undefined. It is then sufficient to take care
of
such cases. Instances of a class are usually initialized even if no
arguments
are provided in the declaration (the empty constructor is invoked). To
declare
a variable that has been initialized in another file, the keyword extern
is always used.
By always initializing variables, instead of assigning values to them
before
they are first used, the code is made more efficient since no temporary
objects
are created for the initialization. For objects having large amounts of
data,
this can result in significantly faster code."

EXCEPTIONS
Exception to this rule are 'volatile' data, non-primitive types, and
arrays.

BENEFITS
Prevents reading from uninitialized variables.

EXAMPLE
int a;
void foo( ) {
int b;
}

// Violation

// Violation

REPAIR
int a = 0;
void foo( ) {
int b = 0;
}

// OK

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 142
4. http://cwe.mitre.org/data/definitions/457.html
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
6. ISO/DIS 26262
point 8.4.4

Initialize all pointer variables [INIT-04-2]


DESCRIPTION
This rule checks if all of your pointer variables are initialized.

NOTES
This rule enforces a good coding standard practice: always initialize
pointer
variables, even if you're going to change (assign) the variable at once.

BENEFITS
Initializing pointer variables prevents dereferencing of uninitialized
pointers.

EXAMPLE
void foo(int y, int * p)
{
int *i; // Violation
int *j; // Violation
if (y) {
j = 0;
} else {
j = p;
}
}

REPAIR
void foo(int y, int * p)
{
int *i = 0;
// OK
int *j = y ? 0 : p; // OK
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 19
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. ISO/DIS 26262
point 8.4.4

Do not initialize a reference to an object whose address can be changed [INIT-05-1]


DESCRIPTION
Do not initialize a reference to refer to the object whose address
can be changed. The reference to an object in the free store can
be deleted via a pointer, and consequently can refer to the object
whose address can be null.

BENEFITS
Prevents illegal accessing to not existing variable which was free
previously.

EXAMPLE
void foo()
{
int *ptr = 0;
int &rptr = *ptr; // Violation
}

REPAIR
void foo()
{
int ptr = 0;
int &rptr = ptr; // OK
}

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

All member variables should be initialized in constructor [INIT-06-1]


DESCRIPTION
Constructors should initialize all member variables.
The rule checks if a member variable is initialized:
- in constructor initialization list
- inside body of constructor
- inside body of function called from constructor (three levels of nested
function's calls are checked).
See also: INIT-10, INIT-14, MISRA-030

NOTES
The rule assumes that member variable might be initialized
by passing its non-const pointer to an external function.

BENEFITS
Prevents reading from uninitialized variables.

EXAMPLE
class C
{
public:
C( );
private:
int mem_a;
int mem_b;
int mem_c;
int mem_d;
int mem_e;
};
C::C( ) // Violation - mem_a, mem_b, mem_c, mem_d, mem_e - not initialized
{
}

REPAIR
class C
{
public:
C( );
void init();
void init2();
void getPtr(int *);
private:
int mem_a; // initialized in constructor initialization list
int mem_b; // initialized inside constructor body
int mem_c; // initialized inside function 'init' called from
constructor
int mem_d; // initialized inside function 'init2' called from 'init'
int mem_e; // its non-const pointer is passed to an external function.
};
void C::init()
{
mem_c = 2;
init2();
}
void C::init2()
{
mem_d = 2;
}

C::C( ) : mem_a( 0 ) // OK - all members are initialized


{
mem_b = 1;
init();
getPtr(&mem_e);
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4

2. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. ISO/DIS 26262
point 8.4.4

Make class members' initialization explicit by providing user-defined constructor [INIT-07-3]


DESCRIPTION
This rule verifies that class type variables are properly initialized
by checking if user-defined constructor is provided. If you do not write
at least one constructor in a class, the compiler will write a public
constructor for you by default.
This rule detects if you do not define at least one constructor.

NOTES
Classes that have only static members or no members at all are omitted
by this rule.

BENEFITS
If you follow this rule, you will make class initialization explicit and
prevent the compiler from initializing members improperly, especially
pointer members.

EXAMPLE
class B
{
public:
static int s;
int b;
int a;
};
int main()
{
B bb;
// Violation
return 0;
}

REPAIR
class A
{

public:
A(){}
private:
static int w;
int b;
int a;
};
class C // OK
{
public:
int foo();
void qwe(int x);
};
class D // OK
{
public:
static int s;
static int b;
static int a;
};
int main()
{
C cc; // OK
A a;
// OK
D dd; // OK
return 0;
}

REFERENCES
Recommended by ParaSoft

User-defined constructor must be provided to ensure the proper initialization of dynamically


allocated class objects [INIT-08-3]
DESCRIPTION
This rule verifies that dynamically allocated class objects are properly
initialized by checking if user-defined constructor is provided. If you
do not write at least one constructor in a class, the compiler will
write a public constructor for you by default.
This rule detects if you do not define at least one constructor.

NOTES
Classes that have only static members or no members at all are omitted
by this rule.

BENEFITS
If you follow this rule, you will make class initialization explicit and
prevent the compiler from initializing members improperly, especially
pointer members.

EXAMPLE
class B
{
public:
static int s;
int b;
int a;
};
B* foo(B* b)
{
B* a=new B(); // Violation
return new B(); // Violation
}
int main()
{
foo(new B()); // Violation
return 0;

REPAIR
class A
{
public:
A(){}
static int w;
int b;
int a;
};
A* foo2()
{
A* a=new A(); // OK
return new A(); // OK
}

REFERENCES
Recommended by ParaSoft

Initialize static class members [INIT-09-1]


DESCRIPTION
All static member variables should be initialized.

SINCE
v7.0

BENEFITS
Prevents reading from uninitialized variables.

EXAMPLE
class C{
const static int a; // Violation
static int b;
};
int C::b; // Violation

REPAIR
class C{
const static int a = 0;
static int b;
};

// OK

const int C::a;


int C::b = 0;

// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

2. ISO/DIS 26262
point 8.4.4

List members in an initialization list in the order in which they are declared [INIT-10-3]
DESCRIPTION
"Recall that the destructors for the members of an object are always
called
in the inverse order of their constructors. Thus, if members were
initialized
in the order of their appearance in an initialization list, compilers
would
have to keep track of the order in which the members were initialized for
each
object, just to ensure that the destructors would be called in the right
order.
That would be an expensive proposition. To avoid that overhead, the order
of construction and destruction is the same for all objects of a given
type,
and the order of members in an initialization list is ignored."
In example section variable b from class A will not be initialized as we
assumed (initialized by the same value).
See also: INIT-06, INIT-14, MISRA-030

BENEFITS
Prevents access to null pointer when memory is not allocated.

EXAMPLE
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int b;
int a;
};
class B : public A {
public:
B( int );
private:
int a;
float b;

// Violation - b is declared before a

};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}
before b

// Violation - a is declared

REPAIR
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int a;
int b;
};

// OK - a is declared before b

class B : public A {
public:
B( int );
private:
float b;
int a;
};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}

// OK - b is declared before a

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 13
3, JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 75
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Assign to all data members in operator= [INIT-11-2]


DESCRIPTION
If you write operator=, this rule ensures that you assigned to every
data member of your object.
The rule checks if a member variable is initialized:
- inside body of assignment operator
- inside body of function called from assignment operator
(three levels of nested function's calls are checked).
See also: MRM-43

NOTES
The rule assumes that member variable might be initialized
by passing its non-const pointer to an external function.

BENEFITS
Assign to all member variables in operator= function in order to prevent
data corruption.

EXAMPLE
class C
{
public:
C& operator=(const C&);
private:
int mem_a;
int mem_b;
int mem_c;
int mem_d;
};
C& C::operator=(const C&) // Violation - mem_a, mem_b, mem_c, mem_d - not
assigned
{
}

REPAIR
class C
{
public:
C& operator=(const C&);
void init();
void init2();
void getPtr(int *);
private:
int mem_a; // assigned inside operator= body
int mem_b; // assigned inside function 'init' called from operator=
int mem_c; // assigned inside function 'init2' called from 'init'
int mem_d; // its non-const pointer is passed to an external function.
};
void C::init()
{
mem_b = 2;
init2();
}
void C::init2()
{
mem_c = 2;
}
C& C::operator=(const C&) // OK - all members are assigned
{
mem_a = 1;
init();
getPtr(&mem_d);
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 12
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,

Chapter: "Constructors, Destructors, and Assignment Operators", Item 16


3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid initialization order problems across translation units [INIT-12-3]


DESCRIPTION
"If initialization of a non-local static object in one translation
unit uses a non-local static object in a different translation
unit, the object it uses could be uninitialized, because the
relative order of initialization of non-local static objects
defined in different translation units is undefined.
Fortunately, a small design change eliminates the problem
entirely. All that has to be done is to move each non-local
static object into its own function, where it's declared
static. These functions return references to the objects
they contain. Clients then call the functions instead
of referring to the objects. In other words, non-local
static objects are replaced with local static objects."

SINCE
v7.0

BENEFITS
"This approach is founded on C++'s guarantee that local
static objects are initialized when the object's definition
is first encountered during a call to that function. So if
you replace direct accesses to non-local static objects
with calls to functions that return references to local
static objects, you're guaranteed that the references you
get back will refer to initialized objects. As a bonus, if you
never call a function emulating a non-local static object,
you never incur the cost of constructing and destructing
the object, something that can't be said for true non-local
static objects."

EXAMPLE
#include <iostream>
using namespace std;
class FileSystem {

public:
size_t numDisks( ) const;
};
extern FileSystem tfs;
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_tfs = tfs.numDisks( );
}
Directory tempDir( );

// Violation

REPAIR
#include <iostream>
using namespace std;
class FileSystem {
public:
size_t numDisks( ) const;
};
FileSystem& tfs_one( ) {
static FileSystem fs;
return fs;
}
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_one = tfs_one().numDisks( );
}
Directory tempDir( );

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.28 Portable Code, AV Rule 214


3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not assume that members are initialized in any special order in constructors [INIT-13-3]
DESCRIPTION
"Do not assume that an object is initialized in any special order
in constructors. Do not depend on the order of initialization in
constructors."

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
class X {
public:
X( int y );
private:
int i;
int j;
};
inline X::X( int y ) : j( y ), i( j ) {}

// Violation

REPAIR
class X {
public:
X( int x, int y );
private:
int i;
int j;
};
inline X::X( int x, int y ) : j( y ), i( x ) {}

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.6 Order of Execution - Port. Rec. 14


2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer initialization to assignment in constructors [INIT-14-5]


DESCRIPTION
This rule checks constructors to see if you are assigning data members
when
you should be initializing them.
Assigning to data members causes a default constructor to be called first,
and then assignment will be performed later.
Initialization eliminates the overhead of performing assignment later.
Note that constants and references can only be initialized, never
assigned.
See also: INIT-06, INIT-10, MISRA-030

BENEFITS
Improves code consistency and runtime performance

EXAMPLE
#include <string>
using namespace std;
class A {
public:
A( const char* file, const char* path ) {
myFile = file;
// Violation
myPath = path;
// Violation
}
private:
string myFile;
string myPath;
};

REPAIR
#include <string>
using namespace std;
class A {

public:
A( const char* file, const char* path ) :
myFile(file), myPath(path) {}
// OK
private:
string myFile;
string myPath;
};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09,
Chapter: "Construction, Destruction, and Copying", Rule 48
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 12
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 74
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

JSF
Joint Strike Fighter
RULES
Any one function (or method) will contain no more than 200 logical source
lines of code (L-SLOCs) [JSF-1-3]
Values of character types shall be restricted to a defined and documented
subset of ISO 10646-1 [JSF-10-3]
Always declare functions at file scope [JSF-107-2]
Do not use functions with variable numbers of arguments [JSF-108-2]
Member functions shall not be defined within the no-template class
definition [JSF-109-4]
Trigraphs shall not be used [JSF-11-3]
Functions with more than 7 parameters will not be used [JSF-110-3]
Never return a reference to a local object [JSF-111-2]
Never return a dereferenced local pointer initialized by new in this
function scope [JSF-112-4]
A function shall have a single point of exit at the end of the function
[JSF-113-3]
All exit paths from a function with non-void return type shall have an
explicit return statement with an expression [JSF-114-2]
If a function returns error information, then that error information shall
be tested [JSF-115-3]
Pass built-in-types by value unless you are modifying them [JSF-116-4]
Declare reference parameters as const references whenever possible [JSF117.1-4]
Avoid slicing function arguments / return value [JSF-117_a-4]
The class object should be passed by reference if the class has non-static
pointers and has no declared copy constructor [JSF-117_b-4]
A pointer parameter in a function prototype should be declared as pointer
to const if the pointer is not used to modify the addressed object [JSF118-4]
Declare a type of parameter as typedef to pointer to const if the pointer
is not used to modify the addressed object [JSF-118_b-4]
Functions shall not call themselves, either directly or indirectly [JSF119-2]
The following digraphs will not be used <%, %>, <:, :>, %:, %:%: [JSF-123]
Only functions with 1 or 2 statements should be considered candidates for
inline functions [JSF-121-4]
Trivial accessor and mutator functions should be inlined [JSF-122-4]
The number of accessor and mutator functions should be minimized [JSF-1234]
Trivial forwarding functions should be inlined [JSF-124-4]

Pass objects by reference instead of by value [JSF-125_a-2]


Consider using op= instead of stand-alone op [JSF-125_b-2]
Prefer C++ style comment [JSF-126-2]
Sections of code should not be "commented out" [JSF-127-2]
Do not use wide string literals [JSF-13-3]
Each variable declaration should be commented [JSF-132_a-3]
Each typedef should be commented [JSF-132_b-3]
Each enumeration value should be commented [JSF-132_c-3]
Each structure member variable should be commented [JSF-132_d-3]
Comment every file [JSF-133_a-3]
Provide copyright information [JSF-133_b-3]
Comment every function [JSF-134-4]
Identifiers in an inner scope shall not use the same name as an identifier
in an outer scope, and therefore hide that identifier [JSF-135_a-2]
Identifiers in an inner scope shall not use the same name as an identifier
in an outer scope, and therefore hide that identifier [JSF-135_b-2]
Declare objects at function scope [JSF-136-4]
Make declarations at file scope static where possible [JSF-137-4]
Use consistent linkage for identifiers [JSF-138_a-2]
The static storage class specifier shall be used in definitions and
declarations of objects and functions that have internal linkage [JSF138_b-2]
External object should not be declared in more than one file [JSF-139-3]
Literal suffixes shall use uppercase rather than lowercase letters [JSF14-2]
Do not use register storage class [JSF-140-2]
A class, structure, or enumeration will not be declared in the definition
of its type [JSF-141-3]
All automatic variables shall have been assigned a value before being used
[JSF-142_a-2]
Initialize all variables [JSF-142_b-2]
Variables will not be introduced until they can be initialized with
meaningful values [JSF-143-2]
Braces shall be used to indicate and match the structure in the non-zero
initialization of arrays and structures [JSF-144-2]
In an enumerator list, the "=" construct shall not be used to explicitly
initialise members other than the first, unless all items are explicitly
initialised [JSF-145-2]
The underlying bit representations of floating point numbers shall not be
used [JSF-147-2]
Enumeration types shall be used instead of integer types (and constants)
as case labels [JSF-148-2]
Octal constants (other than zero) and octal escape sequences shall not be
used [JSF-149-2]

Hexadecimal constants will be represented using all uppercase letters


[JSF-150-3]
Avoid magic numbers [JSF-151-3]
A string literal shall not be modified [JSF-151.1-2]
Multiple variable declarations shall not be allowed on the same line [JSF152-2]
Unions shall not be used [JSF-153-2]
Bit fields shall only be defined to be of type unsigned int or signed int
[JSF-154-2]
All the members of a structure (or union) shall be named [JSF-156-2]
The right-hand operand of a logical && or || operator shall not contain
side effects [JSF-157-2]
Each operand of a logical '&&' or '||' shall be a postfix-expression [JSF158-2]
Avoid overloading &&, || or , (comma) [JSF-159-2]
Assignment operators shall not be used in expressions that yield a Boolean
value [JSF-160-2]
Avoid implicit conversions between signed and unsigned integer types [JSF162_a-2]
Avoid implicit conversions between signed and unsigned integer types [JSF162_b-2]
Use explicit type conversions for arithmetic using signed and unsigned
values [JSF-162_c-2]
Unsigned arithmetic shall not be used [JSF-163-2]
The right-hand operand of a shift operator shall lie between zero and one
less than the width in bits of the underlying type of the left-hand
operand [JSF-164-2]
The left-hand operand of a right-shift operator shall not have a negative
value [JSF-164.1-2]
The unary minus operator shall not be applied to an expression whose
underlying type is unsigned [JSF-165-2]
The sizeof operator shall not be used on expressions that contain side
effects [JSF-166-3]
Document integer division [JSF-167-2]
The comma operator shall not be used, except in the control expression of
a for loop [JSF-168_a-2]
The comma operator shall not be used [JSF-168_b-2]
Pointers to pointers should be avoided whenever possible [JSF-169-4]
The error indicator errno shall not be used [JSF-17-2]
The declaration of objects should contain no more than 2 levels of pointer
indirection [JSF-170_a-2]
The declaration of objects should contain no more than 2 levels of pointer
indirection [JSF-170_b-2]

>, >=, <, <= shall not be applied to pointer types except where they point
to the same array [JSF-171-2]
The address of an object with automatic storage shall not be assigned to
another object that may persist after the first object has ceased to exist
[JSF-173-2]
The NULL pointer shall not be dereferenced [JSF-174_a-2]
The NULL pointer shall not be dereferenced [JSF-174_b-2]
Do not compare a pointer to NULL or assign NULL to a pointer; use 0
instead [JSF-175-2]
Use a typedef to simplify program syntax when declaring function pointers
[JSF-176-3]
Do not use user-defined conversion functions [JSF-177-4]
Avoid casts down the inheritance hierarchy [JSF-178-2]
A pointer to a virtual base class shall only be cast to a pointer to a
derived class by means of dynamic_cast [JSF-179-2]
The macro offsetof, in library stddef.h, shall not be used [JSF-18-2]
Implicit conversions which may result in a loss of information shall not
be used [JSF-180_a-2]
Avoid implicit conversions between integer and floating types [JSF-180_c2]
Avoid implicit conversions of complex expressions [JSF-180_d-2]
Avoid implicit conversions from wider to narrower types [JSF-180_e-2]
Avoid implicit conversions of function return expressions [JSF-180_f-2]
Avoid implicit conversions of function arguments [JSF-180_h-2]
Redundant explicit cast to the same type is not allowed [JSF-181_a-3]
Avoid explicit cast from derived to a base class [JSF-181_b-3]
A cast should not convert a pointer type to an integral type [JSF-182_a-2]
A cast should not convert an integral type to a pointer type [JSF-182_b-2]
Never use explicit type conversions (casts) [JSF-183-4]
Avoid implicit conversions of float type resulting in a loss of
information [JSF-184_a-2]
Avoid implicit conversions of float type resulting in a loss of
information [JSF-184_b-2]
Prefer C++-style casts [JSF-185-2]
There shall be no unreachable code in "else" block [JSF-186_a-2]
There shall be no unreachable code after 'return', 'break', 'continue',
and 'goto' statements [JSF-186_b-2]
There shall be no unreachable code in "if/else/while/for" block [JSF186_c-2]
There shall be no unreachable code in switch statement [JSF-186_d-2]
There shall be no unreachable code in 'for' loop [JSF-186_e-2]
There shall be no unreachable code after 'if' or 'switch' statement [JSF186_f-2]

There shall be no unreachable code after "if" or "switch" statement inside


while/for/do...while loop [JSF-186_g-2]
All non-null statements shall either have at least one side-effect however
executed or cause control flow to change [JSF-187-2]
Do not use labels [JSF-188-3]
The goto statement shall not be used [JSF-189-3]
Do not use locale.h header and setlocale function [JSF-19-2]
The continue statement shall not be used [JSF-190-2]
Do not use the break statement [JSF-191-2]
All 'if...else-if' constructs shall be terminated with an 'else' clause
[JSF-192-3]
An unconditional break statement shall terminate every non-empty switch
clause [JSF-193-2]
Always provide a default branch for switch statements [JSF-194-2]
A switch expression shall not represent a value that is effectively
Boolean [JSF-195-3]
Every switch statement will have at least two cases and a potential
default [JSF-196-3]
Do not use floating point variables as loop counters [JSF-197-2]
The initialization expression in a for loop will perform no actions other
than to initialize the value of a single for loop parameter [JSF-198-3]
The increment expression in a for loop will perform no action other than
to change a single loop parameter to the next value for the loop [JSF-1993]
The setjmp macro and the longjmp function shall not be used [JSF-20-2]
Null initialize or increment expressions in for loops will not be used; a
while loop will be used instead [JSF-200-3]
Do not modify for loop counter within a body of the loop [JSF-201-2]
Floating-point expressions shall not be tested for equality or inequality
[JSF-202-2]
Evaluation of constant unsigned integer expressions should not lead to
wrap-around [JSF-203-2]
Assert liberally to document internal assumptions and invariants [JSF204_a-2]
The increment (++) and decrement (--) operators should not be mixed with
other operators in an expression [JSF-204_b-2]
The value of an expression shall be the same under any order of evaluation
that the standard permits [JSF-204_c-2]
The second or third operand of a ternary operator '?:' shall not contain
side effects [JSF-204_d-2]
Don't write code that depends on the order of evaluation of function
arguments [JSF-204_e-2]
Do not use the volatile keyword [JSF-205-2]

Dynamic heap memory allocation shall not be used [JSF-206-2]


Encapsulate global variables and constants, enumerated types, and typedefs
in a class [JSF-207-3]
C++ exceptions shall not be used (i.e. throw, catch and try shall not be
used.) [JSF-208-2]
typedefs that indicate size and signedness should be used in place of the
basic types [JSF-209-2]
The signal handling facilities of signal.h shall not be used [JSF-21-2]
Algorithms shall not make assumptions concerning the order of allocation
of nonstatic data members separated by an access specifier [JSF-210.1-2]
Limited dependence should be placed on C's operator precedence rules in
expressions [JSF-213_a-2]
Limited dependence should be placed on C's operator precedence rules in
expressions [JSF-213_b-2]
No parentheses are required for the operand of a unary operator [JSF213_c-2]
Limited dependence should be placed on C's operator precedence rules in
expressions [JSF-213_d-2]
Use parentheses unless all operators in the expression are the same [JSF213_e-2]
Avoid initialization order problems across translation units [JSF-214-2]
Avoid pointer arithmetic [JSF-215-3]
The input/output library stdio.h shall not be used [JSF-22-2]
The library functions atof, atoi and atol from library stdlib.h shall not
be used [JSF-23-2]
The library functions abort, exit, getenv and system from library stdlib.h
shall not be used [JSF-24-2]
The time handling functions of library time.h shall not be used [JSF-25-2]
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include [JSF-26-2]
Use multiple include guards [JSF-27-3]
The #ifndef and #endif pre-processor directives will only be used to
prevent multiple inclusions of the same header file [JSF-28-3]
A function should be used in preference to a function-like macro [JSF-292]
Follow the Cyclomatic Complexity limit of 20 [JSF-3-2]
Do not define constants via #define [JSF-30-2]
Avoid macros [JSF-31-3]
The #include pre-processor directive will only be used to include header
(*.h) files [JSF-32-3]
The #include directive shall use the <filename.h> notation to include
header files [JSF-33-2]
Use mechanism that prevents multiple inclusion of the file i.e. include
guards or "#pragma once" preprocessor directive [JSF-35-3]

Don't define entities with linkage in a header file [JSF-39_a-3]


Source lines will be kept to a length of 120 characters or less [JSF-41-3]
Only one statement shall be allowed per line [JSF-42-3]
Tabs that do not use ASCII spaces shall not be used [JSF-43-4]
User-specified identifiers (internal and external) will not rely on
significance of more than 64 characters [JSF-46-2]
Do not use identifiers which begin with one or two underscores (`_' or
`__') [JSF-47-3]
Identifiers will not differ by mixture of case, the underscore character,
interchange of the similarly looking letters and numbers [JSF-48-3]
Only the first word of the name of a class, structure, namespace,
enumeration, or typedef will begin with an uppercase letter [JSF-50-3]
All letters contained in function and variable names will be composed
entirely of lowercase letters [JSF-51-3]
Identifiers for constant and enumerator values shall be lowercase [JSF-522]
Header files will always have a file name extension of '.h' [JSF-53-3]
The following character sequences shall not appear in header file names:
', \, /*, //, or " [JSF-53.1-2]
Implementation files will always have a file name extension of ".cpp"
[JSF-54-3]
Order of scopes in class: public before all others [JSF-57_a-3]
Order of scopes in classes: protected before private [JSF-57_b-3]
When declaring functions with more than 2 parameters, the leading
parenthesis and the first argument are to be written on the same line as
the function name, each additional argument will be written on a separate
line [JSF-58-3]
The statement forming the body of a 'switch', 'while', 'do...while' or
'for' statement shall be a compound statement [JSF-59_a-2]
'if' and 'else' should be followed by a compound statement [JSF-59_b-2]
Braces "{}" which enclose a block should be placed in the same column
[JSF-60-3]
Place an opening brace '{' on its own line [JSF-61_a-3]
Place a closing brace '}' on its own line [JSF-61_b-3]
The dereference operator `*' and the address-of operator `&' should be
directly connected with the type names [JSF-62-3]
There shall be no white space following '.' or '->' operator [JSF-63_a-3]
There shall be no white space preceding '.' or '->' operator [JSF-63_b-3]
There shall be no white space between a prefix unary operator and its
operand [JSF-63_c-3]
There shall be no white space between a postfix unary operator and its
operand [JSF-63_d-3]
Avoid "public" data members [JSF-67_a-2]

Avoid 'protected' data members [JSF-67_b-2]


Declare the copy constructor and copy assignment operator private not in
class itself, but in a specifically designed base class [JSF-68-2]
Member functions shall be declared const whenever possible [JSF-69-3]
Freed memory shouldn't be accessed under any circumstances. Destructor
should not be called manually [JSF-70.1-2]
Public and protected methods should not be invoked by class constructor
[JSF-71-2]
Avoid calling virtual functions from constructors and destructors [JSF71.1-2]
Prefer initialization to assignment in constructors [JSF-74-3]
List members in an initialization list in the order in which they are
declared [JSF-75-2]
Declare an assignment operator for classes with dynamically allocated
memory [JSF-76_a-2]
Declare a copy constructor for classes with dynamically allocated memory
[JSF-76_b-2]
A copy constructor shall copy all data members and bases [JSF-77-2]
The definition of a constructor shall not contain default arguments that
produce a signature identical to that of the implicitly-declared copy
constructor [JSF-77.1-2]
Define a virtual destructor in classes used as base classes which have
virtual functions [JSF-78-2]
Call fclose() on pointer member in destructor if the pointer was used to
open a file [JSF-79-2]
Check for assignment to self in operator= [JSF-81-2]
Have assignment operator returns a reference to *this; make assignment
operator's return type a non-const reference to it's class' type [JSF-822]
The assignment operator must assign all members, including those in base
classes [JSF-83-2]
When two operators are opposites (such as == and !=), it is appropriate to
define both [JSF-85-3]
Hierarchies should be based on abstract classes [JSF-87-4]
A stateful virtual base shall be explicitly declared in each derived class
that accesses it [JSF-88.1-2]
A base class shall not be both virtual and non-virtual in the same
hierarchy [JSF-89-2]
Only use characters defined in ISO C standard [JSF-9-3]
Never redefine an inherited nonvirtual function [JSF-94_a-2]
Do not redefine an inherited nonvirtual function with template parameter
[JSF-94_b-2]
Do not redefine an inherited virtual function with a different default
parameter value [JSF-95-2]

Don't treat arrays polymorphically [JSF-96-2]


Arrays shall not be used in interfaces [JSF-97-2]
Avoid using global variables, global functions, and class in file outside
namespaces [JSF-98-4]
Namespaces will not be nested more than two levels deep [JSF-99-3]

Any one function (or method) will contain no more than 200 logical source lines of code (LSLOCs) [JSF-1-3]
DESCRIPTION
Any one function (or method) will contain no more than 200
logical source lines of code (L-SLOCs).

SINCE
v7.1

NOTES
Logical line of code is a single declaration or statement terminated
by semicolon.
Two semicolons in parenthesis after 'for' keyword are counted as one.

BENEFITS
Rule prevents using long functions which tend to be complex and
therefore difficult to comprehend and test.

EXAMPLE
int sample_function(int p)
{
int x, y;

// Violation
// L-SLOCs number = 1

// ...
x++;
// L-SLOCs number = 99
for(y = 10; y > 0; y--){
// L-SLOCs number = 100
x = y;
// L-SLOCs number = 101
}
// ...
x = x + p; y = y + p;
151

// L-SLOCs number = 150, L-SLOCs number =

// ...
return x;

// L-SLOCs number = 201

REPAIR
Do not use functions containing more than 200
logical source lines of code (L-SLOCs).

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 3.2 Code Size and Complexity, AV Rule 1

Values of character types shall be restricted to a defined and documented subset of ISO
10646-1 [JSF-10-3]
DESCRIPTION
"The chosen implementation of C shall conform to a subset of
ISO 10646-1, and the chosen subset shall be documented."
Explicitly specified numeric value of character may not conform to
chosen subset of ISO 10646-1.

BENEFITS
Values of character types are defined and documented as subset of ISO
10646-1.

EXAMPLE
void foo()
{
const char * s[] = {"a",
"\012" /* Violation */
};
}

REPAIR
Define character types as subset of ISO 10646-1.

REFERENCES
1. Origin: Misra Guidelines - Rule 006
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 10

Always declare functions at file scope [JSF-107-2]


DESCRIPTION
Functions shall always be declared at file scope.
Declaring functions at block scope may be confusing,
and can lead to undefined behaviour.

BENEFITS
Rule prevents undefined behaviour and improves readability.

EXAMPLE
void foo1( ) {
void foo2( );
}

/* Violation */

REPAIR
void foo2( );
void foo1( ) {
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 68
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 107
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-2

Do not use functions with variable numbers of arguments [JSF-108-2]


DESCRIPTION
Functions with variable numbers of arguments shall not be used.

BENEFITS
Prevents from a lot of potential problems with this feature.

EXAMPLE
void foo(int x, ...)
{
}

// Violation

REPAIR
Do not use functions with variable numbers of arguments.

REFERENCES
1. Misra Guidelines - Rule 69
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.1 Function Arguments - Rule 31
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 98
4. Scott Meyers and Martin Klaus, "Examining C++ Program Analyzers",
Dr. Dobbs' Journal, the February 1997,
Chapter: "Implementation", Item 23
http://www.aristeia.com/ddjpaper1_frames.html
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 108

6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-1

Member functions shall not be defined within the no-template class definition [JSF-109-4]
DESCRIPTION
Functions defined within the class definition are implicitly inline;
however,
defining member functions within a class definition also makes the class
definition less compact and harder to read. This rule detects if you
define
member functions in the class definition.
See also: CODSTA-CPP-33

BENEFITS
This rule ensure better data hiding by separating interface and
implementation.

EXAMPLE
class A {
public:
int foo( ) {};
inline int bar( );
};

// Violation

inline int A::bar( ) {


return 0;
};

REPAIR
class A {
public:
int foo( );
inline int bar( );
};
int A::foo( ) {};
inline int A::bar( ) {
return 0;
};

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 21
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 109

Trigraphs shall not be used [JSF-11-3]


DESCRIPTION
Rule reports a violation message if trigraphs are used.
All occurrences in a source file of the following sequences of three
characters (called trigraph sequences) are replaced with the corresponding
single character.
??= #
??( [
??/ \
??) ]
??' ^
??< {
??! |
??> }
??- ~
If the compiler has a switch to ignore trigraphs then this
option should be used, or alternatively ensure that two
adjacent question marks are never used in the code.

BENEFITS
Trigraphs can cause accidental confusion with other uses of two question
marks and lead to unexpected behaviour.

EXAMPLE
??=define TEST 1
/* Violation
*/
void foo() {
const char* s = "(Date should be in the form ??-??-??)"; /* Violation */
}

REPAIR
#define TEST 1
OK */
void foo() {

/*

const char* s = "(Date should be in the form " "??" "-??" "-??" ")"; /*
OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 4
2. Origin: Misra Guidelines - Rule 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 11
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-3-1

Functions with more than 7 parameters will not be used [JSF-110-3]


DESCRIPTION
Functions having long argument lists can be difficult to read,
use, and maintain. Functions with too many parameters may
indicate an under use of objects and abstractions.

SINCE
v7.1

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
void foo(int a, int b, int c, int d, int e, int f, int g, int h)
Violation
{
}

REPAIR
// Limit the number of parameters to 7 per function.
void foo(int a, int b, int c, int d, int e, int f, int g)
{
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
4.13 Function, AV Rule 110

// OK

//

Never return a reference to a local object [JSF-111-2]


DESCRIPTION
"A function must never return a pointer or reference to a local variable.
If a function returns a reference or a pointer to a local variable, the
memory
to which it refers will already have been deallocated, when this reference
or
pointer is used. The compiler may or may not give a warning for this."
See also: MRM-23, PB-40, MISRA2004-17_6

BENEFITS
Returning a reference to a local object or a dereferenced pointer
initialized
by new within the function may cause a memory leak.

EXAMPLE
int* foo(
int i;
return
}
int& bar(
int i;
return
}

) {
&i; // Violation
) {
i;

// Violation

REPAIR
int foo( ) {
int i = 0;
return i; // OK
}
int bar( ) {
int i = 0;
return i; // OK
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#9.4
From: 9 Functions - 9.4 Return Types and Values - Rule 34
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Implementation", Item 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 111
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Never return a dereferenced local pointer initialized by new in this function scope [JSF-112-4]
DESCRIPTION
Never return a reference to a local object or a dereferenced pointer
initialized by new within the function. This rule detects when you
return a reference to a local object or dereferenced pointer.
See also: MRM-24

BENEFITS
Returning a reference to a local object or a dereferenced pointer
initialized
by new within the function may cause a memory leak.

EXAMPLE
class A {
public:
A(int xval, int yval) : _x(xval), _y(yval) {}
friend A& operator+(const A& p1, const A& p2);
private:
int _x, _y;
};
A& operator+(const A& p1, const A& p2) {
A *result = new A(p1._x + p2._x, p1._y + p2._y);
return *result;
// Violation
}

REPAIR
class A {
public:
A(int xval, int yval) : _x(xval), _y(yval) {}
friend A operator+(const A& p1, const A& p2);
private:
int _x, _y;
};
A operator+(const A& p1, const A& p2) {

A result = A(p1._x + p2._x, p1._y + p2._y);


return result;

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 31
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 112
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A function shall have a single point of exit at the end of the function [JSF-113-3]
DESCRIPTION
Every function should have a single point of exit.

NOTES
Calls of functions exit, abort, and _Exit from standard library stdlib.h
are detected by rule as exit points.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
int foo(int i)
{
if (i == 0) {
return 0;
// Violation
} else if (i == 1) {
return 1;
// Violation
} else {
return 2;
// Violation
}
}
int foo2(int a) {
int result;
if (a > 0) {
return result;
}
}

REPAIR
int foo(int i)
{
int result = 0;

// Violation

if (i == 0) {
result = 0;
} else if (i == 1) {
result = 1;
} else {
result = 2;
}
return result;
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 82
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 113
4. ISO/DIS 26262
point 8.4.4

All exit paths from a function with non-void return type shall have an explicit return statement
with an expression [JSF-114-2]
DESCRIPTION
"All exit paths from a function with non-void return type
shall have an explicit return statement with an expression.
This expression gives the value that the function returns.
The absence of a return with an expression leads to undefined
behaviour (and the compiler may not give an error)."

NOTES
"goto" statement is considered as exit point.
The rule does not track the flow. It assumes that each path could
be reachable independently from conditions in conditional statements.

BENEFITS
Rules prevents unpredictable function behaviour.

DRAWBACKS
Rule skips "while", "for", and "catch" sections.

EXAMPLE
int foo1(int x){ // Violation
// in second 'if' statement, 'return' statement is missing
if (x==0) {
if (x==0) {
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // Violation

// in 'switch' statement, 'default' statement is missing


switch(x){
case 0: return 1;
case 1: return 1;
case 2: return 1;
}
}
int foo3(int x){ // Violation
}
int foo4(int x){ // Violation - rule does not track the flow
if (x > 10) {
return 0;
}
if (x <= 10) {
return 1;
}
// unreachable path
}

REPAIR
int foo1(int x){ // OK
if (x==0) {
if (x==0) {
return 0;
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // OK
switch(x){
case 0: return 1;
case 1: return 1;
case 2: return 1;
default: return 1;
}
}

int foo3(int x){ // OK


return 0;
}
int foo4(int x){ // OK
if (x > 10) {
return 0;
} else {
return 1;
}
// unreachable path
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-3

If a function returns error information, then that error information shall be tested [JSF-115-3]
DESCRIPTION
"A function (whether it is part of the standard library, a third party
library
or a user defined function) may provide some means of indicating the
occurrence
of an error. This may be via an error flag, some special return value or
some
other means. Whenever such a mechanism is provided by a function the
calling
program shall check for the indication of an error as soon as the function
returns.
However, note that the checking of input values to functions is considered
a more robust means of error prevention than trying to detect errors after
the function has completed (see Rule MISRA2004-20_3). Note also that the
use
of errno (to return error information from functions) is clumsy and should
be
used with care (see Rule MISRA2004-20_5)."

NOTES
Rules checks usage of function calls which returns char, short, int, enum,
or typedef to char, short, int, or enum value and reports violation when
this value is not assigned, checked or cast to void.

BENEFITS
Rule helps writing safety code.

EXAMPLE
int SomeFunctionReturningError( );
void foo( )
{
SomeFunctionReturningError( ); // Violation
}

REPAIR
int SomeFunctionReturningError( );
int foo( )
{
int x;
x = SomeFunctionReturningError( );
(void)SomeFunctionReturningError( );
if (SomeFunctionReturningError( ));
switch (SomeFunctionReturningError( )) {
}
return SomeFunctionReturningError( );
}

//
//
//
//

OK
OK
OK
OK

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 86
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 115
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-3-2
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 7
6. http://cwe.mitre.org/data/definitions/391.html

Pass built-in-types by value unless you are modifying them [JSF-116-4]


DESCRIPTION
This rule checks if your code passes arguments of built-in types by value,
unless they should be modified by functions.

BENEFITS
Passing arguments of built-in types by value improves the efficiency
of your code.

EXAMPLE
int Foo(int i, int &j)
{
return i + j;
}
int Bar(int &i, int j)
{
j += i;
return j;
}

// Violation

// Violation

REPAIR
int Foo(int i, int j)
{
return i + j;
}
int Bar(int i, int j)
{
j += i;
return j;
}

// OK

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,

(C) 2005 Pearson Education, Inc. Chapter: "Take Parameters Appropriately


by Value, (Smart) Pointer, or Reference", Rule 25
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions (Value, Pointer or Reference), AV Rule 116

Declare reference parameters as const references whenever possible [JSF-117.1-4]


DESCRIPTION
This rule checks if you declared your reference parameters as const
references.
When your function is not going to modify the argument it is referencing,
you
should use const to protect variables from unintended modifications when
the
function returns.
See also: CODSTA-CPP-03, CODSTA-CPP-38, CODSTA-CPP-44,
MISRA-104, MISRA2004-16_7, OPT-21

NOTES
The rule does not report violations on virtual functions.

BENEFITS
Declaring parameters which are not modified as const reference instead of
reference improves legibility. It also prevents future revisions from
unintentional changing the caller's data.

EXAMPLE
struct Foo {
int x;
int y;
};
int Bar( Foo &f ) {
return f.x;
}

// Violation

int FooBar( Foo &f ) { // OK


return f.x++;
}

REPAIR
struct Foo {
int x;
int y;
};
int Bar( const Foo &f ) {
return f.x;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid slicing function arguments / return value [JSF-117_a-4]


DESCRIPTION
This rule detects where an object of classs with virtual methods has been
passed or returned by value instead of by reference. Passing / returning
objects by reference is more efficient than passing by value because no
new objects are being created and because it avoids the "slicing problem."
See also: OPT-14, PB-23

SINCE
v7.0

BENEFITS
Rule prevents slicing problem, improves code consistency
and runtime performance.

EXAMPLE
class A {
public:
virtual void someFun();
const A violation( A a ) {
value
return a;
}
};

// Violation - passing parameter by

REPAIR
class A {
public:
virtual void someFun();
const A& valid( const A &a ) {
return a;
}
};

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 20
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 22
4. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 43
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 117

The class object should be passed by reference if the class has non-static pointers and has
no declared copy constructor [JSF-117_b-4]
DESCRIPTION
This rule detects where an object containing pointer member fields has
been
passed by value using a compiler-generated copy constructor. Passing such
objects by reference avoids possible problems with improper bitwise
copying
member pointers.
If a class/struct has non-static pointer member fields, has no declared
copy
constructor, and class/struct object is passed by value then the rule
reports
a violation message.
See also: OPT-14, PB-20

SINCE
v7.1

EXCEPTIONS
The rule excludes from checking objects of type class/struct which names
end with 'iterator' (e.g 'iterator', 'const_iterator',
'normal_iterator',...)

BENEFITS
Rule helps to avoid possible problems with bitwise copying member
pointers.

EXAMPLE
class A;
void foo1(A a);
class A
{

int *x;
};
void foo(void)
{
A a;
foo1(a);
}

// Violation

REPAIR
class A;
void foo1(A &a);

class A
{
int *x;
};
void foo(void)
{
A a;
foo1(a);
}

// OK - passed by reference

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 117
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A pointer parameter in a function prototype should be declared as pointer to const if the


pointer is not used to modify the addressed object [JSF-118-4]
DESCRIPTION
"A pointer parameter in a function prototype should be declared as pointer
to
const if the pointer is not used to modify the addressed object. The const
qualification should be applied to the object pointed to, not to the
pointer,
since it is the object itself that is being protected."
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104

NOTES
There can already be overloaded function with parameter declared as
pointer
to const. Then changing the type of parameter to pointer to const will
make
the code non-compilable.

EXCEPTIONS
Violation is not reported if parameter is unnamed.

BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.

EXAMPLE
int function(int* ptr)
{
return (*ptr) + 1;
}

REPAIR

// Violation

int function(const int* ptr) // OK


{
return (*ptr) + 1;
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2

Declare a type of parameter as typedef to pointer to const if the pointer is not used to modify
the addressed object [JSF-118_b-4]
DESCRIPTION
The rule reports a violation if a parameter in a function prototype is
declared
as typedef to pointer to non-const object and the pointer is not used to
modify
the addressed object. Then the type of parameter could be changed to
typedef
to pointer to const object.
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104

NOTES
It is not sufficient to add 'const' identifier before typedef's
name in a function declaration, because it is applied to pointer
not to pointed object.
There can already be overloaded function with parameter declared as
typedef
to pointer to const. Then changing the type of parameter to typedef to
pointer
to const will make the code non-compilable.

BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.

EXAMPLE
typedef int* PINT;
typedef const int* CINT;
int function1(PINT ptr)
{
return (*ptr) + 1;
}

// Violation

int function2(const PINT ptr)

// Violation

{
return (*ptr) + 1;
}

REPAIR
typedef int* PINT;
typedef const int* CINT;
int function1(CINT ptr)
{
return (*ptr) + 1;
}

// OK

int function2(const CINT ptr)


{
return (*ptr) + 1;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2

Functions shall not call themselves, either directly or indirectly [JSF-119-2]


DESCRIPTION
Functions shall not call themselves, either directly or indirectly.

NOTES
This rule checks for direct recursion and simple indirect
recursion (up to three nested function calls).

BENEFITS
Prevents using recursive functions.

EXAMPLE
void foo( int l ) {
int x = l;
if (l > 0) {
foo( x - 1 );
}

/* Violation */

}
void foo3( int );
void foo4( int i ) {
if (i > 0) {
foo3( (int) i / 2 );
}
}

/* Violation */

void foo3( int i ) {


int x = i;
if (i > 0) {
foo4( x - i );
}
}

/* Violation */

REPAIR
void foo1( ) {
/* empty */
}

/* OK */

void foo2( );

/* OK */

void foo3( ) {
foo2( );
}

/* OK */

void foo7( int );


void foo4( int i ) {
foo7( i );
/* OK - cannot check complex indirect recursion */
}
void foo5( int i ) {
foo4( i );
/* OK - cannot check complex indirect recursion */
}
void foo6( int i ) {
foo5( i );
/* OK - cannot check complex indirect recursion */
}
void foo7( int i ) {
if (i > 0) {
foo6( i - 5 );
}
}

/* OK - cannot check complex indirect recursion */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 70
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 119

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-4
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1
6. HIS Source Code Metriken, version 1.3.1
Metrik "ap_cg_cycle"
7. ISO/DIS 26262
point 8.4.4

The following digraphs will not be used <%, %>, <:, :>, %:, %:%: [JSF-12-3]
DESCRIPTION
The following digraphs will not be used <%, %>, <:, :>, %:, %:%:
The use of digraphs listed in this rule can obscure the meaning
of otherwise simple constructs.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
int a <: 2 :> <: 2 :> = <%<%0,1%>,<%2,3%>%>; // Violation

REPAIR
int a[2][2] = { {0,1}, {2,3} };

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-5-1

Only functions with 1 or 2 statements should be considered candidates for inline functions
[JSF-121-4]
DESCRIPTION
Only functions with 1 or 2 statements should be considered
candidates for inline functions.
Rule reports a violation message if inlined function has more
than 2 statements.

SINCE
v7.1

BENEFITS
Inlining complex functions may lead to significant code bloat
as well as to complicate debugging efforts.

DRAWBACKS
Each declared variable is counted as a separate statement.
int a, b, c;

// counted as 3 statements

EXAMPLE
inline int foo(int a)
{
int b = 0;
b = (b-a)/a;
return b;
}

// Violation

REPAIR
int foo(int a)
{
int b = 0;

// OK

b = (b-a)/a;
return b;
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 121
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Trivial accessor and mutator functions should be inlined [JSF-122-4]


DESCRIPTION
Trivial accessor and mutator functions should be inlined.
Rule reports a violation message if accessor/mutator which does not have:
- loop statements
- virtual function calls
- recursion
- more than 5 statements
is not inline.

SINCE
v7.1

EXCEPTIONS
Template methods, virtual methods.

BENEFITS
Inlining short, simple functions can save both time and space.

DRAWBACKS
Rule assumes that getter/setter (accessor/mutator) methods are methods
with names
starting from get/Get or set/Set prefix followed by underscoring or
capitalized
letter and:
- get method returns member variable or reference to it
- set method sets the value to member variable

EXAMPLE
class A
{

int m_var;
public:
int get_m_var();
void set_m_var();
};

int A::get_m_var()
{
return m_var;
}

// Violation

void A::set_m_var()
{
m_var = 0;
}

// Violation

REPAIR
class A
{
int m_var;
public:
inline int get_m_var();
inline void set_m_var();
};

inline int A::get_m_var()


{
return m_var;
}

// OK

inline void A::set_m_var()


{
m_var = 0;
}

// OK

REFERENCES

1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.13 Functions, AV Rule 122
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The number of accessor and mutator functions should be minimized [JSF-123-4]


DESCRIPTION
The number of accessor and mutator functions should be minimized
to number of member variables. Rule reports a violation message
if number of setter methods or number of getter methods exceeds
number of member variables.

SINCE
v7.1

NOTES
Rule assumes that setter/getter (mutator/accessor) methods are methods
with names starting from get/Get or set/Set prefix and followed by
underscoring or capitalized letter.

BENEFITS
Numerous accessors and mutators may indicate that a class simply serves
to aggregate a collection of data rather than to embody an abstraction
with a well-defined state or invariant. In this case, a struct with
public data may be a better alternative.

EXAMPLE
class Sample // Violation
{
private:
int m_var;
public:
int get_m_var();
void set_m_var();
void set_m_var(int a);
};

REPAIR
class Sample // OK
{
private:
int m_var;
public:
int get_m_var();
void set_m_var(int a = 0);
};

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 123
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Trivial forwarding functions should be inlined [JSF-124-4]


DESCRIPTION
Trivial forwarding functions should be inlined.
Rule reports a violation message if a function performing
only one action i.e. calling another function is not inlined.

SINCE
v7.1

EXCEPTIONS
Constructors, destructors, template methods, virtual methods.

BENEFITS
Inlining short, simple functions can save both time and space.

EXAMPLE
int goo(int a, int b)
{
/* code */
return 1;
}
int foo(int a, int b)
{
return(goo(a,b));
}

REPAIR
int goo(int a, int b)
{
/* code */
return 1;

// Violation

}
inline int foo(int a, int b) // OK
{
return(goo(a,b));
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 124
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Pass objects by reference instead of by value [JSF-125_a-2]


DESCRIPTION
This rule detects where an object has been passed by value instead
of by reference. Passing objects by reference is more efficient
than passing by value because no new objects are being created
and because it avoids the "slicing problem."
See also: PB-20, PB-23, OPT-33

EXCEPTIONS
There also may be a situation where the object is so small that it would
be
more efficient to pass by value instead of by reference.
Due to C++'s type system and the fact that QString, RWCString and CString
are implicitly shared, they may be treated like ints or other basic types.

BENEFITS
Improves code consistency and runtime performance.

EXAMPLE
class A {
public:
const A violation( A a ) {
value
return a;
}
};

// Violation - passing parameter by


// Violation - returning by value

REPAIR
class A {
public:
const A& valid( const A &a ) {
return a;
}

// OK
// OK

};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 20
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 22
4. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 43
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125
7. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Consider using op= instead of stand-alone op [JSF-125_b-2]


DESCRIPTION
When you define stand-alone version of operators:
+ , - , * , / , ^, % , | , & , >> , << (e.g., operator+), the assignment
version of an operator (e.g., operator+=) should be also defined.
"Offering assignment versions of operators as well as stand-alone
versions,
you allow clients of your classes to make the difficult trade-off between
efficiency and convenience."
"You should consider using assignment versions of operators instead
of stand-alone versions whenever performance is at a premium."

BENEFITS
"Assignment versions of operators are more efficient than stand-alone
versions,
because stand-alone versions must typically return a new object, and that
costs
us the construction and destruction of a temporary. Assignment versions of
operators write to their left-hand argument, so there is no need to
generate
a temporary to hold the operator's return value."

EXAMPLE
class A {
public:
};
A& operator+( A& a, A& b );
A& operator-( A& a, A& b );
class B {
public:
B& operator+=( B& b );
};
B& operator+( B& a, B& b );
void foo( ) {
B ba, bb ,bc, bd;

// Violation
// Violation

bb = ba + bc + bd;

// Violation

REPAIR
class A {
public:
A& operator+=( A& a );
A& operator-=( A& a );
};
A& operator+( A& a, A&
A& operator-( A& a, A&
class B {
public:
B& operator+=( B& b
};
B& operator+( B& a, B&
void foo( ) {
B ba, bb ,bc, bd;
bb = ba;
bb += bc;
bb += bd;
}

b );
b );

// OK
// OK

);
b );

// OK
// OK
// OK

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 22
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125

Prefer C++ style comment [JSF-126-2]


DESCRIPTION
Use // for comments. Do not use /* and */.
"C++, however, does not allow comments to be nested using /* */."

BENEFITS
Rule improves readability and maintainability. If the characters // are
consistently used for writing comments, then the combination /* */ may be
used
to make comments out of entire sections of code during the development and
debugging phases.

EXAMPLE
/* Violation */

REPAIR
// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 9
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 126

Sections of code should not be "commented out" [JSF-127-2]


DESCRIPTION
"Where it is required for sections of source code not to be compiled then
this should be achieved by use of conditional compilation (e.g. #if or
#ifdef constructs with a comment)."

NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.

BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."

EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}

// Violation

REPAIR
void foo()
{
int x = 5;
/* Comment without

// OK

code within */
#if 0
if (x==0){
x++;
}
#endif
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3

Do not use wide string literals [JSF-13-3]


DESCRIPTION
Wide string literals shall not be used.

BENEFITS
Prevents from various undefined and implementation-defined behaviours
associated with
them and they shall not be used.

EXAMPLE
#include <stddef.h>
void foo() {
wchar_t* x = L"Fred";/* Violation */
}

REPAIR
#include <stddef.h>
void foo() {
char* x = "Fred";/* OK */
}

REFERENCES
1. Origin: Misra Guidelines - Rule 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 13

Each variable declaration should be commented [JSF-132_a-3]


DESCRIPTION
Each variable declaration should be commented.
Rule reports a violation message if there is no comment
placed in line of variable declaration nor in previous line.

SINCE
v7.1

NOTES
Rule checks only declarations of local and global variables.

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo()
{
int var1;
// Violation
int var2;
// Violation
}

REPAIR
void foo()
{
int var1; // comment - OK
// comment - OK
int var2;

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

Each typedef should be commented [JSF-132_b-3]


DESCRIPTION
Each typedef should be commented.
Rule reports a violation message if there is no comment in line
of typedef declaration and in previous line.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
typedef int int32;
// Violation

REPAIR
typedef int int32; // OK - comment

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

Each enumeration value should be commented [JSF-132_c-3]


DESCRIPTION
Each enumeration value should be commented.
Rule reports a violation message if there is no comment
in line of enumeration value declaration and in previous line.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
enum {
ENUM1 = 2,
// Violation
};

REPAIR
enum {
ENUM1 = 2, // OK - comment
};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

Each structure member variable should be commented [JSF-132_d-3]


DESCRIPTION
Each structure member variable should be commented.
Rule reports a violation message if there is no comment
in line of structure member declaration and in previous line.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
struct S
{
char* c;
// Violation
};

REPAIR
struct S
{
char* c; // comment - OK
};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132

Comment every file [JSF-133_a-3]


DESCRIPTION
"Every file that contains source code must be documented with an
introductory
comment that provides information on the file name and its contents."

NOTES
C and C++ style comments are allowed.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
// No comment "File:"

// Violation - no introductory comment

REPAIR
// File: <short description of the file>

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133

Provide copyright information [JSF-133_b-3]


DESCRIPTION
"All files must include copyright information, that is to say a line
starting
with: // Copyright"

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
// Violation - no copyright information

REPAIR
// Copyright

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 5
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133

Comment every function [JSF-134-4]


DESCRIPTION
"Write some descriptive comments before every function."
Rule reports a violation message on:
1) function prototype if no function definition is visible and prototype
is
not preceded with a comment,
2) function definition if:
- there is no prototype and function definition is not preceded with a
comment
- there is visible prototype but neither prototype nor function
definition is
preceded with a comment

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo1();

// Violation

int foo2(int x){ // Violation


return x++;
}
int foo3(int x);
int foo3(int x){ // Violation
return x++;
}

REPAIR
// Comment with description for the function.
void foo1();
// Comment with description for the function.

int foo2(int x){


return x++;
}
// Comment with description for the function.
int foo3(int x);
int foo3(int x){
return x++;
}
int foo4(int x);
// Comment with description for the function.
int foo4(int x){
return x++;
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 134

Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [JSF-135_a-2]
DESCRIPTION
Do not hide names of global variables and parameters.

BENEFITS
Hiding names of global variables or parameters
can lead to errors and confusion.

EXAMPLE
int x;
void foo( ) {
int x;
/* Violation */
x = 3;
}

REPAIR
Avoid hiding names of global variables and parameters.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4

Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [JSF-135_b-2]
DESCRIPTION
Do not hide names of local variables.

BENEFITS
Hiding names of local variables can lead to errors and confusion.

EXAMPLE
int foo( ) {
int a;
{
int a;
}
}

/* Violation */

REPAIR
Avoid hiding names of local variables.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4

Declare objects at function scope [JSF-136-4]


DESCRIPTION
Declarations of objects should be at function scope
unless a wider scope is necessary.

BENEFITS
Prevents using global variables.

EXAMPLE
int globalVar;

// Violation

REPAIR
void foo( ) {
int localVar;
}

// OK

REFERENCES
1. Misra Guidelines - Rule 22
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 57
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 136
4. ISO/DIS 26262
point 8.4.4

Make declarations at file scope static where possible [JSF-137-4]


DESCRIPTION
All declarations at file scope should be static where possible.

BENEFITS
Prevents from accidentally overwriting of functions or variables

EXAMPLE
int g1; /* Violation */
void foo1() {}; /* Violation */

REPAIR
static int g2; /* OK */
static void foo2(){}; /* OK */

REFERENCES
1. Origin: Misra Guidelines - Rule 23
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 137

Use consistent linkage for identifiers [JSF-138_a-2]


DESCRIPTION
Identifiers shall not simultaneously have both internal and external
linkage in the same translation unit.

BENEFITS
Rule prevents variable-name hiding which can be confusing.

EXAMPLE
static unsigned short x;
static unsigned short y;
void foo( ) {
extern unsigned short x;
// Violation
extern unsigned short y;
// Violation
{
extern unsigned short y; // Violation
}
}

REPAIR
Do not declare variables simultaneously with internal and external
linkage in the same translation unit.

REFERENCES
1. Origin:

Misra Guidelines - Rule 24

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.15 Declarations and Definitions, AV Rule 138

The static storage class specifier shall be used in definitions and declarations of objects and
functions that have internal linkage [JSF-138_b-2]
DESCRIPTION
"It is good practice to apply the static keyword consistently to
all declarations of objects and functions with internal linkage."
See also: CODSTA-81

BENEFITS
Rule improves good programming style and readability.

EXAMPLE
/* file.h */
static int x;
/* file.c */
#include "file.h"
extern int x;

/* Violation */

REPAIR
/* file.h */
static int x;
/* file.c */
#include "file.h"
static int x;

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 138

External object should not be declared in more than one file [JSF-139-3]
DESCRIPTION
External objects should be declared in header files which are then
included in all
those source files which use these objects. This rule will inform about
multiple
declarations of symbols.

BENEFITS
Rule improves readability, clarity of code and prevents errorneous code.

EXAMPLE
/* misra_027.h */
/* Do not declare external object in more than one file. */
extern int a;
/* Violation */
/* misra_027.c */
#include "misra_027.h"
extern int a;

REPAIR
/* misra_027.h */
extern int a;

/* OK */

/* misra_027.c */
#include "misra_027.h"
int a;

REFERENCES
1. Origin: Misra Guidelines - Rule 27
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 139

Literal suffixes shall use uppercase rather than lowercase letters [JSF-14-2]
DESCRIPTION
Literal suffixes shall use uppercase rather than lowercase letters.
See also: CODSTA-50

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo(long param = 64l) // Violation
{
const long a = 64l; // Violation
}

REPAIR
void foo(long param = 64L) // OK
{
const long a = 64L;
// OK
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4

Do not use register storage class [JSF-140-2]


DESCRIPTION
The register storage class specifier shall not be used.

BENEFITS
Prevents from dependencies on compiler.

EXAMPLE
void foo()
{
register int a;
}

// Violation

REPAIR
Do not use the 'register' storage class specifier.

REFERENCES
1. Origin:

Misra Guidelines - Rule 28

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.15 Declarations and Definitions, AV Rule 140

A class, structure, or enumeration will not be declared in the definition of its type [JSF-141-3]
DESCRIPTION
A class, structure, or enumeration will not be declared in the definition
of its type.

SINCE
v7.1

BENEFITS
Rule improves readability.

EXAMPLE
enum
{
up,
down
} direction;

// Violation

REPAIR
enum direction_e
{
up,
down
};
direction_e direction; // OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 141

All automatic variables shall have been assigned a value before being used [JSF-142_a-2]
DESCRIPTION
"The intent of this rule is that all variables shall have been written to
before
they are read. This does not necessarily require initialisation at
declaration.
Ideally a static check should be performed for any automatic variables
which
might be used without having first been assigned a value"
See also: INIT-06, INIT-10, INIT-14, BD-PB-NOTINIT

NOTES
The rule assumes that local variable might be initialized
by passing its non-const pointer to an external function.

BENEFITS
Prevents reading from uninitialized variables.

EXAMPLE
void foo( ) {
int b;
b++;
}

// Violation

REPAIR
void foo( ) {
int b = 0;
b++;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve

Your Programs and Design", Third Edition, Addison-Wesley,


(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. Misra Guidelines - Rule 30
3. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9, rule 9.1
4. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 40
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 142
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-1

Initialize all variables [JSF-142_b-2]


DESCRIPTION
"A variable must always be initialized before use. Normally, the compiler
gives
a warning if a variable is undefined. It is then sufficient to take care
of
such cases. Instances of a class are usually initialized even if no
arguments
are provided in the declaration (the empty constructor is invoked). To
declare
a variable that has been initialized in another file, the keyword extern
is always used.
By always initializing variables, instead of assigning values to them
before
they are first used, the code is made more efficient since no temporary
objects
are created for the initialization. For objects having large amounts of
data,
this can result in significantly faster code."

EXCEPTIONS
Exception to this rule are 'volatile' data, non-primitive types, and
arrays.

BENEFITS
Prevents reading from uninitialized variables.

EXAMPLE
int a;
void foo( ) {
int b;
}

// Violation

// Violation

REPAIR
int a = 0;
void foo( ) {
int b = 0;
}

// OK

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 142
4. http://cwe.mitre.org/data/definitions/457.html
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
6. ISO/DIS 26262
point 8.4.4

Variables will not be introduced until they can be initialized with meaningful values [JSF-1432]
DESCRIPTION
Variables will not be introduced until they can be initialized with
meaningful values.
Rule reports a violation message if:
- value assigned to local variable during initialization is not used (i.e.
there is
no variable usage after initialization statement and before new value
assignment)
- local variable is prematurely declared and is only used in for loop

SINCE
v7.1

NOTES
Rule is enabled for C++ only.

BENEFITS
Prevent clients from accessing variables without meaningful values.

EXAMPLE
int f(int);
void fun_1(int x)
{
int i;

int max=0;

// Violation: i is prematurely declared


// (the intent is to use i in the for loop only)
// Violation: max initialized with a dummy value

max = f(x);
for (i=0 ; i<max ; ++i)
{

}
}

REPAIR
int f(int);
void fun_2(int x)
{
int max = f(x);

// OK: max not introduced until meaningful


// value is available

for(int i = 0; i < max; i++) // OK


{
}
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 143
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Braces shall be used to indicate and match the structure in the non-zero initialization of arrays
and structures [JSF-144-2]
DESCRIPTION
"ISO C requires initializer lists for arrays, structures and union types
to be
enclosed in a single pair of braces (though the behaviour if this is not
done
is undefined). The rule given here goes further in requiring the use
of additional braces to indicate nested structures.
The zero initialization of arrays or structures shall only be applied
at the top level. The non-zero initialization of arrays or structures
requires an explicit initializer for each element."

NOTES
Rule checks only up to three-level nested bracket initialization.

EXCEPTIONS
"All the elements of arrays or structures can be initialized (to zero or
NULL)
by giving an explicit initializer for the first element only. If this
method
of initialization is chosen then the first element should be initialized
to zero (or NULL), and nested braces need not be used."

BENEFITS
"This forces the programmer to explicitly consider and demonstrate the
order
in which elements of complex data types are initialized"

EXAMPLE
int y[3][2] = { 1, 2, 3, 4, 5, 6 }; // Violation
struct S {
int i;

struct T {
int j;
}t;
} s = {1, 2}; // Violation

REPAIR
int y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // OK
struct S {
int i;
struct T {
int j;
}t;
} s = {1, { 2 }}; // OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Misra Guidelines - Rule 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 144
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-2

In an enumerator list, the "=" construct shall not be used to explicitly initialise members other
than the first, unless all items are explicitly initialised [JSF-145-2]
DESCRIPTION
"In enumerator list, the '=' construct shall not be used
to explicitly initialize members other than the first,
unless all items are explicitly initialized."

BENEFITS
Helps avoid errors and confusion.

EXAMPLE
enum TEST { /* Violation */
X = 1,
Y,
Z = 3,
};
enum TEST2 { /* Violation */
X2,
Y2 = 2,
Z2,
};
enum TEST3 { /* Violation */
X3,
Y3,
Z3 = 3,
};

REPAIR
enum TEST { /* OK */
X,
Y,
Z,
};

enum TEST2 { /* OK */
X2 = 1,
Y2,
Z2,
};
enum TEST3 { /* OK */
X3 = 1,
Y3 = 2,
Z3 = 3,
};

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Origin: Misra Guidelines - Rule 32
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-3

The underlying bit representations of floating point numbers shall not be used [JSF-147-2]
DESCRIPTION
The underlying bit representations of floating point numbers shall not be
used
in any way by the programmer.

BENEFITS
Prevents from casting with possible data losing.

EXAMPLE
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
long * pl;
pi
pi
ps
pl

=
=
=
=

(int*)pf;
(int*)pd;
(short*)pf;
(long*)pf;

/*
/*
/*
/*

Violation
Violation
Violation
Violation

REPAIR
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
pf = (float*)pd;
ps = (short*)pi;
}

/* OK */
/* OK */

*/
*/
*/
*/

REFERENCES
1. Origin: Misra Guidelines - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.17 Types, AV Rule 147

Enumeration types shall be used instead of integer types (and constants) as case labels [JSF148-2]
DESCRIPTION
Enumeration types shall be used instead of integer types (and constants)
to
select from a limited series of choices. Rule reports a violation message
if integer types (constants) are used as case labels.

SINCE
v7.1

EXCEPTIONS
This rule is not intended to exclude character constants (e.g. 'A', 'B'
etc.)
from use as case labels.

BENEFITS
Enhances debugging, readability and maintenance.
Note that a compiler flag (if available) should be set to generate a
warning
if all enumerators are not present in a switch statement.

EXAMPLE
void foo(int color)
{
switch(color)
{
case 1:
break;
case 2:
break;
case 3:
break;

// Violation
// Violation
// Violation

default:
break;
}
}

REPAIR
enum color
{
RED = 1,
BLUE = 2,
GREEN = 3
};
void foo(int color)
{
switch(color)
{
case RED:
break;
case BLUE:
break ;
case GREEN:
break;
default:
break;
}
}

// OK
// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 148

Octal constants (other than zero) and octal escape sequences shall not be used [JSF-149-2]
DESCRIPTION
"Any integer constant beginning with a '0' (zero) is treated as octal.
So there is a danger, for example, with writing fixed length constants.
Octal escape sequences can be problematic because the inadvertent
introduction of a decimal digit ends the octal escape and introduces
another character. It is better not to use octal constants or escape
sequences at all and to statically check for any occurrences.
The integer constant zero (written as a single numeric digit) is, strictly
speaking, an octal constant, but is a permitted exception to this rule.
Additionally \0 is the only permitted octal escape sequence."

EXCEPTIONS
Rule ignores any #pragma parasoft / codewizard directives.
Rule ignores any values inside asm blocks.

BENEFITS
Rule increases readability and maintainability.
Rule prevents using implementation-defined values.

EXAMPLE
void foo()
{
int code1;
int code2;
int code3;
code1 = 052;
/* Violation */
code2 = 071;
/* Violation */
code3 = '\100'; /* Violation */
}

REPAIR
void foo1()

{
int code1;
int code2;
int code3;
code1 = 42;
code2 = 57;
code3 = 64;

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 7
2. Origin: Misra Guidelines - Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 149
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-2

Hexadecimal constants will be represented using all uppercase letters [JSF-150-3]


DESCRIPTION
Hexadecimal constants will be represented using all uppercase letters.
See also: CODSTA-51

SINCE
v7.1

BENEFITS
Improved readability and maintenance.

EXAMPLE
int i = 0x3fff;

// Violation

REPAIR
int i = 0x3FFF;

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 150
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4

Avoid magic numbers [JSF-151-3]


DESCRIPTION
Avoid spelling literal constants in code. They are not self-explanatory.
Use symbolic values instead.
See also: CODSTA-29

NOTES
We excluded using literal constants in initialization.
We also skip usage of 0 or 1 because they are equivalent of true or false.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void boo(int);
int foo( int a[], int b ) {
int e;
int f = 0;
a[5] = 56; // Violation
e= 8;
// Violation
boo(56);
// Violation
return 8; // Violation
}

REPAIR
const int MAX = 8;

// OK

void boo(int);
int foo( float a[], float b ) {
int e;
int f = 0;
// OK
int i = 5;
// OK

a[i] = MAX;
e = MAX;
boo(a[5]);
return MAX;

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151

A string literal shall not be modified [JSF-151.1-2]


DESCRIPTION
A string literal shall not be modified. Rule reports violations if
a string literal is assigned to non-const variable, parameter or
expression.

SINCE
v7.1

BENEFITS
The effect of attempting to modify a string literal is undefined.

EXAMPLE
void moo(char * p)
{
}
void foo()
{
char* c1 = "Hello";
char c2[] = "Hello";
char c3[6] = "Hello";
char* c12;
c12 = "Hello";
moo("Hello");
}

// Violation
// Violation
// Violation
// Violation
// Violation

REPAIR
void moo(const char * p)
{
}
void foo()
{

const char* c1 = "Hello";


const char c2[] = "Hello";
const char c3[6] = "Hello";
const char* c12;
c12 = "Hello";
moo("Hello");
}

// OK
// OK
// OK
// OK
// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Multiple variable declarations shall not be allowed on the same line [JSF-152-2]
DESCRIPTION
Rule triggers if some variables are declared on the same line.
See also: FORMAT-33

NOTES
Violation is not reported if variables are declared by macros.

BENEFITS
Rule increases readability and prevents confusion.

EXAMPLE
void foo( ) {
int a, b;
}

// Violation

REPAIR
void foo( ) {
int a;
int b;
}

// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.19 Variables, AV Rule 152

Unions shall not be used [JSF-153-2]


DESCRIPTION
"Even when memory is being reused for related purposes,
there is still a risk that the data may be misinterpreted.
Therefore, this rule prohibits the use of unions for any purpose."

Note:
Rule reports a violation message on each union's declaration.

BENEFITS
Rule prevents undefined behaviour and erroneous code.

EXAMPLE
union U {
/* Violation */
int _i;
char _buf[ sizeof( int ) ];
};

REPAIR
Do not use union.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 97
3. Origin: Misra Guidelines - Rule 109

4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.20 Unions and Bit Fields, AV Rule 153
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 9, Rule 9-5-1

Bit fields shall only be defined to be of type unsigned int or signed int [JSF-154-2]
DESCRIPTION
"Bit fields shall only be defined to be of type unsigned int or signed
int.
Using int is implementation-defined because bit fields of type int can be
either signed or unsigned. The use of enum, short or char types for bit
fields
is not allowed because the behaviour is undefined."

BENEFITS
Prevents implementation-defined behaviour.

EXAMPLE
enum Enum { E1, E2};
struct Struct
{
unsigned char f1:2;
unsigned short f2:2;
unsigned long f3:2;
enum Enum
f4:2;
int
f5:2;
};

/*
/*
/*
/*
/*

Violation
Violation
Violation
Violation
Violation

REPAIR
struct Struct
{
unsigned int
unsigned int
unsigned int
signed int
signed int
};

REFERENCES

f1:2;
f2:2;
f3:2;
f4:2;
f5:2;

/*
/*
/*
/*
/*

OK
OK
OK
OK
OK

*/
*/
*/
*/
*/

*/
*/
*/
*/
*/

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 6
2. Origin: Misra Guidelines - Rule 111
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.20 Unions and Bit Fields, AV Rule 154

All the members of a structure (or union) shall be named [JSF-156-2]


DESCRIPTION
All the members of a structure (or union) shall be named.
The "bit field" facility in C is one of the most poorly defined parts
of the language. There are two main uses to which bit-fields could be put:
1) To access individual bits, or group of bits, in larger data-types,
in conjunction with unions (see rule 110).
2) To allow flags or other short-length data to be packed to save storage
space
The packing together of short-length data to economise on storage is the
only
acceptable use of bit fields envisaged in this document.
Provided the elements of the structure are only ever accessed by their
name,
the programmer needs to make no assumptions about the way the bit fields
are stored within the structure.
This rules checks that all declared bit fields have names.

BENEFITS
Prevents using unaccessible data.

EXAMPLE
typedef signed int t;
typedef int plain;
struct tag {
unsigned t:4;
const t:5;
/* Violation */
plain r:5;
};

REPAIR

Name all the members of a structure (or union).

REFERENCES
1. Origin:

Misra Guidelines rule 113

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.21 Operators, AV Rule 156

The right-hand operand of a logical && or || operator shall not contain side effects [JSF-157-2]
DESCRIPTION
"There are some situations in C or C++ where certain parts of expressions
may
not be evaluated. If these sub-expressions contain side effects then those
side
effects may or may not occur, depending on the values of other sub
expressions.
The operators which can lead to this problem are && and || where the
evaluation
of the right-hand operand is conditional on the value of the left-hand
operand.
The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
See also: MISRA2004-12_2_a, MISRA2004-12_4_b

NOTES
Rule checks only three nested level of function calls.

BENEFITS
Rule prevents conditional evaluation of the right-hand operand that can
easily
cause problems if the developer relies on a side effect occurring.

EXAMPLE
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i++)) ; // Violation
}

REPAIR

void foo( ) {
int i;
int j;
if ((j == i) || (0 == i)) i++; // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 33
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 157
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-14-1
5. ISO/DIS 26262
point 8.4.4

Each operand of a logical '&&' or '||' shall be a postfix-expression [JSF-158-2]


DESCRIPTION
The rule reports a violation if an operand other than a single identifier,
constant or function call is not parenthesised.
"Parentheses are important in this situation both for readability
of code and for ensuring that the behaviour is as the developer intended."
See also: MISRA2004-12_1_e, MISRA2004-12_5

SINCE
v7.3

EXCEPTIONS
"Where an expression consists of either a sequence of only logical '&&'
or a sequence of only logical '||', extra parentheses are not required.

BENEFITS
"The effect of this rule is to require that operands are appropriately
parenthesized."

EXAMPLE
int foo( int x, int y, int z )
{
if ( x || y && z );
// Violation
if ( x && !y );
// Violation
return 0;
}

REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
if ( x && ( !y ) );

// OK
// OK

return 0;
}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-1
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 158

Avoid overloading &&, || or , (comma) [JSF-159-2]


DESCRIPTION
"The built-in &&, || or, (comma) enjoy special treatment from the
compiler.
If you overload them, they become ordinary functions with very different
semantics, and this is a sure way to introduce subtle bugs and
fragilities."
This rule detects when you overload operator &&, || or ,(comma).

BENEFITS
Overloading these operators changes the way the compiler reads the
semantics of an expression, resulting in unpredictable program behavior.

EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
~A( );
int value( ) { return _i; }
private:
int _i;
};
int operator&&( A& lhs, A& rhs ) {
return lhs.value( ) && rhs.value( );
}

// Violation

REPAIR
Do not overload operator &&, || or ,(comma).

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,

(C) 2005 Pearson Education, Inc.


Chapter: "Functions and Operators", Rule 30
2. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 159
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-11
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Assignment operators shall not be used in expressions that yield a Boolean value [JSF-160-2]
DESCRIPTION
"No assignments are permitted in any expression which is considered to
have a
Boolean value. This precludes the use of both simple and compound
assignment
operators in the operands of a Boolean-valued expression. However, it does
not
preclude assigning a Boolean value to a variable. If assignments are
required
in the operands of a Boolean-valued expression then they must be performed
separately outside of those operands. This helps to avoid getting "=" and
"=="
confused, and assists the static detection of mistakes."

NOTES
An expression is considered to represent a Boolean value either because
it appears in a position where a Boolean value is expected or because it
uses an operator that gives rise to a Boolean value. Boolean values are
expected in the following contexts:
- the controlling expression of an if statement
- the controlling expression of an iteration statement
- the first operand of the conditional operator ?

BENEFITS
Rule prevents getting "=" and "==" confused.

EXAMPLE
void foo()
{
int x;
int y;
int z;
z = !(x = y);
if ((x > y) && (x = 4));

// Violation
// Violation

if (!(x = y));

// Violation

REPAIR
void foo()
{
int x;
int y;
int z;
z = !(x == y);
// OK
if ((x > y) && (x == 4)); // OK
if (!(x == y));
// OK
}

REFERENCES
1. Misra Guidelines - Rule 35
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 160
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-1

Avoid implicit conversions between signed and unsigned integer types [JSF-162_a-2]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = u32a;
s32b = s32a + u32a;

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = (signed int)u32a;

/* OK */

s32b = s32a + (signed int)u32b; /* OK */


}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions between signed and unsigned integer types [JSF-162_b-2]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used
when variables are initialized.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = u32a;
}

/* Violation */

REPAIR
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = (signed int)u32a;
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4

Use explicit type conversions for arithmetic using signed and unsigned values [JSF-162_c-2]
DESCRIPTION
"Mixing signed and unsigned values is error prone as it subjects
operations
to numerous arithmetic conversion and integral promotion rules."
The rule reports a violation if one operand of arithmetic binary
expression
is signed type and other is unsigned type. A violation is reported only if
both operands are non constant expressions.
The following binary arithmetic operators are checked:
'+', '-', '*', '/', '%', '^', '&', '|', '>>', '<<',
'+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '>>=', '<<='

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
void foo(signed char a, unsigned char b)
{
unsigned char c = a + b;
}

// Violation

REPAIR
void foo(signed char a, unsigned char b)
{
unsigned char c = (unsigned char)a + b;
}

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 8
2. Misra Guidelines - Rule 48

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.21 Operators, AV Rule 162

Unsigned arithmetic shall not be used [JSF-163-2]


DESCRIPTION
Unsigned arithmetic shall not be used.
Rule reports a violation message if type of
arithmetic expression operand is unsigned type.

SINCE
v7.1

BENEFITS
Over time, unsigned values will likely be mixed with signed values what
is error prone as it subjects operations to numerous arithmetic
conversion and integral promotion rules.

EXAMPLE
void foo(unsigned p)
{
unsigned int a = 0;
int b = 0;
b = p + a;

// Violation

REPAIR
void foo(signed p)
{
signed int a = 0;
int b = 0;
b = p + a;
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 163

The right-hand operand of a shift operator shall lie between zero and one less than the width
in bits of the underlying type of the left-hand operand [JSF-164-2]
DESCRIPTION
"If, for example, the left-hand operand of a left-shift or right-shift is
a
16-bit integer, then it is important to ensure that this is shifted only
by a
number between 0 and 15 inclusive.
There are various ways of ensuring this rule is followed. The simplest is
for
the right-hand operand to be a constant (whose value can then be
statically
checked). Use of an unsigned integer type will ensure that the operand is
non-negative, so then only the upper limit needs to be checked
(dynamically at
run-time or by review). Otherwise both limits will need to be checked."
The rule checks right-hand operand of shift operator and reports a
violation
in following cases:
- the operand is a constant with negative value or with value that exceeds
the length (in bits) of the left-hand operand
- the operand is a non-const variable and it's value is not checked by
specific
pattern.
The specific pattern recognized by the rule requires the shift operator
to be wrapped by an 'if' statement which checks the variable's value
using
comparison operators (both "greater then" and "less then" operators must
be used).

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )

uint8_t;
uint16_t;

{
uint8_t u8a;
u8a = (uint8_t) (u8a << 9); /* Violation */
u8a = (uint8_t) (u8a << p); /* Violation */
}

REPAIR
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
{
uint8_t u8a;
uint16_t u16a;

uint8_t;
uint16_t;

u16a = (uint16_t) ((uint16_t) u8a << 9); /* OK */


if (p >= 0 && p <= 8) {
u8a = (uint8_t) (u8a << p); /* OK - p range checked */
}
u8a = (uint8_t) (u8a << 4); /* OK - constant value in range */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-8-1

The left-hand operand of a right-shift operator shall not have a negative value [JSF-164.1-2]
DESCRIPTION
The rule reports a violation message if as left-hand operand of rightshift
operator is used one from the following options:
- constant with a negative value
- unary operator '-' followed by parameter, variable or expression
- parameter or variable of signed type
- expression of signed type that contains parameter, variable,
dereferenced
pointer or function call of signed type

SINCE
v7.1

BENEFITS
Rule prevents implementation-defined behaviours.
"For e1 >> e2, if e1 has a signed type and a negative value, the value
of (e1 >> e2) is implementation-defined."

EXAMPLE
void foo(signed int signed_param)
{
signed int signed_variable;
int variable;
signed int* ptr_signed_variable;
signed_param >> 5;
signed_variable >> 5;
-variable >> 5;
-100 >> 5;
-100u >> 5;
*ptr_signed_variable >> 5;
}

//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation

REPAIR
void foo(unsigned int unsigned_param)
{
unsigned int unsigned_variable;
int variable;
unsigned int* ptr_signed_variable;
unsigned_param >> 5;
unsigned_variable >> 5;
(unsigned int)variable >> 5;
100 >> 5;
100u >> 5;
*ptr_signed_variable >> 5;

//
//
//
//
//
//

OK
OK
OK
OK
OK
OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The unary minus operator shall not be applied to an expression whose underlying type is
unsigned [JSF-165-2]
DESCRIPTION
"Applying the unary minus operator to an expression of type unsigned int
or
unsigned long generates a result of type unsigned int or unsigned long
respectively and is not a meaningful operation. Applying unary minus to an
operand of smaller unsigned integer type may generate a meaningful signed
result
due to integral promotion, but this is not good practice."

BENEFITS
Prevents unexpected result due to integral promotion.

EXAMPLE
void foo() {
unsigned char ui1;
signed short si2;
si2 = -ui1;
}

// Violation

REPAIR
void foo() {
unsigned char ui1;
signed short si2;
si2 = -(signed short) ui1;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12

2. Origin: Misra Guidelines - Rule 39


3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 165
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-2

The sizeof operator shall not be used on expressions that contain side effects [JSF-166-3]
DESCRIPTION
"A possible programming error in C is to apply the sizeof operator to an
expression and expect the expression to be evaluated. However the
expression
is not evaluated: sizeof only acts on the type of the expression. To avoid
this
error, sizeof shall not be used on expressions that contain side effects,
as the side effects will not occur."
"The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."

NOTES
Rule checks only three nested level of function calls.

EXCEPTIONS
An operand of the form sizeof(i) where i is volatile is permitted.

BENEFITS
Prevents error that are caused by believing that operand of sizeof is
evaluated.

EXAMPLE
int glob;
int fun_with_se(){
glob++; // side-effect
return glob;
}
void foo1(int i){
int j, k, l, m;

j = sizeof(k = 2);
// Violation - k is not set to 2
l = sizeof(i++);
// Violation - i is not incremented
m = sizeof(fun_with_se()); // Violation - glob is not incremented
}

REPAIR
int fun_without_se(){
// no side-effect
return 1;
}
void foo1(int i){
int j, k, l, m, n, o;
volatile int vol;
k = 2;
j = sizeof(k);
i++;
l = sizeof(i);
// examples of correct code
m = sizeof(fun_without_se());
n = sizeof(int);
o = sizeof(vol);
}

// OK
// OK
// OK
// OK
// OK - volatile objects are permitted

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 166
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-4

Document integer division [JSF-167-2]


DESCRIPTION
The implementation of integer division in the
chosen compiler should be determined,
documented and taken into account.
This rule checks that, wherever there is an integer division
in the code, there must be comment on the previous line.

BENEFITS
Prevents unexpected loss of data/precision.

EXAMPLE
void foo()
{
int i=2;
int j=3;
int k;
k=j/i;

/* Violation - no comment before division*/

REPAIR
void boo()
{
int i=2;
int j=3;
int k;
/*

OK - comment before integer division */


k=i/j;

REFERENCES
1. Origin: Misra Guidelines - Rule 41

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.21 Operators, AV Rule 167

The comma operator shall not be used, except in the control expression of a for loop [JSF168_a-2]
DESCRIPTION
"Use of the comma operator in situations other than the control
expression
of a loop is generally detrimental to the readability of code, and the
same
effect can be achieved by other means"
See also: misra2004-12_10

BENEFITS
Extensive use of comma operator reduces readability.

EXAMPLE
void foo1( int x, int y )
{
int i;
i = (x = 1, y = 0);
x++, y++;
for (i = 0; i < 10; i++){
foo1( (x--, y + 2), y );
}
}

// Violation
// Violation
// Violation

REPAIR
void foo2( int x, int y ) {
int i;
x++;
y++;
for (i = 0; i >=0, i < 10; i++){
}
x--;
foo2( y + 2, y );
}

// OK
// OK

// OK

REFERENCES
1. Origin: Misra Guidelines - Rule 42
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 168

The comma operator shall not be used [JSF-168_b-2]


DESCRIPTION
"Use of the comma operator is generally detrimental to the readability of
code,
and the same effect can be achieved by other means."
See also: misra-042

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int x, y;
x = 0, y = 0;
}

// Violation

REPAIR
void foo() {
int x, y;
x = 0;
y = 0;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-18-1

Pointers to pointers should be avoided whenever possible [JSF-169-4]


DESCRIPTION
This rule detects if code uses pointers to pointers.
"Pointers to pointers should whenever possible be avoided.
By improving the readability of code, the probability of failure is
reduced."

EXCEPTIONS
"One exception to this rule is represented by functions which provide
interfaces to other languages (such as C). These are likely to only allow
pre-defined data types to be used as arguments in the interface, in which
case pointers to pointers are needed. Another example is the second
argument
to the main function, which must have the type char*[]."

BENEFITS
Rule improves the readability of the code and encourages data abstraction.

EXAMPLE
void foo() {
int** a; // Violation
}

REPAIR
Instead, declare a class that has
a member variable of the pointer type.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#12
From: 12 Pointers and References - Rec. 48

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.22 Pointers & References, AV Rule 169
3. ISO/DIS 26262
point 8.4.4

The error indicator errno shall not be used [JSF-17-2]


DESCRIPTION
"errno is a facility of C and C++, which in theory should be useful, but
which
in practice is poorly defined by the standard. A non zero value may or may
not
indicate that a problem has occurred; as a result it shall not be used.
Even for those functions for which the behaviour of errno is well defined,
it is preferable to check the values of inputs before calling the function
rather than rely on using errno to trap errors"

BENEFITS
The rule prevents undefined behaviours.

EXAMPLE
#include <errno.h>
int err_check( ) {
errno = 1;
return (errno);
}

/* Violation */
/* Violation */

REPAIR
Do not use errno.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 119
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 17

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 19, Rule 19-3-1

The declaration of objects should contain no more than 2 levels of pointer indirection [JSF170_a-2]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int * INTPTR;
struct s {
int *** s3;
};
struct s *** ps3;
int ** (***pfunc3)();
int *** ( **pfunc4)();
void function( int * par1,
int *** par3,
INTPTR * const * const par5
)
{

/* Violation */

/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */

int *** ptr3;


/* Violation */
INTPTR * const * const ptr5 = 0; /* Violation */
}

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4

The declaration of objects should contain no more than 2 levels of pointer indirection [JSF170_b-2]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int* apInt[] ;
apInt* rule12;
/* Violation */

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4

>, >=, <, <= shall not be applied to pointer types except where they point to the same array
[JSF-171-2]
DESCRIPTION
"Attempting to make comparisons between pointers will produce undefined
behaviour."

NOTES
"It is permissible to address the next element beyond the end of an array,
but accessing this element is not allowed."

EXCEPTIONS
"Both operands are of the same type and point to the same array"

BENEFITS
Rule makes the code more readable and less confusing.

DRAWBACKS
For more complex code rule may not be able to check if there is
applied pointer comparison to pointers which point the same array.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
}

=
=
=
=
=

a; i
p1;i
p2;i
p3;i
p4;i

=
=
=
=
=

p1
p2
p3
p4
p5

<
<
<
<
<

a;
a;
a;
a;
a;

//
//
//
//
//

OK
OK
OK
Violation - false positive
Violation - false positive

EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 < p2;
i = p2 < a;
i = p3 < a;

// Violation
// Violation
// OK

REPAIR
Do not apply pointer comparison to pointers that address elements
of different arrays

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 103
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 171
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-18

The address of an object with automatic storage shall not be assigned to another object that
may persist after the first object has ceased to exist [JSF-173-2]
DESCRIPTION
"If the address of an automatic object is assigned to another automatic
object
of larger scope, or to a static object, or returned from a function then
the
object containing the address may exist beyond the time when the original
object
ceases to exist (and its address becomes invalid). For example:
int * foo( void ) {
int local_auto;
return (&local_auto);
}"

BENEFITS
Prevents loss of data

EXAMPLE
int* global;
int* foo() {
int iLocal;
static int* siLocal;
siLocal = &iLocal;
global = &iLocal;
return &iLocal;
}
void goo() {
int* piLocal;
{
int iiLocal;
piLocal = &iiLocal;
}
}

// Violation
// Violation
// Violation

// Violation

REPAIR
Do not assign local address of object to more global,
or static object or return from function.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 106
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 173
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-2

The NULL pointer shall not be dereferenced [JSF-174_a-2]


DESCRIPTION
"Where a function returns a pointer and that pointer is subsequently
de-referenced, the program should first check that the pointer is not
NULL."
If a control statement contains in condition non-dereferenced pointer,
then
the rule assumes that this pointer is checked. In such cases rule does not
report violations in spite of it does not check if a control statement is
really used to prevent null pointer dereference.
See also: MISRA-107_b, BD-PB-NP

BENEFITS
Complying with this rule leads to safer code.

EXAMPLE
int* ret_ptr(int* p){
return p;
}
void func(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
/* here pointer 'ptr' should be checked */
i = *ptr;
/* Violation - pointer 'ptr' may be null */
}

REPAIR
int* ret_ptr(int* p){
return p;
}
int check(int* p){
if(p == 0)
return 0;

if(p > 0)
return 1;
}
void func1(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(ptr){
i = *ptr;
/* OK - pointer 'ptr' was checked in 'if' condition */
}
}
void func2(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(!ptr){
return;
}
i = *ptr;
/* OK - pointer 'ptr' was checked in 'if' condition */
}
void func3(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(check(ptr)){
i = *ptr;
/* OK - pointer 'ptr' was checked in 'check' function */
}
}
void func4(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(ptr == 0){
i = *ptr;
/* OK - pointer 'ptr' was checked in 'if' condition.
The 'if' condition is not correct, but the rule
does not check such cases. To detect this issue
could be used Bug Detectiv rule - BD-PB-NP */
}

REFERENCES
1. Origin: Misra Guidelines - Rule 107
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 174
3. http://cwe.mitre.org/data/definitions/476.html
4. ISO/DIS 26262
point 8.4.4

The NULL pointer shall not be dereferenced [JSF-174_b-2]


DESCRIPTION
"Where a function returns a pointer and that pointer is subsequently
de-referenced, the program should first check that the pointer is not
NULL."
If a control statement contains in condition non-dereferenced pointer,
then
the rule assumes that this pointer is checked. In such cases rule does not
report violations in spite of it does not check if a control statement is
really used to prevent null pointer dereference.
See also: MISRA-107_a, BD-PB-NP

BENEFITS
Complying with this rule leads to safer code.

EXAMPLE
struct S{
int si;
};
struct S* ret_ptr(struct S* p){
return p;
}
void func(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
/* here pointer 's' should be checked */
s->si = i;
/* Violation - pointer 's' may be null */
}

REPAIR
struct S{
int si;

};
struct S* ret_ptr(struct S* p){
return p;
}
int check(struct S* p){
if(p == 0)
return 0;
if(p > 0)
return 1;
}
void func1(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(s){
s->si = i;
/* OK - pointer 's' was checked in 'if' condition */
}
}
void func2(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(!s){
return;
}
s->si = i;
/* OK - pointer 's' was checked in 'if' condition */
}
void func3(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(check(s)){
s->si = i;
/* OK - pointer 's' was checked in 'check' function */
}

}
void func4(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(s == 0){
s->si = i;
/* OK - pointer 's' was checked in 'if' condition.
The 'if' condition is not correct, but the rule
does not check such cases. To detect this issue
could be used Bug Detectiv rule - BD-PB-NP */
}
}

REFERENCES
1. Origin: Misra Guidelines - Rule 107
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 174
3. http://cwe.mitre.org/data/definitions/476.html
4. ISO/DIS 26262
point 8.4.4

Do not compare a pointer to NULL or assign NULL to a pointer; use 0 instead [JSF-175-2]
DESCRIPTION
This rule detects code that compares a pointer to NULL or assigns NULL
to a pointer. "Do not compare a pointer to NULL or assign NULL to a
pointer; use 0 instead."

BENEFITS
According to the ANSI-C standard, NULL is defined either as (void*)0 or as
0.
If this definition remains in ANSI-C++, problems may arise.
If NULL is defined to have the type void*, it cannot be assigned an
arbitrary
pointer without an explicit type conversion.

EXAMPLE
#include <stddef.h>
void foo( ) {
int *lp = NULL; // Violation
}

REPAIR
#include <stddef.h>
void foo( ) {
int *lp = 0; // OK
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rule 42
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 175

Use a typedef to simplify program syntax when declaring function pointers [JSF-176-3]
DESCRIPTION
"Use a typedef to simplify program syntax when declaring function
pointers."

BENEFITS
"Another reason to use typedef is that the readability of the code is
improved.
If pointers to functions are used, the resulting code can be almost
unreadable.
By making a type declaration for the function type, this is avoided."

EXAMPLE
void (*p)();

// Violation

REPAIR
typedef void (*PTF)();
PTF p;

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rec. 49
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 176

Do not use user-defined conversion functions [JSF-177-4]


DESCRIPTION
Be wary of user-defined conversion functions. This rule warns you when it
finds
user-defined conversion functions. Such calls may in the best case result
in
creating and destroying temporary objects, affecting runtime, and in the
worst,
allow the most meaningless code to compile. In the latter case, problems
that
could be detected at compile time are pushed to run-time testing.
See also: CODSTA-CPP-04

BENEFITS
Generally improves runtime performance and predictability of program
behavior. May detect severe coding defects masked by the compiler.

EXAMPLE
class A {
public:
operator const char*( ) const;
};

// Violation

void foo(){
A a;
const char* ch_ptr = a; // implicit conversion
}

REPAIR
class A {
public:
const char* asPointerToConstChar( ) const; // OK
};
void foo(){
A a;

const char* ch_ptr = a.asPointerToConstChar(); // explicit conversion


}

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 5
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 177

Avoid casts down the inheritance hierarchy [JSF-178-2]


DESCRIPTION
Avoid casts down the inheritance hierarchy.
This rule detects casts from a base class pointer to a subclass pointer.

BENEFITS
Allowing casts down the inheritance hierarchy leads to maintenance
problems,
and downcasting from a base class is always illegal.

EXAMPLE
class Base {};
class Derived: public Base {};
class Derived2: public Derived {};
void foo() {
Base *pb;
Derived *pd = (Derived *) pb;
Base *pb2;
Derived *pd2 = (Derived2 *) pb2;

// Violation

// Violation

REPAIR
class Base {};
void foo() {
Base *pb0;
Base *pd0 = (Base *) pb0;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,

Chapter: "Inheritance and Object-Oriented Design", Item 39


2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 178

A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of
dynamic_cast [JSF-179-2]
DESCRIPTION
"Since the virtualness of inheritance is not a property of a base class,
the layout of a derived class object, referenced through a virtual base
pointer, is unknown at compile time."
"Casting from a virtual base to a derived class, using any means
other than dynamic_cast has undefined behaviour.
The behaviour for dynamic_cast is defined."
See also: OOP-29, OOP-49

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviours.

EXAMPLE
// The code is not compilable with all compilers
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = static_cast<D*>(pB); // Violation
}

REPAIR

class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = dynamic_cast<D*>(pB);
}

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 179
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-2

The macro offsetof, in library stddef.h, shall not be used [JSF-18-2]


DESCRIPTION
"Use of this macro can lead to undefined behaviour
when the types of the operands are incompatible or
when bit fields are used."
Rule reports a violation message if the offsetof
macro is used and the file includes any of the
following headers: stddef.h, stddef, or cstddef.

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
// Violation - The macro offsetof shall not be used. Macro is in line:
[10]
#include <stddef.h>
struct S {
int x, y, z;
char buffer[ 128 ];
};
int main( ) {
int i = offsetof( struct S, buffer );
return 0;
}

REPAIR
Do not use offsetof.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20

2. Origin: Misra Guidelines - Rule 120


3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 18
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-2-1

Implicit conversions which may result in a loss of information shall not be used [JSF-180_a-2]
DESCRIPTION
"C performs many type conversions implicitly and silently, so as to
harmonize
types within an expression before evaluating it. Some of these conversions
can
result in loss of information. Such implicit conversions shall not be
used,
but explicit casts should be used instead."
The rule reports a violation if a parameter/variable/expression of
integral
or floating type is implicitly cast to a narrower type.
See also: MISRA2004-10_1_b, MISRA2004-10_2, PORT-27, PORT-28

NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
float < double < long double
The rule assumes that the size of enumeration type is the same as int
type.

EXCEPTIONS
The rule does not report violation if a conversion is used:
- on a constant expression
- between integral and floating type
- between signed and unsigned type
- on a bit field

BENEFITS
"Explicit casts should normally only be used in the case where a
conversion
which could result in a loss of information is specifically required by
the
programmer. If the static checking of implicit conversions is overridden
by
the use of explicit casts in this way, then the programmer should be aware

of the issues of truncation and lost of precision associated with the


operation,
and should provide appropriate checking of values in the code"

EXAMPLE
void bar(unsigned char c);
void foo(unsigned int ui, double d)
{
float f;
unsigned short us1;
unsigned short us2 = ui; /* Violation
us1 = us2 + us2;
/* Violation
f = d;
/* Violation
bar(ui);
/* Violation
}

*/
- due to integral promotion */
*/
*/

REPAIR

void bar(unsigned char c);


void foo(unsigned int ui, double d)
{
float f;
unsigned short us = (unsigned short)ui; /* OK */
f = (float)d;
/* OK */
bar((unsigned char)ui);
/* OK */
}
/* exceptions */
void except(unsigned int ui){
unsigned char uc = 300;
/* OK - constant expression */
int i = ui;
/* OK - only signed/unsigned conversion */
float f = ui;
/* OK - integral/floating conversion */
}

REFERENCES

1. Origin: Misra Guidelines rule 43


2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 180

Avoid implicit conversions between integer and floating types [JSF-180_c-2]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between integer and floating types are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
float f32a;
unsigned int u32a;
f32a = u32a;
f32a = f32a + u32a;
f32a = u32a + 2.5f;
}

REPAIR
void Conv1_int( ) {
float f32a;
unsigned int u32a;

/* Violation */
/* Violation */
/* Violation */

f32a = (float)u32a;
f32a = f32a + (float)u32a;
f32a = (float)u32a + 2.5f;

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of complex expressions [JSF-180_d-2]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
"The intention when restricting implicit conversion of complex expressions
is to require that in a sequence of arithmetic operations within an
expression,
all operations should be conducted in exactly the same arithmetic type.
Notice that this does not imply that all operands in an expression are
of the same type.
The expression u32a + u16b + u16c is compliant - both additions will
notionally
be performed in type U32.
The expression u16a + u16b + u32c is not compliant - the first addition
is notionally performed in type U16 and the second in type U32.
The word 'notionally' is used because, in practice, the type in which
arithmetic will be conducted will depend on the implemented size of an
int."
Rule checks if implicit conversions of complex expressions are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;

u32a = u16b + u16a + u32b;


u32a = u32b + (u16a + u16b);

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
u32a = u32b + u16b + u16a;
u32a = u16b + (u16a + u32b);

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions from wider to narrower types [JSF-180_e-2]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted
to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always
conducted on integer operands of type int or long (signed or unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation.
The underlying type of an integer constant expression will be determined
according to its magnitude and signedness"
The rule reports a violation if parameter/variable/expression of integral
type is implicitly converted to a narrower integral type.

SINCE
v7.0

NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
The underlying type of an integer constant is determined according
to its magnitude and signedness.

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = u32a;
u8a = u32a;

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = (unsigned short)u32a;
u8a = (unsigned char)u32a;

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6

Avoid implicit conversions of function return expressions [JSF-180_f-2]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type if the expression is not constant
and is a return expression.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always conducted on integer operands of type int or long (signed or
unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation."
Rule checks if implicit conversions of function return expressions are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
unsigned int Conv_ret1( signed char a )
{
return a;
/* Violation */
}

REPAIR
unsigned int Conv_ret1( signed char a )

{
return (unsigned int)a;

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of function arguments [JSF-180_h-2]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type if the expression is not
constant and is a function argument.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always conducted on integer operands of type int or long (signed or
unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation."
Rule checks if implicit conversions of function arguments are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double(si);
/* Violation */
takes_unsigned_int(uc);
/* Violation */
takes_signed_int(ui);
/* Violation */
}

REPAIR
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double((double) si);
takes_unsigned_int(ui);
takes_signed_int((int) ui);
}

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4

Redundant explicit cast to the same type is not allowed [JSF-181_a-3]


DESCRIPTION
"Explicit casting between identical types is unnecessary and clutters
code.
Furthermore it can mask problems if changes are made to the code (e.g. one
of
the types changes and a conversion with possible loss of information
occurs)"

SINCE
v7.2

BENEFITS
"The use of casting should be sufficient to cause the calculations
required
to occur with the desired precision. Unnecessary casting adds the
possibility
of confusion, and may be such that its interaction with the rules of
promotion
leads to results other than those expected. Unnecessary casting may also
lead
to code which is harder to maintain, should the types of variables
change."

EXAMPLE
typedef int INT;
int someFunction1();
INT someFunction2();
void foo(int p)
{
/* ... */
p = (int)someFunction1();
p = (int)someFunction2();
}

// Violation
// Violation

REPAIR
typedef int INT;
int someFunction1();
INT someFunction2();
void foo(int p)
{
/* ... */
p = someFunction1();
p = someFunction2();
}

// OK
// OK

REFERENCES
1. Origin: Misra Guidelines - Rule 44
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 181

Avoid explicit cast from derived to a base class [JSF-181_b-3]


DESCRIPTION
This rule reports violation on any explicit cast from derived to base
class.
Such casts are usually unnecessary and scope resolution operator "::" can
be used instead.
Rarely the "::" operator is not applicable. In such cases we recommend to
rewrite the code to avoid using explicit casts.
Explicit casts can be a source of serious and hard to detect errors.
For example the result of cast can be incorrect if the class definition is
not
visible (if only forward declaration is seen). At the moment of adding the
cast the class definition is visible (e.g. because appropriate header is
included), but later the #include is removed and only forward declaration
is
left. The result of cast might not be correct and program behavior
changes,
which passes unnoticed due to explicit cast.

BENEFITS
Simplifies code, protects from errors.

EXAMPLE
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = (Base *)d;
}
class Base1 {
int f();
};
class Base2 {
int f();
};

};

// Violation

class Derived1 : public Base1, public Base2 { };


int Func1() {
Derived1 *d = new Derived1();
return (static_cast<Base1*>(d))->f();
// Violation
}
class Child1 : public Base1 {};
class Child2 : public Base1 {};
void foo(Child1* c1, Child2* c2, bool b) {
Base1* p = b ? (Base1*)c1 : (Base1*)c2;
}

// Violation

REPAIR
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = d;
}

};

// OK - cast removed

class Base1 {
int f();
};
class Base2 {
int f();
};
class Derived1 : public Base1, public Base2 { };
int Func1() {
Derived1 *d = new Derived1();
return d->Base1::f();
// OK - scope operator used
}
class Child1 : public Base1 {};
class Child2 : public Base1 {};
void foo(Child1* c1, Child2* c2, bool b) {
Base1* p = 0;
if (b) {
p = c1;
// OK - code rewritten
} else {
p = c2;
// OK - code rewritten
}
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 181

A cast should not convert a pointer type to an integral type [JSF-182_a-2]


DESCRIPTION
"The size of integer that is required when a pointer is converted to an
integer
is implementation-defined. Casting between a pointer and an integer type
should
be avoided where possible, but may be unavoidable when addressing memory
mapped
registers or other hardware specific features."

EXCEPTIONS
The rule allows to cast to UINT_PTR or INT_PTR type. These types are
integral
types that scale to the size of a pointer for both 32-bit and 64-bit
Windows.

BENEFITS
Prevents undefined or implementation-defined behaviour.

EXAMPLE
void foo( ) {
int* pi;
int i;
i = (int) pi;
}

// Violation

REPAIR
Do not cast pointers to non-pointers.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 11
2. Misra Guidelines rule 45
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 7
4. http://msdn2.microsoft.com/en-gb/library/aa489560.aspx
5. http://www.codeproject.com/system/64BitOSAndPortingIssues.asp
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
7. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-9
8. ISO/DIS 26262
point 8.4.4

A cast should not convert an integral type to a pointer type [JSF-182_b-2]


DESCRIPTION
Integral types shall not be cast to pointers. Problems can arise when
an arbitrary integer is converted to a pointer.

EXCEPTIONS
The rule allows to cast integer constant '0' to pointer type.

BENEFITS
Rule prevents undefined or implementation-defined behaviour.

EXAMPLE
void foo( ) {
int* pi;
int i;
pi = (int*)i;
}

// Violation

REPAIR
Do not cast non-pointers to pointers.

REFERENCES
1. Origin: Misra Guidelines rule 45
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
4. ISO/DIS 26262

point 8.4.4

Never use explicit type conversions (casts) [JSF-183-4]


DESCRIPTION
"Never use explicit type conversions (casts)."

NOTES
Rule is limited to primitive types only.

EXCEPTIONS
Explicit type conversions may be used to convert a pointer to a base class
to a pointer of a derived class.
Explicit type conversion must be used to convert an anonymous bit-stream
to an object.
Generally, explicit type conversions are needed for reading an external
representation of an object.

BENEFITS
Rule improves clarity and maintainability of code.

EXAMPLE
void foo( ) {
const int ci = 0;
int i;
i = (int) ci;
// Violation
i = (int) &i;
// Violation
}

REPAIR
Do not use casts.

REFERENCES

1. Ellemtel Coding Standards


http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 13 Type Conversions - Rule 43
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 183

Avoid implicit conversions of float type resulting in a loss of information [JSF-184_a-2]


DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}

REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;

// Violation
// Violation
// Violation

float32_t f32bt = (float)f64a;


// OK
unsigned int u32a = (unsigned int)f32a;
// OK
unsigned short u16a = (unsigned short)1.0; // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of float type resulting in a loss of information [JSF-184_b-2]


DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a

=
=
=
=

f32a;
f32a;
f64a;
f32b + f32a + f64b;

REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;

//
//
//
//

Violation
Violation
Violation
Violation

u32b
s32b
f32a
f64a

=
=
=
=

(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

Prefer C++-style casts [JSF-185-2]


DESCRIPTION
This rule detects C-style casts in your code.
"Traditional C-style casts raise several concerns. First, they enable most
any
type to be converted to most any other type without any indication of the
reason
for the conversion. Next, the C-style cast syntax: '(type) expression'
is difficult to identify for both reviewers and tools. Consequently,
both the location of conversion expressions as well as the subsequent
analysis
of the conversion rationale proves difficult for C-style casts.
Thus, C++ introduces several new-style casts (const_cast, dynamic_cast,
reinterpret_cast, and static_cast) that address these problems.
Not only are these casts easy to identify, but they also communicate more
precisely the developers intent for applying a cast."

BENEFITS
"Programs that use the new casts are easier to parse
(both for humans and for tools), and they allow compilers
to diagnose casting errors that would otherwise go undetected."

EXAMPLE
void foo1(){
int i, j;
double d = (double)i/j;
}

// Violation

class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = (Derived*)b;

// Violation

REPAIR
void foo1(){
int i, j;
double d = static_cast<double>(i)/j;
}

// OK

class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = dynamic_cast<Derived*>(b);
}

// OK

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Basics", Item 2
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 95
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 185

There shall be no unreachable code in "else" block [JSF-186_a-2]


DESCRIPTION
There shall be no unreachable code in "else" statement.
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
See also: MISRA2004-14_1_b, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo(int a, int b)
{
if(a == a){
a = a + b;
}
else{
// Violation
a = a - b;
}
}

REPAIR
void foo(int a, int b)
{
if(a == 3){
a = a + b;
}

else{
a = a - b;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code after 'return', 'break', 'continue', and 'goto' statements
[JSF-186_b-2]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code after 'return', 'break',
'continue' and 'goto' statements.
See also: MISRA2004-14_1_a, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// Violation
foo();
case 2:
j = 3;
return j; // Violation
foo();
}
}

REPAIR
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// OK
case 2:
j = 3;
return j; // OK
}
foo();
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code in "if/else/while/for" block [JSF-186_c-2]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code inside if/while/for/else block if in a
condition
a constant value is used.
See also: The groups of rules MISRA2004-14_1 and MISRA2004-13_7

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo()
{
int unreachable_code = 1;
if(0)
{
unreachable_code = 2;
}
}

// Violation

REPAIR
There shall be no unreachable code

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code in switch statement [JSF-186_d-2]


DESCRIPTION
There shall be no unreachable code in "switch" statement.
Rule detects statements, expressions placed outside case and default body.
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo( int i ) {
switch (i) {
// Violation
i = 0;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}

REPAIR
void foo( int i ) {
switch (i) {
// OK
case 0:
i = 0;
break;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code in 'for' loop [JSF-186_e-2]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation if a 'for' loop contains in condition single
relational expression 'VAR < FB', 'VAR <= FB', 'FB > VAR', 'FB >= VAR'
that result is always false, where FB is a constant or a const variable
and VAR is a variable assigned in for-init-statement.
If a result of for-condition is always false then a body is never
executed.
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_f, MISRA2004-14_1_g

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo( int i, int j )
{
for ( i = 0; i < 0; i++ )
{
j = 1;
}
}

// Violation

REPAIR
void foo( int i, int j )
{
for ( i = 0; i < 5; i++ )
{
j = 1;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code after 'if' or 'switch' statement [JSF-186_f-2]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation if:
- the code is after 'if/else' construction, where each branch has
unconditional
'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_g

SINCE
v7.0

NOTES
This rule does not report violations on the code inside loop.
Rule MISRA2004-14_1_g reports violations on the code inside loop.

BENEFITS
Rule helps avoid useless code.

EXAMPLE
int foo1( int c ) {
if ( c > 2 ) {

// Violation

return 0;
} else {
return 1;
}
return c;

// unreachable code

}
int foo2( int i ) {
switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return 2;
}
return i;
}

// Violation

// unreachable code

REPAIR
int foo1( int
if ( c > 2
return
} else {
return
}
}

c ) {
) {
0;

// OK

c;

int foo2( int i ) {


switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return i;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code after "if" or "switch" statement inside while/for/do...while
loop [JSF-186_g-2]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation on the code inside loop if:
- the code is after 'if/else' construction, where each branch has
unconditional
'break', 'continue' or 'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_f

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
int foo( int c ) {
while ( c > 1 ) {
if ( c > 2 ) {
continue;
} else {
break;
}

// Violation

c++;

// unreachable code

}
for (int i = 0; i > 1; i++ ) {
switch(i){
// Violation
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}
c++;
// unreachable code
}
return c;
}

REPAIR
int foo( int c ) {
while ( c > 1 ) {
c++;
if ( c > 2 ) {
continue;
} else {
break;
}
}

// OK

for (int i = 0; i > 1; i++ ) {


c++;
switch(i){
// OK
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}

}
return c;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

All non-null statements shall either have at least one side-effect however executed or cause
control flow to change [JSF-187-2]
DESCRIPTION
"Any statement (other than a null statement) which has no side effect and
does
not result in a change of control flow will normally indicate a
programming
error, and therefore a static check for such statements shall be
performed."
A side effect and null statement are defined by ISO/IEC 9899:1999
standard.
"Accessing a volatile object, modifying an object, modifying a file,
or calling a function that does any of those operations are all side
effects,
which are changes in the state of the execution environment."
"A null statement (consisting of just a semicolon) performs no
operations."
For example, if an expression evaluation result is not used, because
a programmer forgot to use assignment operator to store the value,
or because he accidentally wrote "==" instead of "=", the statement
is considered not to have a side effect. Such programming errors
are potentially disastrous.

NOTES
Empty function body is not considered as violating this rule.
For purposes of this rule any function call is considered as
having side effects, even if no variable is modified as a result
of the function call.
The rule does not report violations on empty blocks.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE

struct tagStruct {
int _iField;
char * _p;
};
int bar( );
void foo( ) {
int i = 0;
struct tagStruct s, *ps;
/* Examples of incorrect code - no side effects: */
i + 3;
/* Violation - result not
3;
/* Violation - result not
i;
/* Violation - result not
i + bar();
/* Violation - result not
ps->_p + s._iField;
/* Violation - result not
ps->_iField << s._iField; /* Violation - result not
*(ps->_p);
/* Violation - result not
}

used
used
used
used
used
used
used

REPAIR
struct tagStruct{
int _iField;
char * _p;
};
volatile struct tagStruct volStr;
int bar( );
void foo( ) {
int i = 0;
volatile int j = 0;
struct tagStruct s, *ps;
/* Examples of correct code - with side effects: */
i = i + 3;
/* OK - assignment */
i <<= 3;
/* OK - assignment */
bar();
/* OK - function call */
j;
/* OK - volatile variable */
volStr._p;
/* OK - volatile variable */

*/
*/
*/
*/
*/
*/
*/

if(ps->_iField){}

/* OK - cause control flow to change */

;
{}

/* OK - null statement */
/* OK - empty block */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
system
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 53
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 187

Do not use labels [JSF-188-3]


DESCRIPTION
Labels should not be used, except in switch statements.

BENEFITS
Using labels can lead to errors and confusion.

EXAMPLE
void foo(int count)
{
/* ... */
goto stop_operation;
/* ... */
stop_operation: return; /* Violation */
/* ... */
}

REPAIR
Do not use labels in your code, except in switch statements.

REFERENCES
1. Origin: Misra Guidelines - Rule 55
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 188

The goto statement shall not be used [JSF-189-3]


DESCRIPTION
The goto statement shall not be used.

BENEFITS
The goto statement can lead to errors and confusion.

EXAMPLE
int foo( int a ) {
if (a < 0) {
goto end;
}
a = foo(a-1);
end:
return a+1;
}

/* Violation */

REPAIR
int foo( int a ) {
/* Code was changed and does not use goto anymore */
if (a >= 0) {
a = foo(a-1);
}
return a+1;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 49

3. Misra Guidelines - Rule 56


4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 189
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1
6. HIS Source Code Metriken, version 1.3.1
Metrik "GOTO"
7. ISO/DIS 26262
point 8.4.4

Do not use locale.h header and setlocale function [JSF-19-2]


DESCRIPTION
<locale.h> and the setlocale function shall not be used.

BENEFITS
Prevents changing the locate from the standard C locate.

EXAMPLE
#include <locale.h>
void foo(void)
{
/* Set the locale back to the default environment */
setlocale(LC_ALL, "C"); /* Violation */
}

REPAIR
Do not use 'setlocale' functions.

REFERENCES
1. Origin: Misra Guidelines - Rule 121
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 19

The continue statement shall not be used [JSF-190-2]


DESCRIPTION
"Avoid the use of continue. continue can be used to exit from loops.
However, code may be more comprehensible by using an else clause instead."

BENEFITS
Rule prevents using 'continue' which can lead to errors and confusion.

EXAMPLE
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
continue;
}
i /= 2;
}
}

/* Violation */

REPAIR
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
/* OK - code was changed and does not use continue anymore */
} else {
i /= 2;
}
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rec. 53
3. Origin: Misra Guidelines - Rule 57
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 190
5. ISO/DIS 26262
point 8.4.4

Do not use the break statement [JSF-191-2]


DESCRIPTION
The break statement shall not be used
(except to terminate the cases of a switch statement).

BENEFITS
Using 'break' can lead to errors and confusion.

EXAMPLE
#define true 1
void foo(int i)
{
while (true)
{
if (i==10)
{
break; /* Violation */
}
}
switch( i )
{
case -1:
while (true)
{
if (i==10)
{
break; /* Violation */
}
}
}
}

REPAIR
#define true 1
void foo(int i)

{
switch( i )
{
case -1 :
break; /* OK */
case 0 :
break; /* OK */
default:
break; /* OK */
}
}

REFERENCES
1. Origin: Misra Guidelines - Rule 58
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 191
3. ISO/DIS 26262
point 8.4.4

All 'if...else-if' constructs shall be terminated with an 'else' clause [JSF-192-3]


DESCRIPTION
"This rule applies whenever an 'if' statement is followed by one or more
'else-if' statements; the final 'else-if' shall be followed by an 'else'
statement. In the case of a simple 'if' statement then the 'else'
statement
need not be included.
The requirement for a final 'else' statement is defensive programming.
The 'else' statement should either take appropriate action or contain
a suitable comment as to why no action is taken."
See also: CODSTA-23

BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.

EXAMPLE
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
}

// Violation

REPAIR
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}

// OK

else
{
// comment or action
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 60
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 192
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-2

An unconditional break statement shall terminate every non-empty switch clause [JSF-193-2]
DESCRIPTION
"The last statement in every switch clause shall be a break statement,
or if the switch clause is a compound statement, then the last statement
in the compound statement shall be a break statement."

NOTES
This rule allows also to use return instead break statement.

BENEFITS
Prevents unpredictable program behaviour.

EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
case 2 :
{
i = 3;
}
default:
i = 8;
}
}

// Violation

// Violation

// Violation

// Violation

REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
break;
}
}

// OK

// OK

// OK

// OK - empty case
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Misra Guidelines - Rule 61
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 47

4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.24 Flow Control Structures, AV Rule 193

Always provide a default branch for switch statements [JSF-194-2]


DESCRIPTION
"A switch statement must always contain a default branch
which handles unexpected cases."
This rule detects if you fail to provide a default branch
for switch statements. If all desired cases are handled
outside of default, then default can be used for error
checking.
See also: MISRA2004-15_3

BENEFITS
Rule prevents possibility of erroneous code.

EXAMPLE
void foo( ) {
int tag;
switch ( tag ) {// Violation
case 0: {
break;
}
case 1: {
foo( );
break;
}
}
}

REPAIR
void foo( ) {
int tag;
switch ( tag ) {// OK
case 0: {
break;
}
case 1: {
foo( );

break;
}
default: break;
}
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 48
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 194

A switch expression shall not represent a value that is effectively Boolean [JSF-195-3]
DESCRIPTION
Values which are effectively Boolean should not be represented in
'switch' condition.
The rule forbids following operators:
a) equality operators (== and !=)
b) logical operators (!, && and ||)
c) relational operators (<, >, <= and >=)
which produce boolean-by-construct values.

BENEFITS
Rule prevents using values that are effectively Boolean in switch.

EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}

// Violation

REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}

REFERENCES

// OK

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 63
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 195
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-7

Every switch statement will have at least two cases and a potential default [JSF-196-3]
DESCRIPTION
Every switch statement will have at least two cases and a potential
default.
See also: CODSTA-41, MISRA2004-15_5

SINCE
v7.1

BENEFITS
An if statement provides a more natural representation.

EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}

// Violation

REPAIR
void foo(int i)
{
switch(i)
{
case 1:
break;
case 2:
break;
default:
;
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 196

Do not use floating point variables as loop counters [JSF-197-2]


DESCRIPTION
Floating point variables shall not be used as loop counters.

BENEFITS
Prevents giving unexpected results when the variable is tested.

EXAMPLE
void foo()
{
float i;
for (i=0.;i<10.;i++)
{
}
}

/* Violation */

REPAIR
void foo()
{
int i;
for (i=0;i<10;i++) /* OK */
{
}
}

REFERENCES
1. Origin: Misra Guidelines - Rule 65
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 197

The initialization expression in a for loop will perform no actions other than to initialize the
value of a single for loop parameter [JSF-198-3]
DESCRIPTION
The initialization expression in a for loop will perform no actions other
than
to initialize the value of a single for loop parameter.
Note that the initialization expression may invoke an accessor that
returns
an initial element in a sequence:
for (Iter_type p = c.begin() ; p != c.end() ; ++p) // Good
{
// ...
}

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo()
{
int k = 0;
/* ... */
for(; k>0; k--){}
for(int i=0, k=2; k>0; k--){}
for(int i = k+2-10; k>0; k--){}
for(k--; k>0; k--){}
}

REPAIR

//
//
//
//

Violation
Violation
Violation
Violation

class A
{
public:
int i;
int moo();
};
void foo()
{
int k = 0;
A obj;
/* ... */
for(k=2; k>0; k--){}
for(int i =0; i>0; i--){}
for(k = obj.i; k>0; k--){}
for(k = obj.moo(); k>0; k--){}
}

//
//
//
//

OK
OK
OK
OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 198

The increment expression in a for loop will perform no action other than to change a single
loop parameter to the next value for the loop [JSF-199-3]
DESCRIPTION
The increment expression in a for loop will perform no action other
than to change a single loop parameter to the next value for the loop

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo()
{
int k = 0;
for(;k>0; ){}
// Violation
for(int i=0; k>0; k--, i++){} // Violation
for(k--; k>0; k+1){}
// Violation
}

REPAIR
void zoo(){}
class A
{
public:
int i;
};
void foo()
{
int k = 0;

A obj;
for(int i = k+2-10; k>0; zoo()){}
for(k=2; k>0; k--){}
for(int i =0; i>0; i=i-1){}
for(k = obj.i; k>0; k-=1){}

//
//
//
//

OK
OK
OK
OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 199

The setjmp macro and the longjmp function shall not be used [JSF-20-2]
DESCRIPTION
"setjmp and longjmp allow the normal function call mechanisms to be
bypassed,
and shall not be used."
Rule reports a violation message if setjmp or longjmp is used and the file
includes any of the following headers: setjmp.h, setjmp, or csetjmp.

BENEFITS
Rule prevents normal function call mechanisms from being bypassed.

EXAMPLE
#include <setjmp.h>
jmp_buf mark;
int
fperr;
void foo( void ) {
int jmpret;
jmpret = setjmp( mark );
}

/* Address for long jump to jump to */


/* Global error number */

/* Violation */

void fphandler( int sig, int num ) {


longjmp( mark, -1 );
/* Violation */
}

REPAIR
Do not use the setjmp macro and the longjmp function.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 122

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.5 Libraries, AV Rule 20
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-5
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1

Null initialize or increment expressions in for loops will not be used; a while loop will be used
instead [JSF-200-3]
DESCRIPTION
Null initialize or increment expressions in for loops
will not be used; a while loop will be used instead.
Rule reports a violation message if 'for' statement
misses init or increment section.

SINCE
v7.1

BENEFITS
A while loop provides a more natural representation.

EXAMPLE
void foo()
{
for(int i=0; i< 10;) // Violation
{
/* ... */
}
int j = 0;
for(; j< 10;)
{
/* ... */
}
}

REPAIR
void foo()
{
int i = 0;

// Violation

while(i< 10)
{
/* ... */
}

// OK

int j = 0;
while(j< 10)
{
/* ... */
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 200

Do not modify for loop counter within a body of the loop [JSF-201-2]
DESCRIPTION
"Loop counters shall not be modified in the body of the loop.
However other loop control variables representing logical values
may be modified in the loop, for example a flag to indicate that something
has been completed, which is then tested in the for statement."

NOTES
A
-

loop-counter is a loop-control-variable that is:


Initialized in, or prior to, for-init-statement; and
an operand to a relational operator in condition; and
modified in expression.

BENEFITS
Modification 'for' loop counter within a body of the loop can lead to
errors and confusion.

EXAMPLE
void foo( ) {
int i;
for ( i = 0; i < 5; i++ ) {
i = i + 3;
}
}

/* Violation */

REPAIR
void foo( ) {
int i;
for ( i = 0; i < 5; i = i + 3 ) {} /* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 67
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 201
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-5-3

Floating-point expressions shall not be tested for equality or inequality [JSF-202-2]


DESCRIPTION
"Floating-point expressions shall not be tested for equality or
inequality.
The recommended method for achieving deterministic floating-point
comparisons is
to write a library that implements the comparison operations. The library
should
take into account the floating-point granularity (FLT_EPSILON) and the
magnitude
of the numbers being compared."

NOTES
Rule does not detect indirect tests of equality and inequality which are
equally
problematic and are also forbidden by Misra standard:
if ( ( x <= y ) && ( x >= y ) )
{
/* ... */
}

BENEFITS
"The inherent nature of floating-point types is such that comparisons of
equality will often not evaluate to true even when they are expected to.
In
addition the behaviour of such a comparison cannot be predicted before
execution, and may well vary from one implementation to another. "

EXAMPLE
void foo() {
float x, y;
if (x == y);
if (x == 0.0f);
}

// Violation
// Violation

REPAIR
void foo( float epsilon ) {
float x, y;
if (x - epsilon <= y && y <= x + epsilon);
if (-epsilon <= x && x <= epsilon);

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 50
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 202
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-2

Evaluation of constant unsigned integer expressions should not lead to wrap-around [JSF203-2]
DESCRIPTION
"Because unsigned integer expressions do not strictly overflow, but
instead
wrap-around in a modular way, any constant unsigned integer expressions
which in effect 'overflow' will not be detected by the compiler."
The rule reports a violation if a result of subtraction of two integer
constants is lower than 0.

NOTES
This rule checks only simple subtractions for unsigned integer constants.
It is not possible to checks:
- expressions other than subtraction
- complex expressions
- expressions which use Macro definition or hexadecimal values

BENEFITS
Prevents from wrap-around for unsigned integer.

EXAMPLE
#if (1u - 2u) /* Violation */
/* ... */
#endif

REPAIR
Avoid wrap-around for unsigned integer.

REFERENCES
1. Origin: Misra Guidelines - Rule 51
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.25 Expressions, AV Rule 203


3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-190
http://cwe.mitre.org/top25/#CWE-190

Assert liberally to document internal assumptions and invariants [JSF-204_a-2]


DESCRIPTION
This rule checks that code asserts liberally to document internal
assumptions and invariants.
"Use assert or an equivalent liberally to document assumptions internal
to a module. Never write expressions with side effects in assert
statement.
Avoid assert(false) and prefer assert(!"informational message").
Most compilers will helpfully emit the string in their error output."

BENEFITS
Rule improves efficiency and prevents error-prone code.

EXAMPLE
#include <assert.h>
void foo( ) {
int i = 0;
assert( i++ != 0 ); // Violation
assert(i=5);
// Violation
assert(false);
// Violation
}

REPAIR
#include <assert.h>
void foo( ) {
int i = 0;
assert(i != 0);
// OK
assert(!"informational message"); // OK
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.

Chapter: "Error Handling and Exceptions", Rule 68


2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions & References, AV Rule 204
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The increment (++) and decrement (--) operators should not be mixed with other operators in
an expression [JSF-204_b-2]
DESCRIPTION
"It is the intention of the rule that when the increment or decrement
operator
is used, it should be the only side-effect in the statement.
The use of increment and decrement operators in combination with other
arithmetic operators is not recommended because:
- It can significantly impair the readability of the code
- It introduces additional side effects into a statement with the
potential for
undefined behaviour
It is safer to use these operations in isolation from any other arithmetic
operators."

BENEFITS
Improves readability and maintainability.
Reduces risk of potential undefined behaviour
caused by additional side effects

EXAMPLE
void foo() {
int x, y;
x = --y + x++;
}

/* Violation */

REPAIR
void foo() {
int x, y;
--y;
x = y + x;
x++;
}

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-10

The value of an expression shall be the same under any order of evaluation that the standard
permits [JSF-204_c-2]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
As an example of what can go wrong, consider x = b[i] + i++; This will
give
different results depending on whether b[i] is evaluated before i++ or
vice
versa. The problem could be avoided by putting the increment operation
in a separate statement."
The rule reports a violation if a variable is used and
incremented/decremented
in the same statement.
See also: MISRA2004-12_4_a, MISRA2004-12_4_b

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo( )
{
int a, b[10];
a = b[a] + a++; // Violation
}

REPAIR
void foo( )
{
int a, b[10];

a = b[a] + a;
a++;

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The second or third operand of a ternary operator '?:' shall not contain side effects [JSF204_d-2]
DESCRIPTION
"There are some situations in C or C++ code where certain parts of
expressions
may not be evaluated. If these sub-expressions contain side effects then
those
side effects may or may not occur, depending on the values of other
sub-expressions.
The operators which can lead to this problem are &&, || and ?:. In the
case of
the ?: operator, either the second or third operands are evaluated but not
both.
The ?: operator is specifically provided to choose between two subexpressions,
and is therefore less likely to lead to mistakes."
See also: MISRA2004-12_2_a, MISRA2004-12_4_a

NOTES
Rule checks only two nested level of function calls.

BENEFITS
Rule prevents conditional evaluation of the second or third operand of
ternary
operator that can easily cause problems if the developer relies on a side
effect
occurring.

EXAMPLE
int i;
int j;
int foo( ) {
return (i > j) ? j++ : i++; // Violation - developer expects 2nd and
3rd
// operand to be evaluated
}

REPAIR
int i;
int j;
int foo( ) {
if (i > j) {
++i;
return j++;
} else {
++j;
return i++;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. ISO/DIS 26262
point 8.4.4

Don't write code that depends on the order of evaluation of function arguments [JSF-204_e-2]
DESCRIPTION
The order of evaluation of function arguments is unspecified. This means
that
if arguments contain side effects then the order in which side effects
take
place is unspecified. A function call can give different results depending
on which of the function's arguments is evaluated first.
By side effect we understand accessing a volatile object, modifying an
object
or calling a function that does any of those operations.
Rule checks calls of functions that have at least two arguments.
A violation is reported if
* a volatile object is read or modified, or
* a non-volatile object is modified
during evaluation of a function argument and the same object is read or
modified during evaluation of function's other argument.

EXCEPTIONS
Only one level of function calls is checked.

BENEFITS
Rule prevents writing source code which might produce different results
between compilers.

EXAMPLE
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
Transmogrify(Bump(count),Bump(count)); // Violation
Transmogrify(count++,count);
// Violation
}

REPAIR
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
int temp1 = Bump(count);
Transmogrify(temp1,Bump(count)); // OK
Transmogrify(count,count);
// OK
count++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 31
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
5. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

Do not use the volatile keyword [JSF-205-2]


DESCRIPTION
Do not use the volatile keyword.
See also: misra2004-12_2_f

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo1() {
volatile int v;
}

/* Violation */

REPAIR
Do not use the volatile keyword.

REFERENCES
1. Origin: Misra Guidelines - Rule 46
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 205

Dynamic heap memory allocation shall not be used [JSF-206-2]


DESCRIPTION
"The use of dynamic memory can lead to out-of-storage run-time failures,
which are undesirable. The built-in new and delete operators, other than
the placement versions, use dynamic heap memory. The functions calloc,
malloc, realloc and free also use dynamic heap memory."

EXCEPTIONS
The rule allows to use a placement new.

BENEFITS
"There is a range of unspecified,
behaviour associated with dynamic
of
other potential pitfalls. Dynamic
memory
leaks, data inconsistency, memory
behaviour."

undefined and implementation-defined


memory allocation, as well as a number
heap memory allocation may lead to
exhaustion, non-deterministic

EXAMPLE
void foo()
{
int * p = new int[10]; // Violation
/* ... */
delete[] p;

// Violation

REPAIR
Do not use neither 'new' and 'delete' operators nor 'calloc', 'malloc',
'realloc' and 'free' functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Misra Guidelines - Rule 118
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-4-1
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 206
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 3

Encapsulate global variables and constants, enumerated types, and typedefs in a class [JSF207-3]
DESCRIPTION
"Encapsulate global variables and constants, enumerated types, and
typedefs
in a class. Static variables in a class should be used instead of global
variables and constants, enumerated data types, and typedefs."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
enum Days {yesterday};
typedef int myint;
myint glob;

// Violation
// Violation
// Violation

REPAIR
class A {
public:
enum Days {yesterday};
typedef int MyInt;
static MyInt glob;
};

// OK
// OK
// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 5 Assigning Names - Rec. 19
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 207
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff

Document issued on: January 11, 2002


4. ISO/DIS 26262
point 8.4.4

C++ exceptions shall not be used (i.e. throw, catch and try shall not be used.) [JSF-208-2]
DESCRIPTION
Do not use C++ exceptions.

SINCE
v7.1

BENEFITS
Rule improves portability of the code.

EXAMPLE
#include <iostream>
using namespace std;
int main()
{
char *buf;
try
// Violation
{
buf = new char[512];
if( buf == 0 )
throw "Memory allocation failure!"; // Violation
}
catch( char * str )
// Violation
{
cout << "Exception raised: " << str << '\n';
}
// ...
return 0;
}

REPAIR
#include <iostream>

using namespace std;


int main()
{
char *buf;
buf = new char[512];
if( buf == 0 )
cout<< "Memory allocation failure!";

// OK

return 0;
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.27 Fault Handling, AV Rule 208

typedefs that indicate size and signedness should be used in place of the basic types [JSF209-2]
DESCRIPTION
"The basic numerical types of signed and unsigned variants of char, int,
short, long, and float, double should not be used, but specific-length
typedefs should be used."
Rule reports a violation message if basic numerical type is used
( e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA-013

EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- plain char, boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)

BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."

EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
short* v_short,
float& r_float)
{
double h;
const int z = 1;
return 1;

/* Violation (for return type) */


/* Violation */
/* Violation */
/* Violation */
/* Violation */

REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
char ch;
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}

/* OK (plain char) */
/* OK (typedef name starts with 'bool'

/* OK (bit-bield type) */
/*
/*
/*
/*
/*

OK
OK
OK
OK
OK

(plain char) */
(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */

/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 18 Portable Code - 18.1 Data Abstraction - Port. Rec. 1

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.28 Portable Code, AV Rule 209

The signal handling facilities of signal.h shall not be used [JSF-21-2]


DESCRIPTION
"Signal handling contains implementation-defined and undefined behaviour."
Rule reports a violation message if a file includes any of the following
headers: signal.h, or csignal.

BENEFITS
Prevents from problems associated with implementation-defined
and undefined behaviour in signal handling.

EXAMPLE
#include <signal.h>

/* Violation */

REPAIR
Do not use <signal.h> header.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 123
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 21
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-7-1

Algorithms shall not make assumptions concerning the order of allocation of nonstatic data
members separated by an access specifier [JSF-210.1-2]
DESCRIPTION
This rule is intended to prohibit an application from making assumptions
concerning the order in which non-static data members, separated by an
access specifier, are ordered.
Rule reports a violation message if static_cast type is pointer to class
with non-static data members separated by an access specifier.

SINCE
v7.1

BENEFITS
The order of allocation of nonstatic data members, separated by an
access-specifier, is unspecified.

EXAMPLE
class A
{
protected: // a could be stored before b, or vice versa
int a;
private:
int b;
};

class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);

// Violation
// application

assumes that objects of


// type A will

always have attribute a


// stored before
attribute b.
}

REPAIR
struct A
{
int a;
int b;
};
class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);

// OK
// attributes in B

not separated
// by an access
specifier
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 210.1

Limited dependence should be placed on C's operator precedence rules in expressions [JSF213_a-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
Parentheses are required for the right-hand operand because the right-hand
side itself contains an assignment expression.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int a, b;
b = a = 0;// Violation
}

REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C's operator precedence rules in expressions [JSF213_b-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it.
It is easy to make a mistake with the rather complicated precedence rules
of C,
and this approach helps to avoid such errors, and helps to make the code
easier
to read. However, do not add too many parentheses so as to clutter the
code and
make it unreadable."
"No parentheses are required for the right-hand operand of an assignment
operator unless the right-hand side itself contains an assignment
expression."

NOTES
Macro's body is excluded from checking.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int a, b;
b = (a = 0);// OK
b = (a + 0);// Violation
}

REPAIR
void foo() {
int a, b;

b = (a = 0);// OK
b = a + 0;// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

No parentheses are required for the operand of a unary operator [JSF-213_c-2]


DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
The rule detects parentheses which are not required for the operand
of a unary operator.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( )
{
int a, b;
b = a * (-1);
}

// Violation

REPAIR
void foo( )
{
int a, b;
b = a * -1;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C's operator precedence rules in expressions [JSF213_d-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
"If all operators are the same, parentheses may be used to control the
order of
operation. Some operators (e.g. addition and multiplication) that are
associative in algebra are not necessarily associative in C. Similarly,
integer
operations involving mixed types (prohibited by several rules) may produce
different results because of the integral promotions. The following
example
written for a 16-bit implementation demonstrates that addition is not
associative and that it is important to be clear about the structure of an
expression:"

SINCE
v7.0

BENEFITS
Rule increases safety in arithmetic operations.

EXAMPLE
#ifdef _MSC_VER
typedef unsigned __int16 uint16;

typedef unsigned __int32 uint32;


#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus( ) {
uint16 a = 10;
uint16 b = 65535;
uint32 c = 0;
uint32 d;
d = (a + b) + c; /* Violation d is 9; a + b wraps modulo 65536 */
}
void fooMultiply( ) {
uint16 a = 10;
uint16 b = 65535;
uint32 c = 0;
uint32 d;
d = (a * b) * c; /* Violation d is 65526; a * b wraps modulo 65536 */
}

REPAIR
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus(
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a + (b
}

) {
10;
65535;
0;
+ c); /* OK d is 65545 */

void fooMultiply( ) {

uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a * (b

10;
65535;
0;
* c); /* OK d is 655350 */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Use parentheses unless all operators in the expression are the same [JSF-213_e-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it unreadable.
Use parentheses unless all operators in the expression are the same."
See also: MISRA2004-12_5, CODSTA-90

NOTES
The operands of a logical && and || are checked by the rule MISRA2004-12_5

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( ) {
int a, b;
b = a * a + a;
}

// Violation

REPAIR
void foo( ) {
int a, b;
b = (a * a) + a;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Avoid initialization order problems across translation units [JSF-214-2]


DESCRIPTION
"If initialization of a non-local static object in one translation
unit uses a non-local static object in a different translation
unit, the object it uses could be uninitialized, because the
relative order of initialization of non-local static objects
defined in different translation units is undefined.
Fortunately, a small design change eliminates the problem
entirely. All that has to be done is to move each non-local
static object into its own function, where it's declared
static. These functions return references to the objects
they contain. Clients then call the functions instead
of referring to the objects. In other words, non-local
static objects are replaced with local static objects."

SINCE
v7.0

BENEFITS
"This approach is founded on C++'s guarantee that local
static objects are initialized when the object's definition
is first encountered during a call to that function. So if
you replace direct accesses to non-local static objects
with calls to functions that return references to local
static objects, you're guaranteed that the references you
get back will refer to initialized objects. As a bonus, if you
never call a function emulating a non-local static object,
you never incur the cost of constructing and destructing
the object, something that can't be said for true non-local
static objects."

EXAMPLE
#include <iostream>
using namespace std;
class FileSystem {

public:
size_t numDisks( ) const;
};
extern FileSystem tfs;
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_tfs = tfs.numDisks( );
}
Directory tempDir( );

// Violation

REPAIR
#include <iostream>
using namespace std;
class FileSystem {
public:
size_t numDisks( ) const;
};
FileSystem& tfs_one( ) {
static FileSystem fs;
return fs;
}
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_one = tfs_one().numDisks( );
}
Directory tempDir( );

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.28 Portable Code, AV Rule 214


3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid pointer arithmetic [JSF-215-3]


DESCRIPTION
Pointer arithmetic should not be used.

BENEFITS
Prevents from access to unintended or invalid memory addresses.

EXAMPLE
void foo()
{
int* a;
int* b;
int tab[10];
a=tab;
a++;
/* Violation */
--a;
/* Violation */
b = a+5;
/* Violation */
}

REPAIR
Do not use pointer arithmetic.

REFERENCES
1. Origin: Misra Guidelines - Rule 101
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 215

The input/output library stdio.h shall not be used [JSF-22-2]


DESCRIPTION
"Streams and file I/O have a large number of unspecified,
undefined and implementation-defined behaviours associated with them.
It is assumed that they will not normally be needed in production
code in embedded systems.
If any of the features of stdio.h need to be used in production code,
then the issues associated with the feature need to be understood."
The rule prevents inclusion of <stdio.h>, and <cstdio> headers.

BENEFITS
Prevents form problems associated with a large number of unspecified,
undefined and implementation-defined behaviour associated
with streams and file I/O.

EXAMPLE
#include <stdio.h>

/* Violation */

REPAIR
Do not use <stdio.h> library.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 124
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 22
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 27, Rule 27-0-1

The library functions atof, atoi and atol from library stdlib.h shall not be used [JSF-23-2]
DESCRIPTION
'atof', 'atoi' and 'atol' functions from library <stdlib.h> have undefined
behaviour associated with them when the string cannot be converted.

BENEFITS
Prevents using functions which have sometimes undefined behaviour.

EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *s; double x; int i; long l;
s = " -2309.12E-15";
x = atof( s );
/* Violation */
s = " -9885 pigs";
i = atoi( s );
/* Violation */
s = "98854 dollars";
l = atol( s );
/* Violation */
}

REPAIR
Do not use atof, atoi and atol functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 125
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 23
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 18, Rule 18-0-2

The library functions abort, exit, getenv and system from library stdlib.h shall not be used
[JSF-24-2]
DESCRIPTION
'abort', 'exit', 'getenv' and 'system' functions from stdlib.h, cstdlib,
or stdlib_iso.h libraries shall not be used.

BENEFITS
Prevents using functions which are not required in an embedded system.

EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *libvar;
libvar = getenv( "LIB" );
system( "dir" );
abort( );
exit( 0 );
}

/*
/*
/*
/*

Violation
Violation
Violation
Violation

*/
*/
*/
*/

REPAIR
Do not use abort, exit, getenv and system functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 126
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 24
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-3

The time handling functions of library time.h shall not be used [JSF-25-2]
DESCRIPTION
"This library is associated with clock times.
Various aspects are implementation dependent
or unspecified, such as the formats of times."
Rule prevents inclusion of <time.h> and <ctime> headers.
See also: SECURITY-01

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include <time.h>

/* Violation */

REPAIR
Do not include time.h header.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 127
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 25
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 18, Section 7, Rule 18-0-4

Only the following pre-processor directives shall be used: #ifndef, #define, #endif, #include
[JSF-26-2]
DESCRIPTION
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include

SINCE
v7.1

BENEFITS
Limit the use of the pre-processor to those cases where it is necessary.

EXAMPLE
#pragma once // Violation

REPAIR
#ifndef FOO_H
#define FOO_H
/* ... */
#endif

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 26
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

Use multiple include guards [JSF-27-3]


DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-07, PFO-08, MISRA2004-19_15

BENEFITS
Rule improves maintainability and optimization of code.

EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present

REPAIR
// file foo.hh
// OK
#ifndef FOO_HH
#define FOO_HH
int i;
#endif

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 27
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-3

The #ifndef and #endif pre-processor directives will only be used to prevent multiple
inclusions of the same header file [JSF-28-3]
DESCRIPTION
The #ifndef and #endif pre-processor directives will only be used
as defined in below example to prevent multiple inclusions of the
same header file.
#ifndef Header_filename
#define Header_filename
// Header declarations...
#endif

SINCE
v7.1

BENEFITS
Conditional code compilation should be kept to a minimum as it can
significantly obscure testing and maintenance efforts.

EXAMPLE
#ifndef MAX

// Violation

int max = 10;


#endif

// Violation

int a;

REPAIR
#ifndef FOO_H
#define FOO_H
int max = 10;
int a;

// OK

#endif

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 28
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

A function should be used in preference to a function-like macro [JSF-29-2]


DESCRIPTION
Rule reports a violation on function-like macro definition.

BENEFITS
"While macros can provide a speed advantage over functions, functions
provide
a safer and more robust mechanism. This is particularly true with respect
to the type checking of parameters, and the problem of function-like
macros
potentially evaluating parameters multiple times.
See also: CODSTA-03, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40

EXAMPLE
#define SUM(A,B) ((A)+(B))

/* Violation */

void foo( int x, int y ) {


/* ... */
SUM( x, y );
/* ... */
}

REPAIR
int sum( int a, int b ) {
return (a + b);
}
void foo( int x, int y ) {
/* ... */
sum( x, y );
/* ... */
}

REFERENCES

/* OK */

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 19
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
3. Misra Guidelines - Rule 93
4. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.5 Inline Functions - Rule 35
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 29
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-4

Follow the Cyclomatic Complexity limit of 20 [JSF-3-2]


DESCRIPTION
This rule identifies methods that do not satisfy the user-defined
requirement
for Cyclomatic Complexity.
Cyclomatic Complexity is calculated according to the formula:
CC = Number of decisions + 1
By decision we mean every occurrence of:
-'if'
-'for'
-'while'
-'do-while'
-'case'
-'catch'
-conditional expression 'a?b:c'
-logical operator '&&' and '||'
An error is reported if a function have a Cyclomatic Complexity higher
than 20.
See also: METRICS-18, METRICS-29, METRICS-33, METRICS-34, METRICS-35

SINCE
v7.1

NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 20" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for

N.

BENEFITS
Studies have found that methods with high Cyclomatic Complexity are errorprone.

EXAMPLE
void foo2(int i, int a, int b, int j, int k)
{
switch (i)
{
case 1: // 1
i++;
default:
i++;
}
switch (j)
{
case 1: // 2
j++;
default:
j++;
}
switch (k)
{
case 1: // 3
k++;
default:
k++;
}
if(a||b)
// 4, 5
{
}
if((a||b)&&(a&&b)) // 6, 7, 8, 9
{
}
do
// 10
{
}while(0);

// Violation - CC value: 21

switch (i)
{
case 1: // 11
i++;
default:
i++;
}
switch (j)
{
case 1: // 12
j++;
default:
j++;
}
switch (k)
{
case 1: // 13
k++;
default:
k++;
}
if(a||b)
// 14, 15
{
}
if((a||b)&&(a&&b)) // 16, 17, 18, 19
{
}
do
// 20
{
}while(0);
}

REPAIR
Keep a Cyclomatic Complexity value on the level lower than 20.

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 3.2 Code Size and Complexity, AV Rule 3

Do not define constants via #define [JSF-30-2]


DESCRIPTION
"Constants are to be defined using const or enum; never using #define. The
preprocessor performs a textual substitution for macros in the source code
which is then compiled. This has a number of negative consequences. For
example, if a constant has been defined using #define, the name of the
constant is not recognized in many debuggers. If the constant is
represented
by an expression, this expression may be evaluated differently for
different
instantiations, depending on the scope of the name. In addition, macros
are,
at times, incorrectly written."
See also: MISRA2004-19_7, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40

BENEFITS
Code is easier to debug. Prevents incorrectly macro writing.

EXAMPLE
#define PI 3.1416

// Violation

REPAIR
const float PI = 3.1416; // OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 10 Constants - Rule 36

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.6 Pre-Processing Directives, AV Rule 30

Avoid macros [JSF-31-3]


DESCRIPTION
Macros are generally an obsolete construct inherited from C language.
The main problems with macros are that they:
- are not type-safe
- are expanded by the preprocessor so debugging them is not possible
- can compile by pure luck creating ugly problems with the program

EXCEPTIONS
Macros are almost never necessary in C++. Exceptions to this rule are:
- #ifdef
- #ifndef
- #if
- #if defined
when used as include guards and for conditional compilation.

BENEFITS
Improves code reliability and maintainability.

EXAMPLE
#define PI 3.14

// Violation

REPAIR
const double PI = 3.14; // OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.6 Pre-Processing Directives, AV Rule 31


3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1

The #include pre-processor directive will only be used to include header (*.h) files [JSF-32-3]
DESCRIPTION
The #include pre-processor directive will only be used to include
header (*.h) files.

SINCE
v7.1

EXCEPTIONS
In the case of template class or function definitions, the code may be
partitioned into separate header and implementation files. In this
case, the implementation file may be included as a part of the header
file. Rule allows for mentioned exception if the implementation file
has the same name as a header file.

BENEFITS
Rule improves the clarity of code.
The only files included in a .cpp file should be the relevant
header (*.h) files.

EXAMPLE
// file.cpp
#include <file2.cpp>
#include <file3.hh>

// Violation
// Violation

// file.h
#include <file2.cpp>
#include <file3.hh>

// Violation
// Violation

REPAIR
// file.cpp
#include <file2.h>

// OK - header (*.h) file

#include <file3.h>
// file.h
#include <file.cpp>
file.cpp
#include <file2.h>
#include <file3.h>

// OK - header (*.h) file

// OK - corresponding to file.h implementation file


// OK - header (*.h) file
// OK - header (*.h) file

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 32

The #include directive shall use the <filename.h> notation to include header files [JSF-33-2]
DESCRIPTION
The #include directive shall use the <filename.h> notation to include
header files.

SINCE
v7.1

BENEFITS
The include form "filename.h" is typically used to include local header
files.
However, due to the unfortunate divergence in vendor implementations, only
the <filename.h> form will be used.

EXAMPLE
#include "foo.h" // Violation

REPAIR
#include <foo.h>
// OK
#include <dir1/dir2/foo.h> // OK: relative path used

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Filess, AV Rule 33

Use mechanism that prevents multiple inclusion of the file i.e. include guards or "#pragma
once" preprocessor directive [JSF-35-3]
DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be either:
- #pragma once - preprocessor directive
or
- include guards defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-02, PFO-07, and MISRA2004-19_15

SINCE
v7.1

BENEFITS
Rule improves maintainability and optimization of code.

EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present

REPAIR
// file foo.hh
// OK
#pragma once

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 35

Don't define entities with linkage in a header file [JSF-39_a-3]


DESCRIPTION
"Header files should be used to declare objects, functions, inline
functions,
function templates, typedefs, macros, classes, and class templates and
shall
not contain or produce definitions of objects or functions (or fragment of
functions or objects) that occupy storage."
See also: MISRA2004-8_5

NOTES
As a headers rule detects files with extensions ".h", ".hh", ".hxx", ".i"
(e.g. "file.h", "file.hh", "file.hxx", "file.i").

EXCEPTIONS
The following definitions are allowed in a header file:
- inline functions
- function templates
- static data members of class templates
- const variables if they have internal or no linkage (C++ mode)
- static const variables

BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.

EXAMPLE
/* file.h */
void f1(){}
int var;
class C {
void f2();
};

// Violation
// Violation

void C::f2() {}

// Violation

/* file.cpp */
#include "file.h"

REPAIR
/* file.h */
void f1();
extern int var;
class C {
void f2();
};
template <typename T>
void f3 ( T ) { }

// OK
// OK

// OK

/* file.cpp */
#include "file.h"
void f1(){}
int var;
void C::f2() {}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-1
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 61
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 39

Source lines will be kept to a length of 120 characters or less [JSF-41-3]


DESCRIPTION
The rule reports a violation if a physical line contains more
than 120 characters. Very long source lines can be difficult
to read and understand.

SINCE
v7.1

NOTES
Tab is counted as one character.
White spaces at the end of line are counted in the same way as other
characters.
Comments with 'parasoft-suppress' are not counted.
To change the default limit of characters modify the variable
'lineLengthLimit'
at the begin of python method 'check'.(e.g. 'lineLengthLimit = 100' means
that
the maximal allowed number of characters in a physical line is 100)

BENEFITS
The rule improves readability of code.

EXAMPLE
int
/*
..........................................................................
..........*/ i1 ; /* Violation */
int
/* ..........white spaces at the end of
line.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........Violation.......
*

..........................................................................
............................Violation.....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* Violation
*/

REPAIR
int
/*
..........................................................................
................*/ i1 ; /* OK */
int
/* ..........There is no spaces at the
end.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........OK......
*
..........................................................................
............................OK....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + \
xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* OK */
int
/*
..........................................................................
...............*/ i3 ; /* parasoft-suppress ITEM ... OK */

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 41

Only one statement shall be allowed per line [JSF-42-3]


DESCRIPTION
This rule checks that there is only one statement per line.

BENEFITS
This rule promotes readability and maintainability by reducing code
complexity.

EXAMPLE
void foo()
{
int i; char c; // Violation
}

REPAIR
void foo()
{
int ii; // OK
char cc;
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 42

Tabs that do not use ASCII spaces shall not be used [JSF-43-4]
DESCRIPTION
This rule checks whether you are using only ASCII white spaces as tabs.
Different operating systems, display devices, and editors handle tabs
in different ways. Code containing tabs will likely be indented
incorrectly
if ported to another environment.

BENEFITS
Rule prevents inconsistent display of code containing tabs
in different environments.

EXAMPLE
void foo()
{
int i; // Violation
}

REPAIR
void foo()
{
int j; // OK
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 43

User-specified identifiers (internal and external) will not rely on significance of more than 64
characters [JSF-46-2]
DESCRIPTION
Identifiers names consisting of more than 64 characters should not be
used.

SINCE
v7.1

BENEFITS
Rule ensures that code can be ported between the majority of
compilers/linkers
without requiring modification (shortening) of identifiers names

EXAMPLE
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam) //
Violation 65 chars
{
}

REPAIR
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam)
64 chars
{
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

// OK

Chapter 4.9 Style, AV Rule 46

Do not use identifiers which begin with one or two underscores (`_' or `__') [JSF-47-3]
DESCRIPTION
"Do not use identifiers which begin with one or two underscores (`_' or
`__')."
See also: CODSTA-92, CODSTA-93

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
void _foo( );

// Violation

REPAIR
void foo( );

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 47

Identifiers will not differ by mixture of case, the underscore character, interchange of the
similarly looking letters and numbers [JSF-48-3]
DESCRIPTION
Identifiers will not differ by:
- Only a mixture of case
- The presence/absence of the underscore character
- The interchange of the letter 'O', with the number '0' or the letter 'D'
- The interchange of the letter 'I', with the number '1' or the letter 'l'
- The interchange of the letter 'S' with the number '5'
- The interchange of the letter 'Z' with the number '2'
- The interchange of the letter 'n' with the letter 'h'.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo(int paramS, int param5);

// Violation

REPAIR
void foo(int param1, int param2);

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 48

Only the first word of the name of a class, structure, namespace, enumeration, or typedef will
begin with an uppercase letter [JSF-50-3]
DESCRIPTION
The first word of the name of a class, structure, namespace, enumeration,
or type created with typedef will begin with an uppercase letter.
All others letters will be lowercase.

SINCE
v7.1

NOTES
If one wants to eliminate some abbreviations from checking it can be done
by
adding abbreviation string to array abb_table in rule's python method
checkNamingConvention() e.g. abb_table = ["RGB", "IBM"]

EXCEPTIONS
The first letter of a typedef name may be in lowercase if the typedef is a
class member or
when it is used as a replacement for primitive types.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class sample_Class
{
// ...
};

// Violation

REPAIR
class Sample_class
{
// ...
};

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 50

All letters contained in function and variable names will be composed entirely of lowercase
letters [JSF-51-3]
DESCRIPTION
All letters contained in function and variable names will be composed
entirely of lowercase letters.

SINCE
v7.1

EXCEPTIONS
Constructors and destructors.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class Sample_class
{
public:
int Some_function();
private:
int Some_variable;
};

// Violation
// Violation

REPAIR
class Sample_class
{
public:
int some_function();
private:
int some_variable;
};

// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 51

Identifiers for constant and enumerator values shall be lowercase [JSF-52-2]


DESCRIPTION
Identifiers for constant and enumerator values shall be lowercase.

SINCE
v7.1

BENEFITS
Although it is an accepted convention to use uppercase letters for
constants and enumerators, it is possible for third party libraries
to replace constant/enumerator names as part of the macro substitution
process (macros are also typically represented with uppercase letters).

EXAMPLE
const int Max_pressure = 100;
// Violation
enum Switch_position {Up, down}; // Violation

REPAIR
const int max_pressure = 100;
enum Switch_position {up, down};

// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 52

Header files will always have a file name extension of '.h' [JSF-53-3]
DESCRIPTION
The rule reports violations on header files which does not have '.h'
extension.
See also: PREPROC-08, NAMING-37, NAMING-38

SINCE
v7.1

NOTES
A header file is defined as any file that is included via #include.

BENEFITS
Rule makes source code more readable.

EXAMPLE
// file.cpp
#include "file.hpp"
// file.hpp
extern int i;

// Violation

REPAIR
// file.cpp
#include "file.h"
// file.h
extern int i;

REFERENCES

// OK

JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.9 Style, AV Rule 53

The following character sequences shall not appear in header file names: ', \, /*, //, or " [JSF53.1-2]
DESCRIPTION
The following character sequences shall not appear in header file
names: ', \, /*, //, or ".

SINCE
v7.1

BENEFITS
If any of the character sequences ', \, /*, //, or " appears in a
header file name (i.e. <h-char-sequence>), the resulting behavior is
undefined.

EXAMPLE
#include "foo's.h" // Violation

REPAIR
#include <foo_s.h> // OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 53.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Implementation files will always have a file name extension of ".cpp" [JSF-54-3]
DESCRIPTION
If a file name extension is not ".h" (reserved for header file) than
it should be ".cpp" (implementation file).
Rule detects file name extensions different than ".cpp" and ".h".
".cpp" extension should be used for implementation files whereas
".h" are reserved for headers (rule NAMING-41).
See also: NAMING-41

SINCE
v7.1

NOTES
Rule is enabled for C++ only.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
//file.cc

// Violation

REPAIR
//file.cpp

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 54

Order of scopes in class: public before all others [JSF-57_a-3]


DESCRIPTION
Public section must be before protected and private sections.
See also: CODSTA-CPP-45, CODSTA-CPP-47, CODSTA-CPP-48, CODSTA-CPP-49

BENEFITS
Readability and maintainability.

EXAMPLE
class Test {
protected:
void foo2(
private:
void foo3(
public:
void foo1(
};

// Violation
);
);
);

REPAIR
class Test {
public:
void foo1(
protected:
void foo2(
private:
void foo3(
};

// OK
);
);
);

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.9 Style, AV Rule 57

Order of scopes in classes: protected before private [JSF-57_b-3]


DESCRIPTION
Protected section must be before private section.
See also: CODSTA-CPP-45, CODSTA-CPP-46, CODSTA-CPP-48, CODSTA-CPP-49

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class Test {// Violation
public:
void foo1( );
private:
void foo3( );
protected:
void foo2( );
};

REPAIR
class Test {// OK
public:
void foo1( );
protected:
void foo2( );
private:
void foo3( );
};

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.9 Style, AV Rule 57

When declaring functions with more than 2 parameters, the leading parenthesis and the first
argument are to be written on the same line as the function name, each additional argument
will be written on a separate line [JSF-58-3]
DESCRIPTION
When declaring and defining functions with more than two parameters,
the leading parenthesis and the first argument will be written on
the same line as the function name. Each additional argument will
be written on a separate line (with the closing parenthesis directly
after the last argument).

SINCE
v7.1

BENEFITS
Readability and style.

EXAMPLE
void foo(int a, int b, int c);// Violation
void zoo(
int a, int b,
int c
)
{

// Violation
// Violation
// Violation

REPAIR
void foo(int a,
int b,
int c);
void zoo( int a,
int b,

// OK

int c)

// OK

{
}
void goo(int a, int b); // OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 58

The statement forming the body of a 'switch', 'while', 'do...while' or 'for' statement shall be a
compound statement [JSF-59_a-2]
DESCRIPTION
" The statement that forms the body of a switch statement or a while,
do ... while or for loop, shall be a compound statement (enclosed within
braces), even if that compound statement contains a single statement."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x ) {
int i;
switch(i)
;

// Violation

for (i=0; i< 10; i++) // Violation


foo( x );
while (1)
// Violation
foo( x );
do
foo( x );
while(1);

// Violation

REPAIR
void foo( int x ) {
int i;
switch(i)
{
}

// OK

for (i=0; i< 10; i++) // OK

{foo( x );}
while (1)
{foo( x );}

// OK

do

// OK

{foo( x );}
while(1);
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 59
3. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-3-1

'if' and 'else' should be followed by a compound statement [JSF-59_b-2]


DESCRIPTION
"An 'if' (expression) construct shall be followed by a compound statement.
The 'else' keyword shall be followed by either a compound statement,
or another 'if' statement."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x, int
{
int i, j;
if(x > 0)
//
x = i;
else if(y > 0) //
y = i;
else
y = j;
//
x = j;
}

y )

Violation
Violation

Violation

REPAIR
void foo( int x, int y )
{
int i, j;
if(x > 0)
// OK
{
x = i;
}
else if(y > 0) // OK
{
y = i;
}
else

{
y = j;
x = j;

// OK

}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Misra Guidelines - Rule 59
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-1

Braces "{}" which enclose a block should be placed in the same column [JSF-60-3]
DESCRIPTION
Rule checks if opening and closing braces are placed in the same column.
See also: FORMAT-02, FORMAT-03

EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//
Rule does not report violation

initializations and empty blocks.


OK
OK
OK
if in line with brace 'tab' is used.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class Foobar {
int a;
};

// Violation

struct S1 {
int a;
};

// Violation

REPAIR
class Foobar
{
int a;
};
struct S1
{
int a;
};

// OK

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 60

Place an opening brace '{' on its own line [JSF-61_a-3]


DESCRIPTION
The rule reports a violation if an opening brace '{' is not placed
on separate line.
See also: FORMAT-03, FORMAT-34

EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//

initializations and empty blocks.


OK
OK
OK

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class A1
{ int a;
};
struct S1 {
int a;
};

// Violation

// Violation

REPAIR
class A1
{
int a;
};
struct S1
{
int a;
};

// OK

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61

Place a closing brace '}' on its own line [JSF-61_b-3]


DESCRIPTION
The rule reports a violation if a closing brace '}' is not placed
on separate line.
See also: FORMAT-02, FORMAT-34

EXCEPTIONS
Rule does not adhere to enums, initializations and empty blocks.
It is allowed to place tokens after '}' in the same line if:
- '}' ends 'do-while' construct
- '}' ends declaration of class/structure/union/enum

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
int goo(int i)
{
if (i == 0) { return i; }
// Violation
do { i++; } while (i < 10); // Violation
}
struct S{ int i; float f; }ss;

REPAIR
int goo(int i)
{
if (i == 0)
{
return i;
}
// OK
do
{
i++;

// Violation

} while (i < 10); // OK - Exception


}
struct S
{
int i;
float f;
}ss;

// OK - Exception

enum E {EN1 = 2, EN2 = 1};


int array[] = {1,2,3,4,5};
class FooBar{};

// OK - Exception
// OK - Exception
// OK - Exception

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61

The dereference operator `*' and the address-of operator `&' should be directly connected with
the type names [JSF-62-3]
DESCRIPTION
"The dereference operator * and the "address-of" operator & should be
directly connected to the type names in declaration and definition."

BENEFITS
Rule makes source code more readable.

EXAMPLE
void foo() {
int k=42;
int *p1;// Violation
int &r1 = k;// Violation
}

REPAIR
void foo() {
int k=42;
int* p2;// OK
int& r2 = k;// OK
}

REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#6.5
from: 6 Style - 6.4 Pointers and References - Rec. 26
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 62

There shall be no white space following '.' or '->' operator [JSF-63_a-3]


DESCRIPTION
The rule reports a violation if there is a space or tab character
immediately following '.' or '->' operators.
See also: FORMAT-18

NOTES
The violation is not reported if '.' or '->' is last in line ignoring
white spaces, comments and backslashes. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.

BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.

EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj.
x;
/* Violation */
myObjPtr-> x; /* Violation */
}
#define MACRO a. b /* Violation */

REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {

myObj.x;
/* OK */
myObjPtr->
/* OK: '->' is last in line*/
x;
myObj./*comment*/ x; /* OK: no space immediately after '.' */
}
#define MACRO a. /* OK: '.' is last in line */ \
b
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif

REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

There shall be no white space preceding '.' or '->' operator [JSF-63_b-3]


DESCRIPTION
The rule reports a violation if there is a space or tab character
immediately preceding '.' or '->' operators.
See also: FORMAT-17

NOTES
The Violation is not reported if '.' or '->' is first in line ignoring
white spaces and comments. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.

BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.

EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj
.x;
/* Violation */
myObjPtr ->x; /* Violation */
}
#define MACRO a .b /* Violation */

REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {

myObj.x;
/* OK */
myObjPtr
->x;
/* OK: '->' is first in line*/
myObj /*comment*/.x; /* OK: no space immediately before '.' */
}
#define MACRO a \
.b /* OK: '.' is first in line */
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif

REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

There shall be no white space between a prefix unary operator and its operand [JSF-63_c-3]
DESCRIPTION
This rule checks whether there is no white space between a prefix unary
operator
and its operand. This promotes continuity in the relationship between
the operators and their associated operand. These operators act solely on
their
operand and cannot be considered separately from it.

BENEFITS
Improves readability.

EXAMPLE
void foo()
{
int i=0;
-- i; // Violation
}

REPAIR
void foo()
{
int i=0;
--i;
// OK
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

There shall be no white space between a postfix unary operator and its operand [JSF-63_d-3]
DESCRIPTION
This rule checks whether there is no white space between a postfix unary
operator and its operand. This promotes continuity in the relationship
between the operators and their associated operand. These operators
act solely on their operand and cannot be consider separately from it.

BENEFITS
Improves the readability of code.

EXAMPLE
void foo()
{
int y = 0;
y ++;
}

// Violation

REPAIR
void foo()
{
int y = 0;
y++;
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63

Avoid "public" data members [JSF-67_a-2]


DESCRIPTION
This rule detects "public" data members that could be accessed
by untrusted code.
See also: OOP-19

NOTES
Rule skips 'static const' variables.

BENEFITS
Prevents the use of "public" data members. Public data members can be
directly
accessed by any user code.
Using public accessor member functions to return data instead
will prevent unauthorized access.

EXAMPLE
class A {
public:
int iData;
};

// Violation

REPAIR
class A {
private:
int iData;
// OK
public:
const int accessiData( );
};

REFERENCES
1. Ellemtel Coding Standards

http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.1 Considerations Regarding Access Rights - Rule 22
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 41
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 22
4. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Design and Declaration", Item 20
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 67
6. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid 'protected' data members [JSF-67_b-2]


DESCRIPTION
This rule detects usage of "protected" data members.
See also: OOP-18

NOTES
Rule skips 'static const' variables.

BENEFITS
Prevents the use of "protected" data members. Protected data members,
while
inaccessible within their classes, can be directly accessed by other
untrusted
classes using inheritance. Using protected accessor member functions to
return
data instead will prevent unauthorized access.

EXAMPLE
class A {
protected:
int iProtectedData;
};

// Violation

REPAIR
class A {
private:
int iPrivateData;
protected:
const int accessData();
};

REFERENCES

// OK

1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve


Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 22
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 41
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.1 Considerations regarding Access Rights - Rule 22
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 67
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declare the copy constructor and copy assignment operator private not in class itself, but in a
specifically designed base class [JSF-68-2]
DESCRIPTION
"It's possible to move the link-time error up to compile time (always a
good
thing earlier error detection is better than later) by declaring the
copy
constructor and copy assignment operator private not in class itself,
but in a base class specifically designed to prevent copying.
This works, because compilers will try to generate a copy constructor
and a copy assignment operator if anybody even a member or friend
function tries to copy a class object."
See also: CODSTA-CPP-02, CODSTA-CPP-19, CODSTA-CPP-21, CODSTA-CPP-24, MRM04,
MRM-05, MRM-37, MRM-38, MRM-40, MRM-47, MRM-48, OOP-27, OOP-34

SINCE
v7.0

BENEFITS
"The compiler-generated versions of these functions will try
to call their base class counterparts, and those calls will be
rejected, because the copying operations are private in the
base class."

EXAMPLE
class HomeForSale {
public:
HomeForSale();
private:
HomeForSale(const HomeForSale&);
// Violation
HomeForSale& operator=(const HomeForSale&); // Violation
};

REPAIR
class Uncopyable {
protected:
Uncopyable() {}
~Uncopyable() {}
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
};

// OK
// OK

class HomeForSale2 : private Uncopyable { };

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 6
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 68

Member functions shall be declared const whenever possible [JSF-69-3]


DESCRIPTION
"Const-correctness is worthwhile, proven, effective, and highly
recommended.
Understanding how and where a program's state changes is vital, and const
documents that directly in code where the compiler can help to enforce it.
If you find it impossible to make a member function const, you usually
gain
a better understanding of the ways in which that member function might
modify
an object's state."
See also: CODSTA-CPP-78

SINCE
v7.1

BENEFITS
"Writing const appropriately helps you gain a better understanding of your
design and makes your code sturdier and safer."

EXAMPLE
class A
{
int foo(int a)
{
return a;
}
};

// Violation

REPAIR
class A
{
int foo(int a) const
{

// OK

return a;
}
};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 15
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 69
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Freed memory shouldn't be accessed under any circumstances. Destructor should not be
called manually [JSF-70.1-2]
DESCRIPTION
"There are three major kinds of invalid objects:
- Destroyed objects: Typical examples are automatic objects that have gone
out
of scope and deleted heap-based objects.
- Semantically invalidated objects: Typical examples include dangling
pointers
to deleted objects (e.g., a pointer p after a delete p;) and invalidated
iterators. It is generally undefined and unsafe to do anything except
assign
another valid value to an invalidated object.
- Objects that were never valid.
Be aware of object lifetimes and validity. Never dereference an invalid
iterator
or pointer. Don't make assumptions about what delete does and doesn't do;
freed memory is freed, and shouldn't be subsequently accessed under
any circumstances. Don't try to play with object lifetime by calling
the destructor manually (e.g. obj.~T())."
The rule reports violations on the use of pointers to deleted objects
and on explicit calls of destructors.

NOTES
The rule checks only simple cases (use of variables, parameters,
a[b], a.b, a->b, or *a expressions after they were deleted).
The rule does not check a flow. It assumes that pointer to deleted object
is used if between 'delete' and an use of that pointer there is no
'case', 'default', 'break', 'return', 'throw', 'goto', exit(), abort().

BENEFITS
Rule prevents writing unsafe and error prone code.

EXAMPLE
class A {

public:
A();
~A();
};
void foo1( ) {
A obj;
obj.~A( );
}

// Violation

char* foo2( ) {
char * a = new char;
delete a;
return a;
// Violation
};
char* foo3(char * ptr){
char * a = new char;
if(a > ptr){
delete a;
(*a)++;
// Violation
} else {
(*a)++;
// OK
}
a = ptr + 1;
return a;
// OK
}

REPAIR
Don't use invalid objects.

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 99
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 70.1

3. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Public and protected methods should not be invoked by class constructor [JSF-71-2]
DESCRIPTION
The intent of this rule is to prevent an object from being used before it
is in
a fully initialized state. This may occur when a class constructor invokes
a public or protected method that requires the object to be fully
initialized as a pre-condition of method invocation.
Rule reports a violation message if class constructor invokes public or
protected method.
See also: OOP-16, INIT-06

SINCE
v7.1

BENEFITS
Public (and in some cases protected) methods assume object initialization
and class invariants have been established prior to invocation. Thus,
invocation of such methods during object construction risks the use of
uninitialized or invalid data since class invariants can not be guaranteed
before an object is fully constructed.

EXAMPLE
class A
{
public:
A();
void foo();
private:
int obj1;
};

A::A()
{
foo();
}

// Violation

REPAIR
Do not call public/protected methods from constructor.

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 71
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid calling virtual functions from constructors and destructors [JSF-71.1-2]


DESCRIPTION
Inside constructors and destructors, virtual functions do not behave
"virtually." Called while executing a constructor, a virtual function will
always be resolved to the type of the constructor. The same applies to
destructors. Further, a call from a constructor to a pure virtual function
has undefined behavior.
Hence, in general, using virtual functions in constructors and destructors
is error prone, and may lead to defects ranging from memory leaks to
program crashes.
Alternatives to calling virtual functions in these circumstances most
often
include requirements to call a post-constructor function:
- document the requirements for clients of the code
- call post-constructor during the first call of a member function
- use a factory that insures the proper initialization sequence
This rule detects when you call virtual functions from constructors
and destructors.

BENEFITS
Improves code reliability and maintainability, may identify runtime bugs
in the application.

EXAMPLE
class Base {
public:
Base( ) {
init_Base( );
// Violation
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
init_Base( );
// Violation
init_Derived1( );
// Violation

this->init_Derived2( ); // Violation
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}

REPAIR
class Base {
public:
Base( ) {
Base::init_Base( );
// OK
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
Base::init_Base( );
// OK
Derived::init_Derived1( ); // OK
derived->init_Derived2( ); // OK
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 49

2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve


Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 9
3. Scott Meyers and Martin Klaus, "Examining C++ Program Analyzers",
Dr. Dobbs' Journal, the February 1997,
Chapter: "Constructors/Destructors/Assignment", Item 13
http://www.aristeia.com/ddjpaper1_frames.html
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 71.1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer initialization to assignment in constructors [JSF-74-3]


DESCRIPTION
This rule checks constructors to see if you are assigning data members
when
you should be initializing them.
Assigning to data members causes a default constructor to be called first,
and then assignment will be performed later.
Initialization eliminates the overhead of performing assignment later.
Note that constants and references can only be initialized, never
assigned.
See also: INIT-06, INIT-10, MISRA-030

BENEFITS
Improves code consistency and runtime performance

EXAMPLE
#include <string>
using namespace std;
class A {
public:
A( const char* file, const char* path ) {
myFile = file;
// Violation
myPath = path;
// Violation
}
private:
string myFile;
string myPath;
};

REPAIR
#include <string>
using namespace std;
class A {

public:
A( const char* file, const char* path ) :
myFile(file), myPath(path) {}
// OK
private:
string myFile;
string myPath;
};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09,
Chapter: "Construction, Destruction, and Copying", Rule 48
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 12
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 74
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

List members in an initialization list in the order in which they are declared [JSF-75-2]
DESCRIPTION
"Recall that the destructors for the members of an object are always
called
in the inverse order of their constructors. Thus, if members were
initialized
in the order of their appearance in an initialization list, compilers
would
have to keep track of the order in which the members were initialized for
each
object, just to ensure that the destructors would be called in the right
order.
That would be an expensive proposition. To avoid that overhead, the order
of construction and destruction is the same for all objects of a given
type,
and the order of members in an initialization list is ignored."
In example section variable b from class A will not be initialized as we
assumed (initialized by the same value).
See also: INIT-06, INIT-14, MISRA-030

BENEFITS
Prevents access to null pointer when memory is not allocated.

EXAMPLE
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int b;
int a;
};
class B : public A {
public:
B( int );
private:
int a;
float b;

// Violation - b is declared before a

};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}
before b

// Violation - a is declared

REPAIR
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int a;
int b;
};

// OK - a is declared before b

class B : public A {
public:
B( int );
private:
float b;
int a;
};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}

// OK - b is declared before a

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 13
3, JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 75
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declare an assignment operator for classes with dynamically allocated memory [JSF-76_a-2]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or
'delete' to deallocate its data member, has an explicitly defined
canonical
assignment operator. A canonical assignment operator returns a class
reference
type and takes a const reference of the type.
"An assignment is not inherited like other operators. If an assignment
operator
is not explicitly defined, then one is automatically defined instead.
If you perform an assignment 'b = a;' (where 'a' and 'b' are pointers)
there is
no client-defined operator= to call, so C++ generates and calls the
default
assignment operator instead.
This default assignment operator performs memberwise assignment from the
members of 'a' to the members of 'b', which for pointers is just a bitwise
copy.
There are at least two problems with this state of affairs.
First, the memory that 'b' used to point to was never deleted;
it is lost forever. This is a classic example of how a memory leak can
arise.
Second, both 'a' and 'b' now contain pointers to the same character
string.
When one of them goes out of scope, its destructor will delete the memory
still pointed to by the other."
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-38,
MRM-40, MRM-47, OOP-27, OOP-30, OOP-34

EXCEPTIONS
Rule does not report violation if there's an assignment operator in a base
class which prevents implicitly declared assignment operator in this class
from being used.

BENEFITS
"Bit-wise copying is only performed for member data having primitive

types.
One consequence of this is that bit-wise copying is performed for member
data
having pointer types. If an object manages the allocation of the instance
of
an object pointed to by a pointer member, this will probably lead to
problems:
either by invoking the destructor for the managed object more than once or
by
attempting to use the deallocated object."

EXAMPLE
class MyClass { // Violation
public:
MyClass( );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}

REPAIR
class MyClass { // OK
public:
MyClass( );
MyClass& operator=( const MyClass& );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 AssignmentOperators - Rule 27
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declare a copy constructor for classes with dynamically allocated memory [JSF-76_b-2]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or 'delete' to deallocate its data member, has an explicitly defined copy
constructor.
See also: CODSTA-CPP-19, MRM-05, MRM-37, MRM-40, MRM-48, OOP-27, OOP-30,
OOP-34

EXCEPTIONS
Rule does not report violation if there's an copy constructor in a base
class which prevents implicitly declared copy constructor in this class
from being used.

BENEFITS
"A copy constructor is recommended to
is initialized using an object of the
the allocation and deallocation of an
object has a pointer to the object to
constructor),
only the value of the pointer will be
invocations
of the destructor for the same object
in a run-time error."

EXAMPLE
class MyClass{ // Violation
public:
MyClass();
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}

avoid surprises when an object


same type. If an object manages
object on the heap (the managing
be created by the class'
copied. This can lead to two
(on the heap), probably resulting

REPAIR
class MyClass{ // OK
public:
MyClass();
MyClass(MyClass&);
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 25
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Constructors,
Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A copy constructor shall copy all data members and bases [JSF-77-2]
DESCRIPTION
"A class may contain many data members as well as exist within an
inheritance
hierarchy. Hence the copy constructor must copy all members, including
those
in base classes."

SINCE
v7.1

NOTES
The rule does not report violations on variables of class/struct type.
If a copy constructor of base class is called then the rule assumes
that all variables from a base class are copied.

BENEFITS
"Ensure data members and bases are properly handled when an object is
copied."

EXAMPLE
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:

Derived (int x, int y, int z) : Base (x),


derived_member_1 (y),
derived_member_2 (z) { }
Derived(const Derived& rhs)
{
}

// Violation

private:
int derived_member_1;
int derived_member_2;
};

REPAIR
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:
Derived (int x, int y, int z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) { }
Derived(const Derived& rhs) : Base(rhs),
derived_member_1 (rhs.derived_member_1),
derived_member_2 (rhs.derived_member_2)
{
}
private:
int derived_member_1;
int derived_member_2;
};

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The definition of a constructor shall not contain default arguments that produce a signature
identical to that of the implicitly-declared copy constructor [JSF-77.1-2]
DESCRIPTION
The definition of a member function shall not contain default arguments
that
produce a signature identical to that of the implicitly-declared copy
constructor for the corresponding class/structure.

SINCE
v7.1

BENEFITS
If the class definition does not explicitly declare a copy constructor,
one is declared implicitly. Thus, for the class definition
class X
{
X(const X&, int);
};
a copy constructor is implicitly-declared. If the user-declared
constructor
is later defined as
X::X(const X& x, int i =0)
{
/* ... */
}
then any use of X's copy constructor is ill-formed because of the
ambiguity.

EXAMPLE
class A
{
A(const A&, int);
A(const A&);

};
A::A(const A& x, int i =0) // Violation
{
/* ... */
}

REPAIR
class A
{
A(const A&, int i=0);
A(const A&);
};
A::A(const A& x, int i) // OK
{
/* ... */
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Define a virtual destructor in classes used as base classes which have virtual functions [JSF78-2]
DESCRIPTION
All classes which are used as base classes and which have virtual
functions
must define a virtual destructor. If a class, having virtual functions but
without virtual destructors, is used as a base class, there may be a
surprise
if pointers to the class are used. If such a pointer is assigned to an
instance
of a derived class and if delete is then used on this pointer, only the
base
class' destructor will be invoked. If the program depends on the derived
class'
destructor being invoked, the program will fail.
See also: OOP-23, OOP-24, OOP-31

BENEFITS
Define a virtual destructor in order to prevent data corruption.

EXAMPLE
class Base
// Violation
{
public:
virtual void foo( );
~Base( );
};
class Derived : public Base{};

REPAIR
class Base
// OK
{
public:
virtual void foo( );

virtual ~Base( );
};
class Derived : public Base{};

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 26
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 78

Call fclose() on pointer member in destructor if the pointer was used to open a file [JSF-79-2]
DESCRIPTION
This rule reports a violation message when pointer member was used to open
a file in constructor and the file is not closed in destructor.
See also: MRM-33

SINCE
v7.1

BENEFITS
Prevention of resource leaks, especially in error cases.
Releasing resources in a destructor provides a convenient means of
resource
management, especially in regards to exceptional cases. Moreover, if it is
possible that a resource could be leaked, then that resource should be
wrapped
in a class whose destructor automatically cleans up the resource.

EXAMPLE
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}

~File_ptr ()
{
}
private:

// Violation

FILE *p;
};

REPAIR
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}

~File_ptr ()
{
if (p)
{
fclose(p);
}
}

// OK

private:
FILE *p;
};

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 79
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Check for assignment to self in operator= [JSF-81-2]


DESCRIPTION
This rule checks your code for aliasing in assignment operators. Not
checking
for assignment to self in operator= can free resources that might be
needed
during the process of allocating new resources.
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37,
MRM-40,
MRM-47, OOP-27, OOP-30

BENEFITS
Checking for assignment to self may also save you a lot of work that you
would otherwise have to do to implement assignments.

EXAMPLE
class A {
public:
A( ) { }
A& operator=( A& a ) {
return *this;
}
};

// Violation

REPAIR
class A {
public:
A( ) { }
A& operator=( A& a ) {
if (&a != this) {
// ...
}
return *this;
}
};

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 11
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 17
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 81

Have assignment operator returns a reference to *this; make assignment operator's return
type a non-const reference to it's class' type [JSF-82-2]
DESCRIPTION
This rule makes sure your assignment operator's return type is non-const
reference to it's class' type and that it returns a reference to its lefthand
argument, *this. Having operator= return a reference to *this protects you
from not knowing where the temporary gets destroyed and allows you to
declare
the operator='s parameter as a reference to const, which is safer than
just
declaring it to be a reference.
See also: CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37, MRM-40, MRM-47,
OOP-27,
OOP-30, OOP-34

BENEFITS
Returning reference to *this in operator= functions protects you from not
knowing where the temporary gets destroyed and allows you to declare
the operator='s parameter as a reference to const, which is safer than
just
declaring it to be a reference.

EXAMPLE
class A {
public:
A( ) { }
void operator=( A& a ) {
return;
}
};
class C {
public:
C( ) { }
C operator=( C& c ) {
C *cp;
return *cp;
}

// Violation

// Violation

};

REPAIR
class A {
public:
A( ) { }
A& operator=( A& a ) {
return *this;
}
};
class C {
public:
C( ) { }
C& operator=( C& c ) {
return *this;
}
};

// OK

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 15
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 15
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 82
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The assignment operator must assign all members, including those in base classes [JSF-83-2]
DESCRIPTION
A class may contain many data members as well as exist within
an inheritance hierarchy. Hence the assignment operator must
assign all members, including those in base classes.
Rule reports a violation message if base class assignment
operator is not called or not all base classes' member variables
are assigned within derived class assignment operator.
See also: INIT-11

SINCE
v7.1

BENEFITS
Assign to all member variables in operator= function
in order to prevent data corruption.

EXAMPLE
typedef unsigned int int32;
class Base
{
public:
Base (int32 x) : base_member (x) {}
Base &operator=(const Base& rhs)
{
if (this != &rhs)
{
base_member = rhs.base_member;
}
else
{
}
return *this;
}
private:

int32 base_member;
};

class Derived : public Base


{
public:
Derived (int32 x, int32 y, int32 z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) {}
Derived& operator=(const Derived& rhs)
// Violation
{
if (this != &rhs)
{
derived_member_1 = rhs.derived_member_1;
derived_member_2 = rhs.derived_member_2;
}
else
{
}
return *this;
}
private:
int32 derived_member_1;
int32 derived_member_2;
};

REPAIR
typedef unsigned int int32;
class Base
{
public:
Base (int32 x) : base_member (x) {}
Base &operator=(const Base& rhs)
{
if (this != &rhs)
{
base_member = rhs.base_member;
}
else
{

}
return *this;
}
private:
int32 base_member;
};

class Derived : public Base


{
public:
Derived (int32 x, int32 y, int32 z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) {}
Derived& operator=(const Derived& rhs)
{
if (this != &rhs) // Check for self-assignment
{
Base::operator=(rhs);
derived_member_1 = rhs.derived_member_1;
derived_member_2 = rhs.derived_member_2;
}
else
{
}
return *this;
}
private:
int32 derived_member_1;
int32 derived_member_2;
};

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 83
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

// OK

When two operators are opposites (such as == and !=), it is appropriate to define both [JSF-853]
DESCRIPTION
"When a client of a class is allowed to apply an operator against a class,
it also expects to be able to apply the negation of that operator against
a class. A good example is the operator==; its semantic opposite is the
operator!=, which should also be defined if operator== was defined."
Rule prevents using:
- '==' operator without '!=' operator
- '<=' operator without '>=' operator
- '<' operator without '>' operator
- '++' operator without '--' operator
- '+' operator without '-' operator
- '<<' operator without '>>' operator
- '&&' operator without '||' operator

BENEFITS
Rule improves readability and maintainability of code and
prevents misunderstanding the meaning of an overloaded operator.

EXAMPLE
class C { // Violation
public:
bool operator<=( C& c );
};

REPAIR
class C { // OK
public:
bool operator<=( C& c );
bool operator>=( C& c );
};

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.7 Operator Overloading - Rec. 36
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 85
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Hierarchies should be based on abstract classes [JSF-87-4]


DESCRIPTION
Public inheritance hierarchy should start from abstract class.

SINCE
v7.1

BENEFITS
Hierarchies based on abstract classes tend to focus designs toward
producing clean interfaces, keep implementation details out of
interfaces, and minimize compilation dependencies while allowing
alternative implementations to coexist.

EXAMPLE
class B
{
};
class A: public B // Violation
{
};

REPAIR
class B
{
public:
virtual int foo()=0;
/* ... */
};

class A: public B // OK
{

};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 87

A stateful virtual base shall be explicitly declared in each derived class that accesses it [JSF88.1-2]
DESCRIPTION
A stateful virtual base shall be explicitly declared
in each derived class that accesses it.

SINCE
v7.1

BENEFITS
"Explicitly declaring a stateful virtual base at each level in a hierarchy
(where that base is used), documents that fact that no assumptions
can be made with respect to the exclusive use of the data contained
within the virtual base."

EXAMPLE
class
class
class
class
class
class

AA
BB
CC
DD
EE
FF

{};
: virtual AA {};
: virtual AA {};
: BB{};
// Violation
: CC{};
// Violation
: DD{};
// Violation

REPAIR
class
class
class
class
class
class

AA
BB
CC
DD
EE
FF

{};
: virtual AA {};
: virtual AA {};
: BB, virtual AA {};
// OK
: CC, virtual AA {};
// OK
: DD, EE, virtual AA {}; // OK

REFERENCES

1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.10 Classes, AV Rule 88.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A base class shall not be both virtual and non-virtual in the same hierarchy [JSF-89-2]
DESCRIPTION
A base class shall not be both virtual and non-virtual
in the same hierarchy.

SINCE
v7.1

BENEFITS
Hierarchy becomes easier to comprehend and use.

EXAMPLE
class A {};
class B : virtual A {};
class C : B, A {};

// Violation

REPAIR
class A {};
class B : virtual A {};
class C : B, virtual A {};

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 89
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-1-3
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Only use characters defined in ISO C standard [JSF-9-3]


DESCRIPTION
Only those characters and escape sequences which are
defined in the ISO C standard shall be used.
Section 5.2.1 of the ISO C standards defines 91 characters
which are the minimum source character set for all
compilers. These are the only characters that should be
used, even if the compiler supports a larger character set,
or supports alternative character sets.
Those
- the
A B C
N O P

characters are:
26 uppercase letters of the Latin alphabet
D E F G H I J K L M
Q R S T U V W X Y Z

- the 26 lowercase letters of the Latin alphabet


a b c d e f g h i j k l m
n o p q r s t u v w x y z
- the 10 decimal digits
0 1 2 3 4 5 6 7 8 9
- the following 29 graphic characters
_{}[]#()<>%:;.?*+-/^&|~!=,\"'
- the space character, and control characters representing
horizontal tab, vertical tab, form feed and new line.

BENEFITS
Minimal required character set.

EXAMPLE
void foo() {
char c1 = '$';
char c2 = '`';
}

/* Violation */
/* Violation */

REPAIR
Do not use characters no defined in the ISO C standard.

REFERENCES
1. Origin: Misra Guidelines - Rule 5
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 9

Never redefine an inherited nonvirtual function [JSF-94_a-2]


DESCRIPTION
"Nonvirtual functions are statically bound. In essence, a nonvirtual
function will hide its corresponding base class version. Hence a single
derived class object may behave either as a base class object or as a
derived class object depending on the way in which it was accessed either
through a base class pointer/reference or a derived class
pointer/reference.
To avoid this duality in behavior, nonvirtual functions should never be
redefined."
See also: OOP-33

NOTES
This rule reports violations for functions without template parameter.
Rule OOP-33 reports violations for functions with template parameter.

BENEFITS
This rule prevents misinterpretation which function is called.

EXAMPLE
class Base
{
public:
void func1(void) {};
void func2(int x) {};
void func3(int x) {};
};
class Derived: public Base
{
public:
void func1(void) {};
void func2(int x) {};
void func3(int x) {};
};

// Violation
// Violation
// Violation

REPAIR
class Base
{
public:
virtual void func1(void) {};
virtual void func2(int x) {};
void func3(int x) {};
};
class Derived: public Base
{
public:
virtual void func1(void) {};
virtual void func2(int x) {};
void func3_renamed(int x) {};
};

// OK
// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 36
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Inheritance and Object-Oriented Design", Item 37
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 94

Do not redefine an inherited nonvirtual function with template parameter [JSF-94_b-2]


DESCRIPTION
"Nonvirtual functions are statically bound. In essence, a nonvirtual
function will hide its corresponding base class version. Hence a single
derived class object may behave either as a base class object or as a
derived class object depending on the way in which it was accessed either
through a base class pointer/reference or a derived class
pointer/reference.
To avoid this duality in behavior, nonvirtual functions should never be
redefined."
See also: OOP-32

NOTES
This rule reports violations for functions with template parameter.
Rule OOP-32 reports violations for functions without template parameter.

BENEFITS
This rule prevents misinterpretation which function is called.

EXAMPLE
template <class T>
{
public:
void foo1(T
void foo2(T
void foo3(T
};

class Base

i) {}
i) {}
i) {}

template <class T> class Derived : public Base <T>


{
public:
void foo1(int i) {} // Violation
void foo2(T i) {}
// Violation
void foo3(T i) {}
// Violation
};

REPAIR
template <class T> class Base
{
public:
virtual void foo1(T i) {}
virtual void foo2(T i) {}
void foo3(T i) {}
};
template <class T> class Derived :
{
public:
virtual void foo1(int i) {}
virtual void foo2(T i) {}
void foo3_renamed(T i) {}
};

public Base <T>

// OK
// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 36
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Inheritance and Object-Oriented Design", Item 37
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 94

Do not redefine an inherited virtual function with a different default parameter value [JSF-95-2]
DESCRIPTION
"Virtual functions are dynamically bound, but default parameters are
statically
bound. That means that you may end up invoking a virtual function defined
in a derived class but using a default parameter value from a base class"
This rule detects cases when you redefine an inherited virtual function
with a different default parameter value.

NOTES
Rule does not check:
- functions with template parameters
- non-constant default parameter values
- default parameter values with complex expressions

BENEFITS
This rule prevents misinterpretation which value is passed as default.

EXAMPLE
class Base
{
public:
virtual void func(int i = 1);
};
class Derived: public Base
{
public:
virtual void func(int i = 0);
};

REPAIR
class Base
{

// Violation

public:
virtual void func1(int i = 1);
virtual void func2(int i = 1);
};
class Derived: public Base
{
public:
virtual void func1(int i);
virtual void func2(int i = 1);
};

// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 37
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Inheritance and ObjectOriented Design", Item 38
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 95
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Don't treat arrays polymorphically [JSF-96-2]


DESCRIPTION
"Arrays are ill-adjusted: Treating arrays polymorphically is a gross type
error that your compiler will probably remain silent about.
Don't fall into the trap."

BENEFITS
Rule prevents leading code to grief.
Array operations almost always involve pointer arithmetic,
so arrays and polymorphism don't mix.

EXAMPLE
class BST {
public:
void cleanBSTArray(BST array[], int numElements)
{
for (int i = 1; i < numElements; ++i)
{
array[i] = array[0];
}
}
void deleteArray(BST array[])
{
delete [] array;
}
};
class BalancedBST: public BST {};
void foo()
{
BalancedBST *p;
BST BSTArray[10];
BalancedBST bBSTArray[10];
p->cleanBSTArray(bBSTArray, 10);
p->deleteArray(bBSTArray);

// Violation
// Violation

REPAIR
class BST {
public:
void cleanBSTArray(BST array[], int numElements)
{
for (int i = 1; i < numElements; ++i)
{
array[i] = array[0];
}
}
void deleteArray(BST array[])
{
delete [] array;
}
};
class BalancedBST: public BST {};
void foo()
{
BalancedBST *p;
BST BSTArray[10];
BalancedBST bBSTArray[10];
p->cleanBSTArray(BSTArray, 10);
p->deleteArray(BSTArray);

// OK
// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 100
2. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Basics", Item 3

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.10 Classes, AV Rule 96
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Arrays shall not be used in interfaces [JSF-97-2]


DESCRIPTION
Array parameters should not be used in public methods.
Instead, the Array class should be used.

SINCE
v7.1

NOTES
Rule defines an interface as a public method.

BENEFITS
Arrays degenerate to pointers when passed as parameters.
This "array decay" problem has long been known to be a source of errors.

EXAMPLE
class Sample
{
public:
void foo(int a[]); // Violation
};

REPAIR
class Array
{
/* Array implementation*/
};

class Sample
{
public:

void goo(Array a); // OK


};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 97

Avoid using global variables, global functions, and class in file outside namespaces [JSF-984]
DESCRIPTION
This rule detects the use of global variables, classes,
and global functions outside of namespaces.

BENEFITS
Prevents the use of global variables, classes, and global functions
outside namespaces. All data and functions in a file should be inside
one or more namespaces.

EXAMPLE
int var = 0;

// Violation

void globalfoo( ) { // Violation


}
class A {
int i;
void foo( );
};

// Violation

REPAIR
namespace name1 {
int var = 0;

// OK

void globalfoo( ) { // OK
}
class A {
int i;
void foo();
};
}

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.11 Namespaces, AV Rule 98
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-3-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
4. ISO/DIS 26262
point 8.4.4

Namespaces will not be nested more than two levels deep [JSF-99-3]
DESCRIPTION
Namespaces will not be nested more than two levels deep.

SINCE
v7.1

BENEFITS
Simplicity and clarity.
Deeply nested namespaces can be difficult to comprehend and use correctly.

EXAMPLE
namespace A
{
namespace B
{
namespace C
{
namespace D // Violation
{
}
}
}
}

REPAIR
namespace A
{
namespace B
{
namespace C // OK
{
}
namespace D // OK

{
}
}
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.11 Namespaces, AV Rule 99

METRICS
Metrics
RULES
Avoid functions with over 50 lines [METRICS-01-5]
Avoid switch statements with many cases [METRICS-02-5]
Number of blocks of code in a function [METRICS-03-3]
Number of function calls within function [METRICS-04-3]
Class inheritance level [METRICS-05-3]
Number of data member(s) per class should not exceed 15 [METRICS-06-3]
Number of methods per class [METRICS-07-3]
Number of parameter(s) per method should not exceed 10 [METRICS-08-3]
Number of private data member(s) per class [METRICS-09-3]
Number of private methods per class [METRICS-10-3]
Number of protected data member(s) per class [METRICS-11-3]
Number of protected methods per class [METRICS-12-3]
Number of public data member(s) per class [METRICS-13-3]
Number of public methods per class [METRICS-14-3]
Avoid functions with more than 5 parameters [METRICS-15-3]
Macros should not use more than 5 parameters [METRICS-16-3]
Avoid structs, unions, or classes with more than 20 fields [METRICS-17-5]
Follow the Cyclomatic Complexity limit of 10 [METRICS-18-3]
The percentage of comment lines versus the total number of module lines
should be between 20 and 60 [METRICS-19-3]
Avoid too long functions (declarations and statements) [METRICS-20-3]
Avoid too long functions (blocks) [METRICS-21-3]
Avoid functions with over 75 lines of code [METRICS-22-3]
Nested block depth should not be higher than 5 [METRICS-23-3]
Avoid source files that are longer than 500 lines [METRICS-24-5]
Any one function (or method) will contain no more than 200 logical source
lines of code (L-SLOCs) [METRICS-25-3]
Source lines will be kept to a length of 120 characters or less [METRICS26-3]
Functions with more than 7 parameters will not be used [METRICS-27-3]
Follow the Cyclomatic Complexity limit of 20 [METRICS-28-3]
Report Cyclomatic Complexity [METRICS-29-5]
No function should be longer than 60 lines of code [METRICS-30-3]
The assertion density of the code should average to a minimum of two
assertions per function [METRICS-31-3]
All functions with more than 20 lines should contain at least 2 assertions
[METRICS-32-3]
Report Essential Complexity [METRICS-33-5]
Follow the Essential Complexity limit of 4 [METRICS-34-5]
Follow the Essential Complexity limit of 10 [METRICS-35-5]

A function should not be called from more than 5 different functions


[METRICS-36-3]
A function should not call more than 7 different functions [METRICS-37-3]
The number of statements within function should be in range 1 - 50
[METRICS-38-3]
The value of VOCF metric for a function should not be higher than 4
[METRICS-39-3]
Statements within function should not be nested deeper than 4 levels
[METRICS-40-3]
The number of blocks of comments before and inside function to the number
of statements in function should be > 0.2 [METRICS-41-3]
Follow the limit for Coupling Between Objects [METRICS-CBO-1]
Follow the limit for Inheritance Depth [METRICS-ID-5]
Follow the limit for Lack Of Cohesion [METRICS-LCOM-1]
Follow the limit for Number Of Constructors [METRICS-NOCT-3]
Follow the limit for Number Of Instance Fields [METRICS-NOF-4]
Follow the limit for Number Of Fields [METRICS-NOFT-2]
Follow the limit for Number Of Instance Methods [METRICS-NOM-4]
Follow the limit for Number Of Methods [METRICS-NOO-4]
Follow the limit for Number Of "private" Fields [METRICS-NPRIF-2]
Follow the limit for Number Of "private" Methods [METRICS-NPRIM-2]
Follow the limit for Number Of "protected" Fields [METRICS-NPROF-2]
Follow the limit for Number Of "protected" Methods [METRICS-NPROM-2]
Follow the limit for Number Of "public" Fields [METRICS-NPUBF-2]
Follow the limit for Number Of "public" Methods [METRICS-NPUBM-2]
Follow the limit for Number Of Static Fields [METRICS-NSF-3]
Follow the limit for Number Of Static Methods [METRICS-NSM-3]

Avoid functions with over 50 lines [METRICS-01-5]


DESCRIPTION
If a function is too long, it can be difficult to comprehend.
The program is easier to create and to understand if it contains
functions that do not have more than 50 lines.
The rule counts lines between opening and closing brace {} of function's
body.
See also: METRICS-20, METRICS-21, METRICS-22

BENEFITS
The rule improves readability and maintainability of code.

EXAMPLE
void too_long_function() // Violation
{
int a1;
int a2;
int a3;
/*
* lines of code, comment lines, empty lines
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
}

REPAIR
Limit the size of the function to 50 lines.

REFERENCES
Recommended by ParaSoft

Avoid switch statements with many cases [METRICS-02-5]


DESCRIPTION
Many case statements makes code difficult to follow. More importantly,
switches with many cases often indicate places where polymorphic behavior
could
better be used to provide different behavior for different types.
Note that although the general principle is to avoid many cases in a
switch,
the actual cutoff point is arbitrary.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
void foo(int i) {
// There are over 10 cases in the switch statement.
switch (i) {
// Violation
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
case 9:
break;
case 10:
break;
case 11:

break;
default:
break;
}
}

REPAIR
Look for cleaner ways to invoke the alternative behaviors.

REFERENCES
Recommended by ParaSoft

Number of blocks of code in a function [METRICS-03-3]


DESCRIPTION
This metric measures the number of blocks of code in a function.
Rule checks if the number of blocks within the function exceeds 10.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
void func(int i) {// Violation
if (1) {
// do something;
} else {
// do another;
}
if (1) {
// do something;
} else {
// do another;
}
if (1) {
// do something;
} else {
// do another;
}
if (1) {
// do something;
} else {
// do another;
}
if (1) {
// do something;
}

do {
} while(1);
switch(i) {
case 1:
break;
default:
break;
}
}

REPAIR
The number of blocks within the function should be limited to 10.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 34.

Number of function calls within function [METRICS-04-3]


DESCRIPTION
Rule measures the number of calls to methods
and system functions within function.

NOTES
The rule reports a violation if the number of function calls
within the function exceeds 10.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo {
public:
void func1() {}// OK
void func2() {// Violation
func1();
func1();
func1();
func1();
func1();
func1();
func1();
func1();
func1();
func1();
func1();
}
};

REPAIR
Limit the number of function calls within the function to 10.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December, 1999, pg. 32.

Class inheritance level [METRICS-05-3]


DESCRIPTION
This metric measures the class inheritance level by calculating the number
of base classes.
Rule triggers if the class inheritance level exceeds 10.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
"An unnecessarily deep class hierarchy adds to complexity and can
represent
a poor use of the inheritance mechanism."

EXAMPLE
class
class
class
class
class
class
class
class
class
class
class
class

Base {};// OK
Dev1 : public Base {};// OK
Dev2 : public Dev1 {};// OK
Dev3 : public Dev2 {};// OK
Dev4 : public Dev3 {};// OK
Dev5 : public Dev4 {};// OK
Dev6 : public Dev5 {};// OK
Dev7 : public Dev6 {};// OK
Dev8 : public Dev7 {};// OK
Dev9 : public Dev8 {};// OK
Dev10 : public Dev9 {};// OK
Dev11 : public Dev10 {};// Violation

REPAIR
Limit he number of base classes to 10.

REFERENCES

By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"


IT Professional, November/December, 1999, pg. 33.

Number of data member(s) per class should not exceed 15 [METRICS-06-3]


DESCRIPTION
This metric measures the number of data members per class.
Rule checks if number of declared data members per class exceeds 15.
See also: METRICS-17

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo { // Violation
public:
int i1;
int i2;
int i3;
int i4;
int i5;
int i6;
protected:
int j1;
int j2;
int j3;
int j4;
int j5;
int j6;
int j7;
private:
int k1;
int k2;
int k3;
};

REPAIR
Limit the number of data members to 15 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December, 1999, pg. 33.

Number of methods per class [METRICS-07-3]


DESCRIPTION
"The number of methods per class indicates the total level of
functionality
implemented by a class."
This metric measures the number of methods per class.
Rule triggers if the number of methods per class exceeds 20.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo {// Violation
public:
void method1();
void method2();
void method3();
void method4();
void method5();
void method6();
protected:
void method7();
void method8();
void method9();
void method10();
void method11();
void method12();
private:
void method13();
void method14();
void method15();

void
void
void
void
void
void

method16();
method17();
method18();
method19();
method20();
method21();

};

REPAIR
Limit the number of methods to 20 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December, 1999, pg. 33.

Number of parameter(s) per method should not exceed 10 [METRICS-08-3]


DESCRIPTION
"A high number of parameters indicates a complex interface to calling
objects,
and should be avoided."
This metric measures the number of parameters in each method.
Rule triggers if the number of parameters exceeds 10 per method.
See also: METRICS-15
NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo
{
public:
void func2(int ,int ,int ,int ,int ,int ,int ,int ,int ,int ,int ); //
Violation
};

REPAIR
// Limit the number of parameters to 10 per method.
class Foo
{
public:
void func(int i, double d, float f, char c, Foo &); // OK
};

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"

IT Professional, November/December, 1999, pg. 34.

Number of private data member(s) per class [METRICS-09-3]


DESCRIPTION
This metric measures the number of private data members per class.
Rule triggers if the number of private data members exceeds 15 per class.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo { // Violation
private:
int i1;
int i2;
int i3;
int i4;
int i5;
int i6;
int
int
int
int
int
int
int

j1;
j2;
j3;
j4;
j5;
j6;
j7;

int k1;
int k2;
int k3;
};

REPAIR
Limit the number of private data members to 15 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 33.

Number of private methods per class [METRICS-10-3]


DESCRIPTION
"The number of methods per class indicates the total level of
functionality
implemented by a class."
This metric measures the number of private methods per class.
Rule triggers if the number of private methods exceeds 10 per class.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo {// Violation
private:
void method1();
void method2();
void method3();
void method4();
void method5();
void method6();
void method7();
void method8();
void method9();
void method10();
void method11();
};

REPAIR
Limit the number of private methods to 10 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 33.

Number of protected data member(s) per class [METRICS-11-3]


DESCRIPTION
This metric measures the number of protected data members per class.
Rule triggers if the number of protected data members exceeds 15 per
class.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo {// Violation
protected:
int i1;
int i2;
int i3;
int i4;
int i5;
int i6;
int
int
int
int
int
int
int

j1;
j2;
j3;
j4;
j5;
j6;
j7;

int k1;
int k2;
int k3;
};

REPAIR
Limit the number of protected data members to 15 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 33.

Number of protected methods per class [METRICS-12-3]


DESCRIPTION
"The number of methods per class indicates the total level of
functionality
implemented by a class."
This metric measures the number of protected methods per class.
Rule triggers if the number of protected methods exceeds 10 per class.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo {// Violation
protected:
void method1();
void method2();
void method3();
void method4();
void method5();
void method6();
void method7();
void method8();
void method9();
void method10();
void method11();
};

REPAIR
Limit the number of protected methods to 10 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 33.

Number of public data member(s) per class [METRICS-13-3]


DESCRIPTION
This metric measures the number of public data members per class.
Rule triggers if the number of public data members exceeds 15 per class.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo {// Violation
public:
int i1;
int i2;
int i3;
int i4;
int i5;
int i6;
int
int
int
int
int
int
int

j1;
j2;
j3;
j4;
j5;
j6;
j7;

int k1;
int k2;
int k3;
};

REPAIR
Limit the number of public data members to 15 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 33.

Number of public methods per class [METRICS-14-3]


DESCRIPTION
"The number of methods per class indicates the total level of
functionality
implemented by a class."
This metric measures the number of public methods per class.
Rule triggers if the number of public methods exceeds 20 per class.

NOTES
This rule applies only to the C++ programming language.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
class Foo {// Violation
public:
void method1();
void method2();
void method3();
void method4();
void method5();
void method6();
void method7();
void method8();
void method9();
void method10();
void method11();
void method12();
void method13();
void method14();
void method15();
void method16();
void method17();
void method18();
void method19();

void method20();
void method21();
};

REPAIR
Limit the number of public methods to 20 per class.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 33.

Avoid functions with more than 5 parameters [METRICS-15-3]


DESCRIPTION
The number of parameters in a function should be limited to five or less.
This should be done to reduce the amount of coupling between functions.
If more parameters are needed, a structure could be used to hold
related data and a pointer could be passed.
See also: METRICS-08

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
void foo(int a, int b, int c, int d, int e, int f) // Violation
{
}

REPAIR
Limit the number of parameters to 5 per function.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 41
2. Motorola Coding Standards G-6
3. HIS Source Code Metriken, version 1.3.1
Metrik "PARAM"

Macros should not use more than 5 parameters [METRICS-16-3]


DESCRIPTION
This rule checks that macros do not use more than 5 parameters.
If a large number of parameters are passed to a macro,
it may become hard to read and understand.
If this occurs, it may be beneficial to break the macro down
into multiple macros or make it into a function.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
#define PLUS(a,b,c,d,e,f) (a+b+c+d+e+f) // Violation

REPAIR
Limit the number of parameters to 5 per macro.

REFERENCES
Recommended by ParaSoft

Avoid structs, unions, or classes with more than 20 fields [METRICS-17-5]


DESCRIPTION
This rule is purely informational and will report a message when a struct,
union or class declaration is found with more than 20 fields.
See also: METRICS-06

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
struct
{
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
};

_tA// Violation
i0;
i1;
i2;
i3;
i4;
i5;
i6;
i7;
i8;
i9;
i10;
i11;
i12;
i13;
i14;
i15;
i16;
i17;
i18;
i19;
i20;
i21;
i22;
i23;

REPAIR
Limit the number of fields to 20.

REFERENCES
Recommended by ParaSoft

Follow the Cyclomatic Complexity limit of 10 [METRICS-18-3]


DESCRIPTION
This rule identifies methods that do not satisfy the user-defined
requirement
for Cyclomatic Complexity.
Cyclomatic Complexity is calculated according to the formula:
CC = Number of decisions + 1
By decision we mean every occurrence of:
-'if'
-'for'
-'while'
-'do-while'
-'case'
-'catch'
-conditional expression 'a?b:c'
-logical operator '&&' and '||'
An error is reported if a function have a Cyclomatic Complexity higher
than 10.
See also: METRICS-28, METRICS-29, METRICS-33, METRICS-34, METRICS-35

NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 10" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for
N.

BENEFITS

Studies have found that methods with high Cyclomatic Complexity are errorprone.

EXAMPLE
void foo(int a, int b) // Violation - CC value: 11
{
switch (a)
{
case 1:
// 1
break;
case 2:
// 2
break;
case 3:
// 3
break;
default:
break;
}
if(a||b)
// 4, 5
{
}
if((a||b)&&(a&&b)) // 6, 7, 8, 9
{
}
do
// 10
{
}while(0);
}

REPAIR
Keep a Cyclomatic Complexity value on the level lower than 10.

REFERENCES
McCabe, T., "A Complexity Measure," IEEE Transactions on Software
Engineering, December 1976.
HIS Source Code Metriken, version 1.3.1
Metrik "v(G)"

The percentage of comment lines versus the total number of module lines should be between
20 and 60 [METRICS-19-3]
DESCRIPTION
Rule checks if percentage of comment lines versus the total number of
method
lines is between 20 and 60.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo1(int y) {// Violation
//
//
//
//
}
void foo12() {// Violation
/*

*/
}
void foo3() {// Violation
/**//**//**//**/
}
void foo4() {// Violation

REPAIR
void foo1() {// OK
//
//
//
//

}
void foo2() {// OK
/*
*/

}
void foo3() {// OK
/**//**//**//**/

REFERENCES
Recommended by ParaSoft

Avoid too long functions (declarations and statements) [METRICS-20-3]


DESCRIPTION
Long functions have disadvantages:
"If a function is too long, it can be difficult to comprehend.
Generally, it can be said that a function should not be longer
than two pages, since that is about how much that can be comprehended
at one time.
If an error situation is discovered at the end of an extremely long
function,
it may be difficult for the function to clean up after itself and
to "undo" as much as possible before reporting the error to
the calling function. "
See also: METRICS-01, METRICS-21, METRICS-22

NOTES
Rule triggers when the number of declarations and statements within
function body exceeds 50.

BENEFITS
By always using short functions, such an error can be more exactly
localized.

EXAMPLE
void too_long_function() {// Violation
int a1;
int a2;
int a3;
int a4;
int a5;
int a6;
int a7;
int a8;
int a9;
int a10;
int a11;
int a12;

int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
}

a13;
a14;
a15;
a16;
a17;
a18;
a19;
a20;
a21;
a22;
a23;
a24;
a25;
a26;
a27;
a28;
a29;
a30;
a31;
a32;
a33;
a34;
a35;
a36;
a37;
a38;
a39;
a40;
a41;
a42;
a43;
a44;
a45;
a46;
a47;
a48;
a49;
a50;
a51;
a52;
a53;
a54;

REPAIR
Number of declarations and statements within function body
should be limited to 50.

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.7 General - Rec 47

Avoid too long functions (blocks) [METRICS-21-3]


DESCRIPTION
"Avoid long and complex functions. Complex functions are difficult to
test.
If a function consists of 15 nested if statements, then there are 2**15
(or 32768) different branches to test in a single function."
See also: METRICS-01, METRICS-20, METRICS-22

NOTES
Rule triggers if function contains more than 10 blocks.

BENEFITS
By always using short and simple functions, such an error can be more
exactly
localized and function testing is much easier.

EXAMPLE
void func( int i ) {
if (1) {
} else {
}
do {
} while(1);
switch(i) {
case 1:
break;
default:
break;
}
if (1) {
} else {
}
if (2) {
} else {
}
if (3) {

// Violation

} else {
}
}

REPAIR
Limit the number of blocks within function body to 10.

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.7 General - Rec. 47

Avoid functions with over 75 lines of code [METRICS-22-3]


DESCRIPTION
"Excessively long functions and nested code blocks are often caused by
failing
to give one function one cohesive responsibility, and both are usually
solved
by better refactoring."
See also: METRICS-01, METRICS-20, METRICS-21

BENEFITS
Rule improves

readability and maintainability of code.

EXAMPLE
class A
{
void foo( int x )
// Violation
{
// ...
// more than 75 lines of constants, declarations, expressions,
// statements, types
// ...
}
};

REPAIR
Do not type functions longer than 75 lines of code.

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 20

Nested block depth should not be higher than 5 [METRICS-23-3]


DESCRIPTION
"Each level of nesting adds intellectual overhead when reading code
because you
need to maintain a mental stack. Prefer better functional decomposition to
help
avoid forcing readers to keep as much context in mind at a time"
The rule reports violation if the nesting level in function is higher than
5.
Following elements of code are recognized as levels:
- if-else construction
- try-catch construction
- for, while, do-while loops
- switch statement
- block {} that is not a part of any of the above statements
See also: METRICS-40

NOTES
It is possible to change the allowed nesting level by modifying
one element of rule in Rule Wizard. The level is checked by expression
in last "Count" node. The default "$$==5" expression imposes maximum
nesting level of 5. For example, to report violation if nesting level is
higher than 10, change the expression to "$$==10".

BENEFITS
"Excessive block nesting depth (e.g. if, for, while, and try blocks) make
functions more difficult to understand and maintain, and often needlessly
so."

EXAMPLE
int foo1(int i)
{
if(i > 1){

if(i > 2){


if(i > 3){
if(i > 4){
if(i > 5){
++i;
if(i > 6){
++i;
if(i > 7){
reported on level 6
return
}
}
} else {
++i;
if(i == 6){
return 6;
}
}
}
}
}
}
}
int foo2(int i)
{
if(i == 1)
return i;
else if(i == 2)
return i;
else if(i == 3)
return i;
else if(i == 4)
return i;
else if(i == 5)
return i;
else if(i == 6)
return i;
else if(i == 7)
6
return i;

// OK - 5 level
// Violation - 6 level
// OK - 7 level - violation already
i;

// Violation - 6 level

// OK - 5 level
// Violation - 6 level
// OK - 7 level - violation already reported on level

// The above statement is in fact identical to following:

if(i == 1) {
return i;
} else {
if(i == 2) {
return i;
} else {
if(i == 3) {
return i;
} else {
if(i == 4) {
return i;
} else {
if(i == 5) { // OK - 5 level
return i;
} else {
if(i == 6) { // Violation - 6 level
return i;
} else {
if(i == 7) { // OK - 7 level - violation
already reported on level 6
return i;
}
}
}
}
}
}
}
}
int foo3(int i)
{
{
{
{
{
{
{
}
}
}
}
}

// OK - 5 level
// Violation - 6 level
return i;

}
}
void foo4()
{
// try-catch is linear and introduces one level, same as if-else:
try {
// OK - 1 level
} catch(char) {
// OK - 1 level
} catch(int) {
// OK - 1 level
} catch(long) {
// OK - 1 level
} catch(float) {
// OK - 1 level
} catch(double) { // OK - 1 level
} catch(...) {
// OK - 1 level
}
}
int foo5(int i)
{
while(i) { // 1
for(;;) { // 2
if(i) { // 3
} else { // still 3
switch(i) { // 4
case 1: // still 4
++i;
{ // 5
do { // 6 - Violation
return i;
} while(0);
}
}
}
}
}
}
#define MACRO(x) { { { { { { return x; } } } } } }
int foo6(int i)
{
// Code from macros might produce violations
MACRO(i); // Violation
}

REPAIR
Do not
"Avoid
Prefer
Prefer

nest statements more than 5 levels.


nested consecutive ifs where an && condition will do.
automatic cleanup via destructors over try blocks.
algorithms: They're flatter than loops, and often better."

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 20

Avoid source files that are longer than 500 lines [METRICS-24-5]
DESCRIPTION
Source files should be no longer than 500 lines. Experience has shown
that larger files are cumbersome to edit correctly and to maintain.

BENEFITS
Improves maintainability and readability of code.

EXAMPLE
// Source file - Violation
/*
code
*/
#line 501
int i = 0;
// line: 501

REPAIR
Limit source files to 500 lines.

REFERENCES
Recommended by ParaSoft

Any one function (or method) will contain no more than 200 logical source lines of code (LSLOCs) [METRICS-25-3]
DESCRIPTION
Any one function (or method) will contain no more than 200
logical source lines of code (L-SLOCs).

SINCE
v7.1

NOTES
Logical line of code is a single declaration or statement terminated
by semicolon.
Two semicolons in parenthesis after 'for' keyword are counted as one.

BENEFITS
Rule prevents using long functions which tend to be complex and
therefore difficult to comprehend and test.

EXAMPLE
int sample_function(int p)
{
int x, y;

// Violation
// L-SLOCs number = 1

// ...
x++;
// L-SLOCs number = 99
for(y = 10; y > 0; y--){
// L-SLOCs number = 100
x = y;
// L-SLOCs number = 101
}
// ...
x = x + p; y = y + p;
151

// L-SLOCs number = 150, L-SLOCs number =

// ...
return x;

// L-SLOCs number = 201

REPAIR
Do not use functions containing more than 200
logical source lines of code (L-SLOCs).

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 3.2 Code Size and Complexity, AV Rule 1

Source lines will be kept to a length of 120 characters or less [METRICS-26-3]


DESCRIPTION
The rule reports a violation if a physical line contains more
than 120 characters. Very long source lines can be difficult
to read and understand.

SINCE
v7.1

NOTES
Tab is counted as one character.
White spaces at the end of line are counted in the same way as other
characters.
Comments with 'parasoft-suppress' are not counted.
To change the default limit of characters modify the variable
'lineLengthLimit'
at the begin of python method 'check'.(e.g. 'lineLengthLimit = 100' means
that
the maximal allowed number of characters in a physical line is 100)

BENEFITS
The rule improves readability of code.

EXAMPLE
int
/*
..........................................................................
..........*/ i1 ; /* Violation */
int
/* ..........white spaces at the end of
line.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........Violation.......
*

..........................................................................
............................Violation.....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* Violation
*/

REPAIR
int
/*
..........................................................................
................*/ i1 ; /* OK */
int
/* ..........There is no spaces at the
end.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........OK......
*
..........................................................................
............................OK....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + \
xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* OK */
int
/*
..........................................................................
...............*/ i3 ; /* parasoft-suppress ITEM ... OK */

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 41

Functions with more than 7 parameters will not be used [METRICS-27-3]


DESCRIPTION
Functions having long argument lists can be difficult to read,
use, and maintain. Functions with too many parameters may
indicate an under use of objects and abstractions.

SINCE
v7.1

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
void foo(int a, int b, int c, int d, int e, int f, int g, int h)
Violation
{
}

REPAIR
// Limit the number of parameters to 7 per function.
void foo(int a, int b, int c, int d, int e, int f, int g)
{
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
4.13 Function, AV Rule 110

// OK

//

Follow the Cyclomatic Complexity limit of 20 [METRICS-28-3]


DESCRIPTION
This rule identifies methods that do not satisfy the user-defined
requirement
for Cyclomatic Complexity.
Cyclomatic Complexity is calculated according to the formula:
CC = Number of decisions + 1
By decision we mean every occurrence of:
-'if'
-'for'
-'while'
-'do-while'
-'case'
-'catch'
-conditional expression 'a?b:c'
-logical operator '&&' and '||'
An error is reported if a function have a Cyclomatic Complexity higher
than 20.
See also: METRICS-18, METRICS-29, METRICS-33, METRICS-34, METRICS-35

SINCE
v7.1

NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 20" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for

N.

BENEFITS
Studies have found that methods with high Cyclomatic Complexity are errorprone.

EXAMPLE
void foo2(int i, int a, int b, int j, int k)
{
switch (i)
{
case 1: // 1
i++;
default:
i++;
}
switch (j)
{
case 1: // 2
j++;
default:
j++;
}
switch (k)
{
case 1: // 3
k++;
default:
k++;
}
if(a||b)
// 4, 5
{
}
if((a||b)&&(a&&b)) // 6, 7, 8, 9
{
}
do
// 10
{
}while(0);

// Violation - CC value: 21

switch (i)
{
case 1: // 11
i++;
default:
i++;
}
switch (j)
{
case 1: // 12
j++;
default:
j++;
}
switch (k)
{
case 1: // 13
k++;
default:
k++;
}
if(a||b)
// 14, 15
{
}
if((a||b)&&(a&&b)) // 16, 17, 18, 19
{
}
do
// 20
{
}while(0);
}

REPAIR
Keep a Cyclomatic Complexity value on the level lower than 20.

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 3.2 Code Size and Complexity, AV Rule 3

Report Cyclomatic Complexity [METRICS-29-5]


DESCRIPTION
This rule reports the Cyclomatic Complexity value for each function.
Cyclomatic Complexity is calculated according to the formula:
CC = Number of decisions + 1
By decision we mean every occurrence of:
-'if'
-'for'
-'while'
-'do-while'
-'case'
-'catch'
-conditional expression 'a?b:c'
-logical operator '&&' and '||'
See also: METRICS-18, METRICS-28, METRICS-33, METRICS-34, METRICS-35

SINCE
v7.1

NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 0" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for
N.

BENEFITS
Studies have found that methods with high Cyclomatic Complexity are errorprone.

EXAMPLE
void foo(int a, int b) // Violation - CC value: 8
{
if(a||b)
// 1, 2
{
}
if((a||b)&&(a&&b)) // 3, 4, 5, 6
{
}
do
// 7
{
}while(0);
}

REPAIR
This rule is an informational rule and reports message
on each function implementation.

REFERENCES
Recommended by ParaSoft

No function should be longer than 60 lines of code [METRICS-30-3]


DESCRIPTION
"No function should be longer than what can be printed on a single sheet
of paper in a standard reference format with one line per statement
and one line per declaration. Typically, this means no more than about
60 lines of code per function."
See also: METRICS-01, METRICS-20, METRICS-21, METRICS-22

SINCE
v7.3

NOTES
The rule counts non-empty lines inside body of function.
Lines containing only comment are not counted.

BENEFITS
"Each function should be a logical unit in the code that is understandable
and verifiable as a unit. It is much harder to understand a logical unit
that
spans multiple screens on a computer display or multiple pages when
printed.
Excessively long functions are often a sign of poorly structured code."

EXAMPLE
void foo( int x )
// Violation
{
// ...
// more than 60 lines of constants, declarations, expressions,
// statements, types
// ...
}

REPAIR
Refactor long functions into several smaller functions.

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 4

The assertion density of the code should average to a minimum of two assertions per function
[METRICS-31-3]
DESCRIPTION
"The assertion density of the code should average to a minimum of two
assertions
per function. Assertions are used to check for anomalous conditions that
should
never happen in real-life executions."
The rule reports a violation if A < 2*F where A is the number of
assertions
and F is the number of defined functions.

SINCE
v7.3

NOTES
The rule detects all using of macros which names are ended by 'assert'
e.g. 'assert', 'c_assert', 'checkAssert' etc.
The rule checks one file at time.

BENEFITS
"Statistics for industrial coding efforts indicate that unit tests often
find at least one defect per 10 to 100 lines of code written. The odds
of intercepting defects increase with assertion density. Use of assertions
is often also recommended as part of a strong defensive coding strategy.
Assertions can be used to verify pre- and post-conditions of functions,
parameter values, return values of functions, and loop-invariants.
Because assertions are side-effect free, they can be selectively disabled
after testing in performance-critical code."

EXAMPLE
/* Violation - 2 functions defined and 1 assertion used */
#define c_assert(x) ((x) ? 1 : 0);

void foo(int x)
/* Some code
c_assert(x);
}
void bar(int x,
/* Some code
}
int baz();

{
*/
/* Use of assertion */
int y) {
*/

REPAIR
/* OK - 2 functions defined and 4 assertions used (density: 2) */
#define c_assert(x) ((x) ? 1 : 0);
void foo(int x) {
c_assert(x); /* Use of assertion */
/* Some code */
}
void bar(int x, int y) {
c_assert(x); /* Use of assertion */
c_assert(y); /* Use of assertion */
/* Some code */
c_assert(x+y); /* Use of assertion */
}
int baz();

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 5

All functions with more than 20 lines should contain at least 2 assertions [METRICS-32-3]
DESCRIPTION
The rule checks if a function that has more than M lines has at least
N assertions. M and N are parameters that could be set inside rule in
python method 'setValue'.
They are default set to:
MinimalNumberOfAssertions = 2
MinimalNumberOfFunctionLines = 20
In this case the rule reports a violation if a function that has more than
20
lines does not contain at least 2 assertions.
See also: METRICS-31

SINCE
v7.3

NOTES
As assertion the rule sees any use of macro with name that
ends with 'assert', e.g. 'assert', 'c_assert', 'checkAssert' etc.
The first line of function is a line containing opening brace '{'
and the last is line containing closing brace '}'. All lines are
counted, including empty and commented out.

BENEFITS
"Statistics for industrial coding efforts indicate that unit tests often
find at least one defect per 10 to 100 lines of code written. The odds
of intercepting defects increase with assertion density. Use of assertions
is often also recommended as part of a strong defensive coding strategy.
Assertions can be used to verify pre- and post-conditions of functions,
parameter values, return values of functions, and loop-invariants.
Because assertions are side-effect free, they can be selectively disabled
after testing in performance-critical code."

EXAMPLE

#define c_assert(x) ((x) ? 1 : 0);


void foo(int x, int y) { // Violation - 21 lines, 1 assertion used
/* Some code */
c_assert(x); /* Use of assertion */
/*
* code
*
*
*
*
*
*
*
*
*
* code
*
*
*
*
*/
}

REPAIR
#define c_assert(x) ((x) ? 1 : 0);
void foo(int x,
/* Some code
c_assert(x);
c_assert(x);
/*
* code
*
*
*
*
*
*
*
*

int y) { // OK - 21 lines, 2 assertion used


*/
/* Use of assertion */
/* Use of assertion */

* code
*
*
*
*
*/
}

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 5

Report Essential Complexity [METRICS-33-5]


DESCRIPTION
This rule reports the Essential Complexity value for each function.
The Essential Complexity metric quantifies the extent to which software is
unstructured.
The metric is calculated according to the formula:
EC = Number of unstructured decisions + 1
By decision we mean every occurrence of:
- 'if', 'for', 'while', 'do-while', 'case'
- conditional expression 'a?b:c' inside 'if', 'for', 'while', 'do-while'
condition
- logical operator '&&' and '||' inside 'if', 'for', 'while', 'do-while'
condition
By unstructured decisions we mean conditional jumps into or out of other
decisions, e.g.
'goto' inside 'if' which is in turn inside 'switch', or
'return' inside 'while' which is in turn inside 'for'.
If a decision contains unstructured decision then it's a unstructured
decision itself.
See also: METRICS-18, METRICS-28, METRICS-29, METRICS-34, METRICS-35

SINCE
v7.3

NOTES
Rule does not consider exception handling ('catch') as a decision.

BENEFITS
"Structured programming avoids unmaintainable "spaghetti code" by
restricting the usage
of control structures to those that are easily analyzed and decomposed."
By comparing Essential Complexity with Cyclomatic Complexity it's possible

to find
functions that are complicated but well structured, which means they can
be refactored.

EXAMPLE
void Example(int x, int y) /* Violation: Essential Complexity = 8
{
for(;x || y;) {
// +2
switch (x*y) {
case 1:
// +1
while (--x > 0) { // +1
if (x % y) {
// +1
return;
}
}
if (x > y) {
// +1
goto OUT;
}
break;
case 2:
// +1
do {
x++;
} while (x && y && (x * y < 100));
break;
}
OUT:
if (y) {
++y;
}
}
if (y) {
goto END;
}
END:
return;
}

REPAIR

*/

This rule is an informational rule and reports Essential Complexity


on each function implementation.

REFERENCES
1. A Complexity Measure
Thomas J. McCabe
308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. SE-2, NO.4, DECEMBER
1976
2. Structured Testing: A Testing Methodology Using the Cyclomatic
Complexity Metric
NIST Special Publication 500-235
Chapter 10 Essential Complexity
http://hissa.nist.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera.htm#446037

Follow the Essential Complexity limit of 4 [METRICS-34-5]


DESCRIPTION
This rule identifies methods that do not satisfy the user-defined
requirement
for Essential Complexity.
An error is reported if a function have the Essential Complexity higher
than 4.
The Essential Complexity metric quantifies the extent to which software is
unstructured.
The metric is calculated according to the formula:
EC = Number of unstructured decisions + 1
By decision we mean every occurrence of:
- 'if', 'for', 'while', 'do-while', 'case'
- conditional expression 'a?b:c' inside 'if', 'for', 'while', 'do-while'
condition
- logical operator '&&' and '||' inside 'if', 'for', 'while', 'do-while'
condition
By unstructured decisions we mean conditional jumps into or out of other
decisions, e.g.
'goto' inside 'if' which is in turn inside 'switch', or
'return' inside 'while' which is in turn inside 'for'.
If a decision contains unstructured decision then it's a unstructured
decision itself.
See also: METRICS-18, METRICS-28, METRICS-29, METRICS-33, METRICS-35

SINCE
v7.3

NOTES
Rule does not consider exception handling ('catch') as a decision.

BENEFITS
"Structured programming avoids unmaintainable "spaghetti code" by

restricting the usage


of control structures to those that are easily analyzed and decomposed."
By comparing Essential Complexity with Cyclomatic Complexity it's possible
to find
functions that are complicated but well structured, which means they can
be refactored.

EXAMPLE
void Example(int x, int y) /* Violation: Essential Complexity = 8
{
for(;x || y;) {
// +2
switch (x*y) {
case 1:
// +1
while (--x > 0) { // +1
if (x % y) {
// +1
return;
}
}
if (x > y) {
// +1
goto OUT;
}
break;
case 2:
// +1
do {
x++;
} while (x && y && (x * y < 100));
break;
}
OUT:
if (y) {
++y;
}
}
if (y) {
goto END;
}
END:
return;
}

*/

REPAIR
This rule is an informational rule and reports Essential Complexity
on each function implementation.

REFERENCES
1. A Complexity Measure
Thomas J. McCabe
308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. SE-2, NO.4, DECEMBER
1976
2. Structured Testing: A Testing Methodology Using the Cyclomatic
Complexity Metric
NIST Special Publication 500-235
Chapter 10 Essential Complexity
http://hissa.nist.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera.htm#446037

Follow the Essential Complexity limit of 10 [METRICS-35-5]


DESCRIPTION
This rule identifies methods that do not satisfy the user-defined
requirement
for Essential Complexity.
An error is reported if a function have the Essential Complexity higher
than 10.
The Essential Complexity metric quantifies the extent to which software is
unstructured.
The metric is calculated according to the formula:
EC = Number of unstructured decisions + 1
By decision we mean every occurrence of:
- 'if', 'for', 'while', 'do-while', 'case'
- conditional expression 'a?b:c' inside 'if', 'for', 'while', 'do-while'
condition
- logical operator '&&' and '||' inside 'if', 'for', 'while', 'do-while'
condition
By unstructured decisions we mean conditional jumps into or out of other
decisions, e.g.
'goto' inside 'if' which is in turn inside 'switch', or
'return' inside 'while' which is in turn inside 'for'.
If a decision contains unstructured decision then it's a unstructured
decision itself.
See also: METRICS-18, METRICS-28, METRICS-29, METRICS-33, METRICS-34

SINCE
v7.3

NOTES
Rule does not consider exception handling ('catch') as a decision.

BENEFITS
"Structured programming avoids unmaintainable "spaghetti code" by

restricting the usage


of control structures to those that are easily analyzed and decomposed."
By comparing Essential Complexity with Cyclomatic Complexity it's possible
to find
functions that are complicated but well structured, which means they can
be refactored.

EXAMPLE
void Example(int x, int y)
/* Violation: Essential Complexity = 12
{
for(;x || y;) {
// +2
switch (x*y) {
case 1:
// +1
for(;x && y && x < y;) {
// +3
while (--x > 0) {
// +1
if (y && x % y) {
// +2
return;
}
}
if (x > y) {
// +1
goto OUT;
}
}
break;
case 2:
// +1
do {
x++;
} while (x && y && (x * y < 100));
break;
}
OUT:
if (y) {
++y;
}
}
if (y) {
goto END;
}
END:
return;
}

*/

REPAIR
This rule is an informational rule and reports Essential Complexity
on each function implementation.

REFERENCES
1. A Complexity Measure
Thomas J. McCabe
308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. SE-2, NO.4, DECEMBER
1976
2. Structured Testing: A Testing Methodology Using the Cyclomatic
Complexity Metric
NIST Special Publication 500-235
Chapter 10 Essential Complexity
http://hissa.nist.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera.htm#446037

A function should not be called from more than 5 different functions [METRICS-36-3]
DESCRIPTION
A function should not be called from more than 5 different functions.
All calls within the same function are counted as 1.
The rule is limited to translation unit scope.

SINCE
v7.3

EXAMPLE
void foo(){} /* Violation */
void goo1(){
foo(); /* 1
}
void goo2(){
foo(); /* 2
}
void goo3(){
foo(); /* 3
}
void goo4(){
foo(); /* 4
}
void goo5(){
foo(); /* 5
}
void goo6(){
foo(); /* 6
}

*/

*/

*/

*/

*/

*/

REPAIR
void foo(){} /* OK */
void goo1(){
foo();

foo();
foo();
foo();
foo();
foo();
}

REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "CALLING"

A function should not call more than 7 different functions [METRICS-37-3]


DESCRIPTION
The rule reports a violation if a function contains more than 7 calls
of different functions. All calls of the same function are counted as 1.

SINCE
v7.3

EXAMPLE
void
void
void
void
void
void
void
void

goo1(){}
goo2(){}
goo3(){}
goo4(){}
goo5(){}
goo6(){}
goo7(){}
goo8(){}

void foo2()
{
goo1();
goo2();
goo3();
goo4();
goo5();
goo6();
goo7();
goo8();
}

REPAIR
void
void
void
void
void

goo1(){}
goo2(){}
goo3(){}
goo4(){}
goo5(){}

/* Violation */

void goo6(){}
void goo7(){}
void goo8(){}
void foo1()
{
goo1();
goo2();
goo3();
goo4();
}

/* OK */

void foo2()
{
foo1();
goo5();
goo6();
goo7();
goo8();
}

/* OK */

REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "CALLS"

The number of statements within function should be in range 1 - 50 [METRICS-38-3]


DESCRIPTION
The rule reports a violation if the number of statements in function body
is more than 50 or the function does not contain any statements.
Counted statements are: asm, break, continue, do...while, empty, for,
goto, if, return, switch, while and the top level expressions.

SINCE
v7.3

EXAMPLE
void foo(){} /* Violation */
void foo2(){} /* Violation */
int goo1(int i){ /* Violation
int e;
foo();
/*
foo2();
/*
if(i){
/*
i++;
/*
return i;
/*
}else{
i--;
/*
return 0;
/*
}
for(e = 0; e < 1; e++){ /*
while(i < 4)
/*
i = i + 4;
/*
}
switch (i){
/*
case 0:
i = 7;
/*
case 1:
i = 30;
/*
case 2:
i = 50;
/*
default:
return i;
/*

*/
1
2
3
4
5

*/
*/
*/
*/
*/

6 */
7 */
8 */
9 */
10 */
11 */
12 */
13 */
14 */
15 */

}
;
a:
foo();
foo2();
if(i){
i++;
return i;
}else{
i--;
return 0;
}
for(e = 0; e
while(i <
i = i
}
switch (i){
case 0:
i = 7;
case 1:
i = 30;
case 2:
i = 50;
default:
return i;
}
;
foo();
foo2();
for(e = 0; e
;
if(i){
i++;
return i;
}else{
i--;
i--;
i--;
return 0;
}
for(e = 0; e
while(i <
i = i
}

/* 16 */
/*
/*
/*
/*
/*

17
18
19
20
21

*/
*/
*/
*/
*/

/* 22 */
/* 23 */
< 1; e++){ /* 24 */
4)
/* 25 */
+ 4;
/* 26 */
/* 27 */
/* 28 */
/* 29 */
/* 30 */
/* 31 */

< 1; e++)

/*
/*
/*
/*
/*
/*
/*
/*

32
33
34
35
36
37
38
39

*/
*/
*/
*/
*/
*/
*/
*/

/*
/*
/*
/*

40
41
42
43

*/
*/
*/
*/

< 1; e++){ /* 44 */
4)
/* 45 */
+ 4;
/* 46 */

i = i + 5 + 4 * (2 / 3);
do{
i = (i < 4) ? 2 : 5;
}while(i < 5);
goto a;
return 10;

/* 47 */
/* 48 */
/* 49 */
/* 50 */
/* 51 */

REPAIR
The function should have at least 1 statement and the number of statements
within function body should be limited to 50.

REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "STMT"

The value of VOCF metric for a function should not be higher than 4 [METRICS-39-3]
DESCRIPTION
The rules checks the value of VOCF metric for a function.
Rule reports a violation if the value of VOCF metric
is higher than 4.
VOCF is
VOCF
where:
N1 N2 n1 n2 -

defined in the following way:


= (N1 + N2)/(n1 + n2)
the
the
the
the

number
number
number
number

of
of
of
of

all operators within function


all operands within function
distinct operators within function
distinct operands within function

Tokens recognized as operators:


- operators:
=, +=, -=, *=, /=, %=, |=, &=, ^=, <<=, >>=, +, -, *, /, %, |, &, ^,
<<, >>, ~, !, ||, &&, ++, --, <, <=, !=, ==, >, >=, ->, ?:, <%, <:,
(), [], {}, ,(comma), ;(semicolon), .(dot) , ...(ellipsis),
- keywords:
asm, auto, break, case, const, continue, default, do, else, enum, extern,
for, goto, if, inline, register, restrict, return, sizeof, static, struct,
switch, typedef, union, volatile, while
Tokens recognized as operands:
- all identifiers which are not keywords
- type specifiers: void, char, short, int, long, float, double, signed,
unsigned
- constants: numbers and strings

SINCE
v7.3

EXAMPLE
/* operators: brace{}(1), parentheses()(10), return(2), = (2), ;(6),
* + (8), * (5), if (2), >= (2),
* - N1 (38), n1 (9)
* operands: int(4), foo(1), i(9), a(3), b (3), 1 (2), 2 (6), 3 (3)

* - N2 (31), n2 (8)
* VOCF = (N1 + N2) / (n1 + n2) = (38 + 31) / (9 + 8) = 4.06 */
int foo(int i){
int a;
int b;

/* Violation */

a = i + (2 * (i + 1)) + (3 * (i + 2));
b = (i + (2 * (i + 1)) + (3 * (i + 2))) * 2;
if(i >= 3)
return a;
if(i >= 2)
return b;
}

REPAIR
/* operators: brace{}(1), parentheses()(5), return(2), = (2), ;(6),
* + (4), * (3), if (2), >= (2),
* - N1 (27), n1 (9)
* operands: int(4), foo(1), i(6), a(4), b (3), 1 (1), 2 (4), 3 (2)
* - N2 (25), n2 (8)
* VOCF = (N1 + N2) / (n1 + n2) = (27 + 25) / (9 + 8) = 3.06 */
int foo1(int i){
int a;
int b;

/* OK */

a = i + (2 * (i + 1)) + (3 * (i + 2));
b = a * 2;
if(i >= 3)
return a;
if(i >= 2)
return b;
}

REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "VOCF"

Statements within function should not be nested deeper than 4 levels [METRICS-40-3]
DESCRIPTION
Statements should not be nested deeper than 4 levels.
The rule as a level detects a block of code enclosed with curly braces
'{}'

SINCE
v7.3

BENEFITS
Rule improves easier code understanding, and maintain, and often
needlessly so.

EXAMPLE
int foo2( int x ) {
/* level-0 */
if (x > 0) {
/* level-1 */
if (x > 1) {
/* level-2 */
if (x > 2) {
/* level-3 */
if (x > 3) {
/* level-4 */
if (x > 4) {
starts */
/* level-5 */
if (x > 5) {
higher level */
/* level-6 */
return x;
}
}
}
}
}
}
}

/*
/*
/*
/*
/*

OK */
OK */
OK */
OK */
Violation - level 5

/* OK - Violation on

REPAIR
Do not use excessive block nesting depth (more than 4 levels)

REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "LEVEL"

The number of blocks of comments before and inside function to the number of statements in
function should be > 0.2 [METRICS-41-3]
DESCRIPTION
The rule reports a violation if the number of blocks of comments in
function
body (BCOM) and before function (BCOB) to number of statements in function
(STMT) is not higher than 0.2
(BCOM + BCOB)/STMT <= 0.2 /* Violation */
Counted statements are: asm, break, continue, do...while, empty, for,
goto,
if, return, switch, while and the top level expressions.

SINCE
v7.3

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
/* 1 block */
/* 1 block */
int comm /* Violation - function 'comm' contains 20 statements
and 4 blocks of comments - COMF = 0.2
2 block */
(
unsigned short s
)
{
int i;
if (s > 0)
i = 3;
else
i = 4;
if (s > 0)

i = 3;
else
i = 4;
if (s > 0)
i = 3;
else
/* 3 block */
i = 4;
if (s > 0)
i = 3;
else
i = 4;
if (s > 0)
i = 3;
else
i = 4;
/* 4 block */
if (s > 0){
i = 3;
i = 5;
}
else
i = 4;
return i;
}

REPAIR
/* 1 block */
/* 1 block */
int comm1 /* OK - function 'comm' contains 20 statements
and 10 blocks of comments - COMF = 0.5
2 block */
(
unsigned short s /* 3 block */
/* 4 block */
)
{
int i;
if (s > 0)
i = 3;
else
i = 4;

if (s > 0)
i = 3;
else
i = 4;
if (s > 0)
i = 3;
/* 5 block */
/* 6 block */
else
/* 7 block */
i = 4;
if (s > 0)
/* 8 block */
/* 8 block */
/* 8 block */ i = 3;
else
i = 4;
if (s > 0)
i = 3;
/* 9 block */
else
i = 4;
if (s > 0){
i = 3;
i = 5;
}
else
i = 4;
return i;
}/* 10 block */

REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "COMF"

Follow the limit for Coupling Between Objects [METRICS-CBO-1]


DESCRIPTION
Number of classes to which a class is coupled
A class is coupled to another class when it calls methods or uses
variables
declared by the other class. Only method calls and variable references are
counted. Other types of uses (for example simply declaring variable of the
other class, or using typedef declared in the other class) does not count
as
coupling.
High coupling between object classes means modules depend on each other
too
much and will be hard to reuse. The more independent a class is, the
easier
it is to reuse it in another application. In order to improve modularity
and
promote reuse, inter-object class couples should be kept to a minimum.
The larger the number of couples, the higher the sensitivity to changes in
other parts of the design, and therefore maintenance is more difficult.
When computing CBO value for a class, only defined methods are taken into
account.
SINCE
v9.2
EXAMPLE
class A { // CBO = 0
public:
void foo() {}
int x;
};
class B : public A { // CBO = 0
public:
void bar1() {
foo(); // class is not coupled to it's parents
}
int bar2() {
x = 0; // class is not coupled to it's parents
return y;

}
int y;
};
class C { // CBO = 2
public:
int bar(A a) {
B b;
a.foo(); // coupling to A
a.x = 0; // coupling to A
return b.bar2(); // coupling to B
}
};
REFERENCES
1. Shyam R. Chidamber, Chris F. Kemerer
A Metrics Suite for Object Oriented Design
IEEE Transactions on Software Engineering, Vol 20., No. 6, June 1994

Follow the limit for Inheritance Depth [METRICS-ID-5]


DESCRIPTION
The ordinal distance from the class to the root of the inheritance tree.
In cases involving multiple inheritance, the maximum length from to class
to
the root of the tree is taken into account.
The deeper a class is in the hierarchy, the greater
and
state variables it is likely to inherit, which make
predict its behavior. If there are a majority of ID
represent poor exploitation of the advantages of OO
inheritance.

the number of methods


it more difficult to
values below 2, it may
design and

Industry standards recommend a maximum ID value of 5 since deeper trees


constitute greater design complexity as more methods and classes are
involved.
It is often difficult to understand a system with many inheritance layers,
however, there is a greater potential reuse of tested inherited methods.
SINCE
v9.2
EXAMPLE
class A { // ID = 0
};
class B : public A { // ID = 1
};
class C : public B { // ID = 2
};
class D { // ID = 0
};
class E : public C, public D { // ID = 3
};
REFERENCES
1. Shyam R. Chidamber, Chris F. Kemerer
A Metrics Suite for Object Oriented Design
IEEE Transactions on Software Engineering, Vol 20., No. 6, June 1994

Follow the limit for Lack Of Cohesion [METRICS-LCOM-1]


DESCRIPTION
LCOM = (avg(m(a)) - m)/(1-m)
m - number of methods which use at least one field
m(a) - number of methods which use field "a"
avg(m(a)) - average number of methods which use field a
(computed over all fields which are used by at least one method)
In other words: avg(m(a)) = (m(a1) + m(a2) + ... + m(an)) / n
Metric calculates Lack of Cohesion in Methods (Henderson-Sellers "LCOM3"
or
"LCOM*" variant). Only fields which are accessed by at least one method,
and methods which access at least one field are included in the count.
Cohesion is a measure of relatedness in a class. If a class has low
cohesion
it may perform various tasks which have little relation to one another.
These classes may be candidates for refactoring into separate, more
targeted,
classes.
LCOM can take values between 0 and 1, where 0 means class is cohesive
(lack of
cohesion is at minimum), and 1 means class is not cohesive (lack of
cohesion is
at maximum). Value 0 means that every field is used by every method (class
is
cohesive - all methods work on the same set of fields and perform common
task),
and 1 means that every field is used by only 1 method (class is not
cohesive every method has it's own field and performs it's own task separated from
other
methods/tasks).
When computing LCOM value for a class, only defined methods are taken into
account.
SINCE
v9.2
EXAMPLE

class A { // LCOM = 0
void foo1() {
x = 0;
y = 0;
}
void foo2() {
x = y;
}
int x;
int y;
};
class B { // LCOM = 1
void foo1() {
x = 0;
}
void foo2() {
y = 0;
}
int x;
int y;
};
class C { // LCOM = 0.5
void foo1() {
x = 0;
}
void foo2() {
y = x;
}
int x;
int y;
};
REPAIR
Consider splitting classes into separate, more targetted, classes.
For example:
class B1 { // LCOM = 0
void foo1() {
x = 0;
}
int x;
};

class B2 { // LCOM = 0
void foo2() {
y = 0;
}
int y;
};
REFERENCES
1. Henderson-Sellers, B.
Object-oriented metrics: measures of complexity
Prentice-Hall, pp.142-147, 1996.
2. Lack of Cohesion in Methods
http://eclipsemetrics.sourceforge.net/descriptions/pages/cohesion/LackOfCohesionInMethod
s.html

Follow the limit for Number Of Constructors [METRICS-NOCT-3]


DESCRIPTION
Number of constructors declared explicitly in a class.
SINCE
v9.2
EXAMPLE
class A { // NOCT = 0
};
class B { // NOCT = 1
public:
B();
};
class C { // NOCT = 4
public:
C();
C(int i);
C(float f);
C(const C& o);
};

Follow the limit for Number Of Instance Fields [METRICS-NOF-4]


DESCRIPTION
Number of non-static fields in a type.
SINCE
v9.2
EXAMPLE
class A { // NOF = 1
public:
static int I;
private:
int _i;
};
class B { // NOF = 3
public:
int i;
float f;
long l;
};
struct C { // NOF = 2
int i;
float f;
};

Follow the limit for Number Of Fields [METRICS-NOFT-2]


DESCRIPTION
Number of fields in a type.
This includes both instance and static fields declared in a type.
SINCE
v9.2
EXAMPLE
class A { // NOFT = 2
public:
static int I;
private:
int _i;
};
struct B { // NOFT = 3
int i;
float f;
long l;
};
union C { // NOFT = 2
int i;
float f;
};

Follow the limit for Number Of Instance Methods [METRICS-NOM-4]


DESCRIPTION
Number of non-static methods (including constructors and destructors)
declared explicitly in a class.
SINCE
v9.2
EXAMPLE
class A { // NOM = 1
public:
void foo();
static void bar();
};
class B { // NOM = 4
public:
B();
void foo();
~B();
private:
void bar();
};
class C { // NOM = 0
public:
static void foo();
};

Follow the limit for Number Of Methods [METRICS-NOO-4]


DESCRIPTION
Number of methods declared explicitly in a class.
This includes both instance and static methods declared in a class.
SINCE
v9.2
EXAMPLE
class A { // NOO = 2
public:
void foo();
static void bar();
};
class B { // NOO = 4
public:
B();
void foo();
~B();
private:
void bar();
};
class C { // NOO = 1
public:
static void foo();
};

Follow the limit for Number Of "private" Fields [METRICS-NPRIF-2]


DESCRIPTION
Number of private fields in a type.
This includes both instance and static fields declared in a type.
SINCE
v9.2
EXAMPLE
class A { // NPRIF = 1
public:
static int I;
private:
int _i;
};
class B { // NPRIF = 3
private:
int _i;
static float _F;
static long _L;
};
class C { // NPRIF = 0
};

Follow the limit for Number Of "private" Methods [METRICS-NPRIM-2]


DESCRIPTION
Number of private methods in a class.
This includes both instance and static methods declared in a class.
SINCE
v9.2
EXAMPLE
class A { // NPRIM = 1
public:
static int foo();
private:
int bar();
};
class B { // NPRIM = 3
private:
void foo();
static float bar();
static void foo(int i);
};
class C { // NPRIM = 0
};

Follow the limit for Number Of "protected" Fields [METRICS-NPROF-2]


DESCRIPTION
Number of protected fields in a type.
This includes both instance and static fields declared in a type.
SINCE
v9.2
EXAMPLE
class A { // NPROF = 1
public:
static int I;
protected:
int _i;
};
class B { // NPROF = 3
protected:
int _i;
static float _F;
static long _L;
};
class C { // NPROF = 0
};

Follow the limit for Number Of "protected" Methods [METRICS-NPROM-2]


DESCRIPTION
Number of protected methods in a class.
This includes both instance and static methods declared in a class.
SINCE
v9.2
EXAMPLE
class A { // NPROM = 1
public:
static int foo();
protected:
int bar();
};
class B { // NPROM = 3
protected:
void foo();
static float bar();
static void foo(int i);
};
class C { // NPROM = 0
};

Follow the limit for Number Of "public" Fields [METRICS-NPUBF-2]


DESCRIPTION
Number of public fields in a type.
This includes both instance and static fields declared in a type.
SINCE
v9.2
EXAMPLE
class A { // NPUBF = 1
public:
static int I;
private:
int _i;
};
class B { // NPUBF = 3
public:
int _i;
static float _F;
static long _L;
};
class C { // NPUBF = 0
};

Follow the limit for Number Of "public" Methods [METRICS-NPUBM-2]


DESCRIPTION
Number of public methods in a class.
This includes both instance and static methods declared in a class.
SINCE
v9.2
EXAMPLE
class A { // NPUBM = 1
public:
static int foo();
protected:
int bar();
};
class B { // NPUBM = 3
public:
void foo();
static float bar();
static void foo(int i);
};
class C { // NPUBM = 0
};

Follow the limit for Number Of Static Fields [METRICS-NSF-3]


DESCRIPTION
Number of static fields in a type.
SINCE
v9.2
EXAMPLE
class A { // NSF = 1
public:
static int I;
private:
int _i;
};
class B {
public:
static
static
static
};

// NSF = 3
int I;
float F;
long L;

struct C { // NSF = 0
int i;
float f;
};

Follow the limit for Number Of Static Methods [METRICS-NSM-3]


DESCRIPTION
Number of static methods in a class.
SINCE
v9.2
EXAMPLE
class A { // NSM = 1
public:
static int foo();
private:
int bar();
};
class B {
public:
static
static
static
};

// NSM = 3
int foo();
float bar();
long foo(int i);

class C { // NSM = 0
};

MISRA
MISRA C
RULES
Provisions should be made for appropriate run-time checking [MISRA-004_a5]
Provisions should be made for appropriate run-time checking [MISRA-004_b5]
Only use characters defined in ISO C standard [MISRA-005-3]
Values of character types shall be restricted to a defined and documented
subset of ISO 10646-1 [MISRA-006-3]
Do not use wide string literals [MISRA-008-3]
The basic types of char, int, short, long, float and double should not be
used, but specific-length equivalents should be typedef'd [MISRA-013-3]
Explicitly declare 'char' type as signed or unsigned [MISRA-014-3]
The underlying bit representations of floating point numbers shall not be
used [MISRA-016-3]
Use type suffix for numeric constants [MISRA-018_a-5]
Use type suffix for numeric constants [MISRA-018_b-5]
Use type suffix for numeric constants [MISRA-018_c-5]
Use type suffix for numeric constants [MISRA-018_d-5]
All functions shall be declared before use [MISRA-020-3]
Declare objects at function scope [MISRA-022-5]
Make declarations at file scope static where possible [MISRA-023-5]
Use consistent linkage for identifiers [MISRA-024-3]
External object should not be declared in more than one file [MISRA-027-3]
Do not use register storage class [MISRA-028-5]
The use of a tag shall agree with its declaration [MISRA-029-3]
All automatic variables shall have been assigned a value before being used
[MISRA-030-3]
Invalid range of the right hand operand of a shift operator [MISRA-038-3]
Document integer division [MISRA-041-5]
The comma operator shall not be used, except in the control expression of
a for loop [MISRA-042-3]
Implicit conversions which may result in a loss of information shall not
be used [MISRA-043-3]
Avoid mixing arithmetic of different precisions in the same expression
[MISRA-043_b-3]
Redundant explicit cast to the same type is not allowed [MISRA-044-3]
Do not use the volatile keyword [MISRA-046_a-3]
Evaluation order of an expression is implementation dependent [MISRA046_c-3]
Evaluation order of an expression is implementation dependent [MISRA046_d-3]

Use explicit casts in mixed precision arithmetic [MISRA-048_a-5]


Use explicit casts in mixed precision arithmetic [MISRA-048_b-5]
Use explicit casts in mixed precision arithmetic [MISRA-048_c-5]
Use explicit casts in mixed precision arithmetic [MISRA-048_d-5]
Use explicit type conversions for arithmetic using signed and unsigned
values [MISRA-048_e-3]
Evaluation of constant unsigned integer expressions should not lead to
wrap-around [MISRA-051-5]
A null statement shall only occur on a line by itself, and shall not have
any other text on the same line [MISRA-054-3]
Do not use labels [MISRA-055-5]
Do not use the break statement [MISRA-058-3]
Do not use floating point variables as loop counters [MISRA-065-3]
Do not use functions with variable numbers of arguments [MISRA-069-3]
Functions shall always have visible prototype at both the function
definition and call [MISRA-071-3]
Provide none or all identifiers for function arguments [MISRA-073-3]
Provide expression for return statement of non-void functions [MISRA-0833]
Avoid expressions in return statements of void functions [MISRA-084-3]
Use empty parentheses when calling function with no arguments [MISRA-0855]
#include directive must be followed by a filename in double-quotes or
angle brackets [MISRA-089-3]
Enclose in parentheses whole definition of a function-like macro [MISRA096-3]
Use only non-ambiguous forms of defined pre-processor operator [MISRA-1003]
Avoid pointer arithmetic [MISRA-101-5]
Do not use non-constant pointers to functions [MISRA-104-3]
All the functions pointed to by a single pointer to function shall be
identical in the number and type of parameters and the return type [MISRA105-3]
The NULL pointer shall not be dereferenced [MISRA-107_a-3]
The NULL pointer shall not be dereferenced [MISRA-107_b-3]
All members of structure or union should be fully specified [MISRA-108-3]
Unions shall not be used to access the sub-parts of larger data structure
[MISRA-110-3]
All the members of a structure (or union) shall be named [MISRA-113-3]
Standard library function names shall not be reused [MISRA-115-3]
Do not use locale.h header and setlocale function [MISRA-121_a-3]
Do not use locale.h header and setlocale function [MISRA-121_b-3]

Provisions should be made for appropriate run-time checking [MISRA-004_a-5]


DESCRIPTION
Ensure that array indices are within the bounds of the array size before
using them to index the array.

BENEFITS
This rule prevents from getting/putting values which are out of range.

EXAMPLE
void foo()
{
int j;
int k[10];
int m;
m = k[j]; /* Violation */
}

REPAIR
void moo()
{
int j;
int k[10];
int m;
if ((j < 10) && (j >= 0)) /* OK */
{
m = k[j];
}
}

REFERENCES
Origin: Misra Guidelines - Rule 4

Provisions should be made for appropriate run-time checking [MISRA-004_b-5]


DESCRIPTION
Left shifting of an integer may cause the most significant bit(s)
to be lost, effectively a kind of overflow.

BENEFITS
Prevents from overflow.

EXAMPLE
void main()
{
int i = 4;
int j = 2;
int k = j << i;
}

/* Violation */

REPAIR
Do not use left shifting of an integer.

REFERENCES
Origin: Misra Guidelines - Rule 4

Only use characters defined in ISO C standard [MISRA-005-3]


DESCRIPTION
Only those characters and escape sequences which are
defined in the ISO C standard shall be used.
Section 5.2.1 of the ISO C standards defines 91 characters
which are the minimum source character set for all
compilers. These are the only characters that should be
used, even if the compiler supports a larger character set,
or supports alternative character sets.
Those
- the
A B C
N O P

characters are:
26 uppercase letters of the Latin alphabet
D E F G H I J K L M
Q R S T U V W X Y Z

- the 26 lowercase letters of the Latin alphabet


a b c d e f g h i j k l m
n o p q r s t u v w x y z
- the 10 decimal digits
0 1 2 3 4 5 6 7 8 9
- the following 29 graphic characters
_{}[]#()<>%:;.?*+-/^&|~!=,\"'
- the space character, and control characters representing
horizontal tab, vertical tab, form feed and new line.

BENEFITS
Minimal required character set.

EXAMPLE
void foo() {
char c1 = '$';
char c2 = '`';
}

/* Violation */
/* Violation */

REPAIR
Do not use characters no defined in the ISO C standard.

REFERENCES
1. Origin: Misra Guidelines - Rule 5
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 9

Values of character types shall be restricted to a defined and documented subset of ISO
10646-1 [MISRA-006-3]
DESCRIPTION
"The chosen implementation of C shall conform to a subset of
ISO 10646-1, and the chosen subset shall be documented."
Explicitly specified numeric value of character may not conform to
chosen subset of ISO 10646-1.

BENEFITS
Values of character types are defined and documented as subset of ISO
10646-1.

EXAMPLE
void foo()
{
const char * s[] = {"a",
"\012" /* Violation */
};
}

REPAIR
Define character types as subset of ISO 10646-1.

REFERENCES
1. Origin: Misra Guidelines - Rule 006
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 10

Do not use wide string literals [MISRA-008-3]


DESCRIPTION
Wide string literals shall not be used.

BENEFITS
Prevents from various undefined and implementation-defined behaviours
associated with
them and they shall not be used.

EXAMPLE
#include <stddef.h>
void foo() {
wchar_t* x = L"Fred";/* Violation */
}

REPAIR
#include <stddef.h>
void foo() {
char* x = "Fred";/* OK */
}

REFERENCES
1. Origin: Misra Guidelines - Rule 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 13

The basic types of char, int, short, long, float and double should not be used, but specificlength equivalents should be typedef'd [MISRA-013-3]
DESCRIPTION
"The storage length of types can vary from compiler to compiler. It is
safer
if programmers work with types which they know to be of a given length."
Rule reports a violation message if basic numerical type is used
(e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA2004-6_3

EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)

BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."

EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
char* p_char,
float& r_float)
{
double h;
const int z = 1;
return 1;

/* Violation (for return type) */


/* Violation */
/* Violation */
/* Violation */
/* Violation */

REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}

/* OK (plain char) */
/* OK (typedef name starts with 'bool'

/* OK (bit-bield type) */
/*
/*
/*
/*

OK
OK
OK
OK

(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */

/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */

REFERENCES
1. Misra Guidelines - Rule 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-9-2

Explicitly declare 'char' type as signed or unsigned [MISRA-014-3]


DESCRIPTION
"The type 'char'
depending
on the compiler.
it is preferable
required
use of 'char' is

may be implemented as a signed or an unsigned type


Rather than making any assumptions about the compiler,
(and more portable) to always specify whether the
signed or unsigned."

NOTES
If a type of variable is a typedef to char, then a violation is reported
only
on a typedef declaration.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
typedef char CHAR; // Violation
char foo(char)
{
char var1;
CHAR var2;
}

// Violation x 2
// Violation
// OK - Violation is reported on a typedef declaration

char (*fptr1)();
void (*fptr2)(char);

// Violation
// Violation

REPAIR
typedef unsigned char CHAR;

// OK

unsigned char foo(unsigned char) // OK


{

unsigned char var1;


CHAR var2;

// OK
// OK

}
unsigned char (*fptr1)();
void (*fptr2)(unsigned char);

// OK
// OK

REFERENCES
1. Origin: Misra Guidelines - Rule 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 4

The underlying bit representations of floating point numbers shall not be used [MISRA-016-3]
DESCRIPTION
The underlying bit representations of floating point numbers shall not be
used
in any way by the programmer.

BENEFITS
Prevents from casting with possible data losing.

EXAMPLE
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
long * pl;
pi
pi
ps
pl

=
=
=
=

(int*)pf;
(int*)pd;
(short*)pf;
(long*)pf;

/*
/*
/*
/*

Violation
Violation
Violation
Violation

REPAIR
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
pf = (float*)pd;
ps = (short*)pi;
}

/* OK */
/* OK */

*/
*/
*/
*/

REFERENCES
1. Origin: Misra Guidelines - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.17 Types, AV Rule 147

Use type suffix for numeric constants [MISRA-018_a-5]


DESCRIPTION
Numeric constants should be suffixed to indicate type,
where an appropriate suffix is available.
Rule checks only value between 65536 and 2147483647.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
unsigned long lVar = 65537; /* Violation */

REPAIR
unsigned long lVar = 65537L; /* OK */

REFERENCES
Origin: Misra Guidelines - Rule 18

Use type suffix for numeric constants [MISRA-018_b-5]


DESCRIPTION
Numeric constants should be suffixed to indicate type,
where an appropriate suffix is available.
Rule checks only value between 65536 and 2147483647.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
unsigned long arrL[] = {
0,
1,
32767,
32768,
65535,
65536, /* Violation */
2147483547,/* Violation */
2147483648,
4294967295
};

REPAIR
unsigned long arrL[] = {
0,/* OK */
1, /* OK */
32767, /* OK */
32768, /* OK */
65535,/* OK */
65536L, /* OK */
2147483547L,/* OK */
2147483648,/* OK */
4294967295/* OK */
};

REFERENCES
Origin: Misra Guidelines - Rule 18

Use type suffix for numeric constants [MISRA-018_c-5]


DESCRIPTION
Numeric constants should be suffixed to indicate type,
where an appropriate suffix is available.
Rule checks only value between 32768 and 65535.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
unsigned long lVar = 32768; /* Violation */

REPAIR
unsigned long lVar = 32768U; /* OK */
unsigned long lVar3 = 32767; /* OK */
unsigned long lVar4 = 65536; /* OK */

REFERENCES
Origin: Misra Guidelines - Rule 18

Use type suffix for numeric constants [MISRA-018_d-5]


DESCRIPTION
Numeric constants should be suffixed to indicate type,
where an appropriate suffix is available.
Rule checks only value between 32768 and 65535.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
unsigned long arrL[] = {
0,
1,
32767,
32768, /* Violation */
65535, /* Violation */
65536,
2147483547,
2147483648,
4294967295
};

REPAIR
unsigned long arrL[] = {
0,/* OK */
1, /* OK */
32767, /* OK */
32768U, /* OK */
65535U,/* OK */
65536, /* OK */
2147483547,/* OK */
2147483648,/* OK */
4294967295/* OK */
};

REFERENCES
Origin: Misra Guidelines - Rule 18

All functions shall be declared before use [MISRA-020-3]


DESCRIPTION
Rule requires that all functions must be declared before they are used.
A declaration provides information to the compiler about the type of
function.
If undeclared function is found, the compiler will have to make
assumptions
about the function prototype, and will not verify if actual parameter
types
match types specified in function declaration. This may lead to undefined
behavior, which can result in hard-to-find errors at runtime.

NOTES
This rule active for C code only.

BENEFITS
The rule prevents undefined behaviours.

EXAMPLE
void goo()
{
foo1();
foo2();
}
void foo2();

/* Violation - function undeclared */


/* Violation - function declared after use */

REPAIR
//--------file.h----------------void foo1_h();
void foo2_h(){}
//--------file.c----------------#include "file.h"
void foo1();

void foo2(){}
void goo()
{
foo1();
foo2();
foo1();
foo2();
}

/*
/*
/*
/*

OK
OK
OK
OK

function
function
function
function

declared before use */


defined before use */
declared in header */
defined in header */

REFERENCES
1. Misra Guidelines - Rule 20
2. Multiplatform Porting to 64 Bits
http://www.ddj.com/showArticle.jhtml;jsessionid=GJEIYBMN14LMIQSNDBCSKHSCJU
MEKJVN?articleID=184406427

Declare objects at function scope [MISRA-022-5]


DESCRIPTION
Declarations of objects should be at function scope
unless a wider scope is necessary.

BENEFITS
Prevents using global variables.

EXAMPLE
int globalVar;

// Violation

REPAIR
void foo( ) {
int localVar;
}

// OK

REFERENCES
1. Misra Guidelines - Rule 22
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 57
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 136
4. ISO/DIS 26262
point 8.4.4

Make declarations at file scope static where possible [MISRA-023-5]


DESCRIPTION
All declarations at file scope should be static where possible.

BENEFITS
Prevents from accidentally overwriting of functions or variables

EXAMPLE
int g1; /* Violation */
void foo1() {}; /* Violation */

REPAIR
static int g2; /* OK */
static void foo2(){}; /* OK */

REFERENCES
1. Origin: Misra Guidelines - Rule 23
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 137

Use consistent linkage for identifiers [MISRA-024-3]


DESCRIPTION
Identifiers shall not simultaneously have both internal and external
linkage in the same translation unit.

BENEFITS
Rule prevents variable-name hiding which can be confusing.

EXAMPLE
static unsigned short x;
static unsigned short y;
void foo( ) {
extern unsigned short x;
// Violation
extern unsigned short y;
// Violation
{
extern unsigned short y; // Violation
}
}

REPAIR
Do not declare variables simultaneously with internal and external
linkage in the same translation unit.

REFERENCES
1. Origin:

Misra Guidelines - Rule 24

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.15 Declarations and Definitions, AV Rule 138

External object should not be declared in more than one file [MISRA-027-3]
DESCRIPTION
External objects should be declared in header files which are then
included in all
those source files which use these objects. This rule will inform about
multiple
declarations of symbols.

BENEFITS
Rule improves readability, clarity of code and prevents errorneous code.

EXAMPLE
/* misra_027.h */
/* Do not declare external object in more than one file. */
extern int a;
/* Violation */
/* misra_027.c */
#include "misra_027.h"
extern int a;

REPAIR
/* misra_027.h */
extern int a;

/* OK */

/* misra_027.c */
#include "misra_027.h"
int a;

REFERENCES
1. Origin: Misra Guidelines - Rule 27
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 139

Do not use register storage class [MISRA-028-5]


DESCRIPTION
The register storage class specifier shall not be used.

BENEFITS
Prevents from dependencies on compiler.

EXAMPLE
void foo()
{
register int a;
}

// Violation

REPAIR
Do not use the 'register' storage class specifier.

REFERENCES
1. Origin:

Misra Guidelines - Rule 28

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.15 Declarations and Definitions, AV Rule 140

The use of a tag shall agree with its declaration [MISRA-029-3]


DESCRIPTION
The use of a tag shall agree with its declaration.
This rule will report violation when tag initializers do not agree with
the structure declared for that tag.
This rule is active for C code only.

BENEFITS
Rule improves readability, clarity of code and prevents error prone code.

EXAMPLE
struct tagSTRUCT {
int _x;
};
struct tagSTRUCT t = { "abc" }; /* Violation - 'char *' initialiser does
not match type of field _x: */

REPAIR
struct tagSTRUCT {
int _x;
};
struct tagSTRUCT s = { 123 }; /* OK - initialiser of type int matches type
of field _x: */

REFERENCES
Origin: Misra Guidelines - Rule 29

All automatic variables shall have been assigned a value before being used [MISRA-030-3]
DESCRIPTION
"The intent of this rule is that all variables shall have been written to
before
they are read. This does not necessarily require initialisation at
declaration.
Ideally a static check should be performed for any automatic variables
which
might be used without having first been assigned a value"
See also: INIT-06, INIT-10, INIT-14, BD-PB-NOTINIT

NOTES
The rule assumes that local variable might be initialized
by passing its non-const pointer to an external function.

BENEFITS
Prevents reading from uninitialized variables.

EXAMPLE
void foo( ) {
int b;
b++;
}

// Violation

REPAIR
void foo( ) {
int b = 0;
b++;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve

Your Programs and Design", Third Edition, Addison-Wesley,


(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. Misra Guidelines - Rule 30
3. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9, rule 9.1
4. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 40
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 142
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-1

Invalid range of the right hand operand of a shift operator [MISRA-038-3]


DESCRIPTION
The right hand operand of a shift operator shall lie between zero
and one less than the width in bits of the left hand operand (inclusive).
Rule makes assumptions about size of types: char has 8 bits, short has 16
bit,
int has 32 bit, long has 64 bit.

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
#ifndef uint8_t
typedef unsigned char
#endif
#ifndef uint16_t
typedef unsigned short
#endif
#ifndef uint32_t
typedef unsigned int
#endif
void foo( )
uint8_t
uint16_t
uint32_t
it8
it16
it32
it16

<<
<<
>>
>>

uint8_t;

uint16_t;

uint32_t;

{
it8;
it16;
it32;
8; //
16; //
32; //
it8;//

Violation
Violation
Violation
Violation

REPAIR
#ifndef uint8_t
typedef unsigned char

uint8_t;

#endif
#ifndef uint16_t
typedef unsigned short
#endif
#ifndef uint32_t
typedef unsigned int
#endif
void foo( )
uint8_t
uint16_t
uint32_t

uint16_t;

uint32_t;

{
it8;
it16;
it32;

it8 << 7;
it16 << 15;
it32 >> 31;
if (it8 > 0
it16 >>

// OK
// OK
// OK
&& it8 < sizeof( it8 ))
it8; // OK

REFERENCES
Origin: Misra Guidelines - Rule 38

Document integer division [MISRA-041-5]


DESCRIPTION
The implementation of integer division in the
chosen compiler should be determined,
documented and taken into account.
This rule checks that, wherever there is an integer division
in the code, there must be comment on the previous line.

BENEFITS
Prevents unexpected loss of data/precision.

EXAMPLE
void foo()
{
int i=2;
int j=3;
int k;
k=j/i;

/* Violation - no comment before division*/

REPAIR
void boo()
{
int i=2;
int j=3;
int k;
/*

OK - comment before integer division */


k=i/j;

REFERENCES
1. Origin: Misra Guidelines - Rule 41

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.21 Operators, AV Rule 167

The comma operator shall not be used, except in the control expression of a for loop [MISRA042-3]
DESCRIPTION
"Use of the comma operator in situations other than the control
expression
of a loop is generally detrimental to the readability of code, and the
same
effect can be achieved by other means"
See also: misra2004-12_10

BENEFITS
Extensive use of comma operator reduces readability.

EXAMPLE
void foo1( int x, int y )
{
int i;
i = (x = 1, y = 0);
x++, y++;
for (i = 0; i < 10; i++){
foo1( (x--, y + 2), y );
}
}

// Violation
// Violation
// Violation

REPAIR
void foo2( int x, int y ) {
int i;
x++;
y++;
for (i = 0; i >=0, i < 10; i++){
}
x--;
foo2( y + 2, y );
}

// OK
// OK

// OK

REFERENCES
1. Origin: Misra Guidelines - Rule 42
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 168

Implicit conversions which may result in a loss of information shall not be used [MISRA-043-3]
DESCRIPTION
"C performs many type conversions implicitly and silently, so as to
harmonize
types within an expression before evaluating it. Some of these conversions
can
result in loss of information. Such implicit conversions shall not be
used,
but explicit casts should be used instead."
The rule reports a violation if a parameter/variable/expression of
integral
or floating type is implicitly cast to a narrower type.
See also: MISRA2004-10_1_b, MISRA2004-10_2, PORT-27, PORT-28

NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
float < double < long double
The rule assumes that the size of enumeration type is the same as int
type.

EXCEPTIONS
The rule does not report violation if a conversion is used:
- on a constant expression
- between integral and floating type
- between signed and unsigned type
- on a bit field

BENEFITS
"Explicit casts should normally only be used in the case where a
conversion
which could result in a loss of information is specifically required by
the
programmer. If the static checking of implicit conversions is overridden
by
the use of explicit casts in this way, then the programmer should be aware

of the issues of truncation and lost of precision associated with the


operation,
and should provide appropriate checking of values in the code"

EXAMPLE
void bar(unsigned char c);
void foo(unsigned int ui, double d)
{
float f;
unsigned short us1;
unsigned short us2 = ui; /* Violation
us1 = us2 + us2;
/* Violation
f = d;
/* Violation
bar(ui);
/* Violation
}

*/
- due to integral promotion */
*/
*/

REPAIR

void bar(unsigned char c);


void foo(unsigned int ui, double d)
{
float f;
unsigned short us = (unsigned short)ui; /* OK */
f = (float)d;
/* OK */
bar((unsigned char)ui);
/* OK */
}
/* exceptions */
void except(unsigned int ui){
unsigned char uc = 300;
/* OK - constant expression */
int i = ui;
/* OK - only signed/unsigned conversion */
float f = ui;
/* OK - integral/floating conversion */
}

REFERENCES

1. Origin: Misra Guidelines rule 43


2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 180

Avoid mixing arithmetic of different precisions in the same expression [MISRA-043_b-3]


DESCRIPTION
"C performs many type conversions implicitly and silently, so as to
harmonize
types within an expression before evaluating it. Some of these conversions
can
result in loss of information. Such implicit conversions shall not be
used,
but explicit casts should be used instead.
As a general principle, avoid mixing arithmetic of different precisions in
the
same expression."
The rule reports a violation if as operands of binary arithmetic,
relational
equality or bitwise operator are used two non-constant operands of
different
types.
See also: MISRA-043, MISRA-048_e, MISRA2004-10_1_b, MISRA2004-10_2, PORT27,
PORT-28,

NOTES
The rule does not report violations on conversions:
- between signed and unsigned types
- between integral and floating types

BENEFITS
The rule prevents unexpected behaviours.
"Mixed arithmetic normally entails implicit promotions and balancing
of types (i.e. conversions), some of which can lead to unexpected
behaviour."

EXAMPLE
void foo(){
int i;
short s1, s2, s3;

float f;
double d;
s1 = i + s2;
// Violation
i = s1 + (s2 - s3); // Violation - due to integral promotion
if( i > s1 ){
// Violation
//...
}
d = f - d;

// Violation

REPAIR
void foo1(unsigned int ui){
int i;
short s1, s2, s3;
float f;
double d;
s1 = i + (int)s2;
// OK
i = s1 + (short)(s2 - s3); // OK
if( i > (int)s1 ){
// OK
//...
}
d = (double)f - d;
/* exceptions */
f = f + i;
s1 = s2 + 10;
ui = ui + i;

// OK

// OK
// OK
// OK

REFERENCES
1. Origin: Misra Guidelines rule 43

Redundant explicit cast to the same type is not allowed [MISRA-044-3]


DESCRIPTION
"Explicit casting between identical types is unnecessary and clutters
code.
Furthermore it can mask problems if changes are made to the code (e.g. one
of
the types changes and a conversion with possible loss of information
occurs)"

SINCE
v7.2

BENEFITS
"The use of casting should be sufficient to cause the calculations
required
to occur with the desired precision. Unnecessary casting adds the
possibility
of confusion, and may be such that its interaction with the rules of
promotion
leads to results other than those expected. Unnecessary casting may also
lead
to code which is harder to maintain, should the types of variables
change."

EXAMPLE
typedef int INT;
int someFunction1();
INT someFunction2();
void foo(int p)
{
/* ... */
p = (int)someFunction1();
p = (int)someFunction2();
}

// Violation
// Violation

REPAIR
typedef int INT;
int someFunction1();
INT someFunction2();
void foo(int p)
{
/* ... */
p = someFunction1();
p = someFunction2();
}

// OK
// OK

REFERENCES
1. Origin: Misra Guidelines - Rule 44
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 181

Do not use the volatile keyword [MISRA-046_a-3]


DESCRIPTION
Do not use the volatile keyword.
See also: misra2004-12_2_f

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo1() {
volatile int v;
}

/* Violation */

REPAIR
Do not use the volatile keyword.

REFERENCES
1. Origin: Misra Guidelines - Rule 46
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 205

Evaluation order of an expression is implementation dependent [MISRA-046_c-3]


DESCRIPTION
The value of an expression shall be the same under
any order of evaluation that the standard permits.

BENEFITS
Readability and maintainability.

EXAMPLE
void foo46c(){
int array[3] = {0};
int iVar = 1;
array[iVar++] = iVar;/* Violation */
}

REPAIR
void foo46c(){
int array[3] = {0};
int iVar = 1;
array[iVar] = iVar + 1;/* OK */
iVar++;
}

REFERENCES
Origin: Misra Guidelines - Rule 46

Evaluation order of an expression is implementation dependent [MISRA-046_d-3]


DESCRIPTION
The value of an expression shall be the same under
any order of evaluation that the standard permits.

BENEFITS
Prevents unpredictable program behaviour.

EXAMPLE
void foo46(){
int array[3] = {0};
int iVar = 1;
array[iVar] = --iVar; /* Violation */
return;
}

REPAIR
void foo46(){
int array[3] = {0};
int iVar = 1;
array[iVar] = iVar-1; /* OK */
return;
}

REFERENCES
Misra Guidelines rule 46

Use explicit casts in mixed precision arithmetic [MISRA-048_a-5]


DESCRIPTION
Mixed precision arithmetic should use explicit casting to generate
the desired result.

BENEFITS
Prevents of loss data

EXAMPLE
void foo48b()
{
int iVar = 2;
long lVar = 1;
float fVar = 1.0;
iVar = (((iVar==2) ? fVar : lVar) + 22); /* Violation */
return;
}

REPAIR
void foo48b()
{
int iVar = 2;
long lVar = 1;
float fVar = 1.0;
iVar = (((iVar==2) ? (int)fVar : (int)lVar) + 22); /* OK */
return;
}

REFERENCES
Origin: Misra Guidelines - Rule 48

Use explicit casts in mixed precision arithmetic [MISRA-048_b-5]


DESCRIPTION
Mixed precision arithmetic should use explicit casting to generate
the desired result.

BENEFITS
Prevents loss of data

EXAMPLE
void foo48c()
{
int iVar = 2;
long lVar = 1;
float fVar = 1.0;
iVar = (((iVar==2) ? lVar : fVar ) + 22); /* Violation */
return;
}

REPAIR
void foo48c()
{
int iVar = 2;
long lVar = 1;
float fVar = 1.0;
iVar = (((iVar==2) ? lVar : (int)fVar ) + 22); /* OK */
return;
}

REFERENCES
Origin: Misra Guidelines - Rule 48

Use explicit casts in mixed precision arithmetic [MISRA-048_c-5]


DESCRIPTION
Mixed precision arithmetic should use explicit casting to generate
the desired result.

BENEFITS
Prevents loss of data.

EXAMPLE
void foo48()
{
int iVar = 2;
int iVar2 = 1;
float fVar = 1.0;
fVar = (float) (iVar2/iVar); /* Violation */
return;
}

REPAIR
void foo48()
{
int iVar = 2;
long lVar = 1;
float fVar = 1.0;
fVar = 34 + lVar/(float)iVar - 2; /* OK */
return;
}

REFERENCES
Origin: Misra Guidelines - Rule 48

Use explicit casts in mixed precision arithmetic [MISRA-048_d-5]


DESCRIPTION
Mixed precision arithmetic should use explicit casting to generate
the desired result.

BENEFITS
Prevents of loss data

EXAMPLE
void foo48b()
{
int iVar = 2;
long lVar = 1;
float fVar = 1.0;
iVar = (((iVar==2) ? fVar : lVar) + 22); /* Violation */
return;
}

REPAIR
void foo48b()
{
int iVar = 2;
long lVar = 1;
float fVar = 1.0;
iVar = (((iVar==2) ? (int)fVar : (int)lVar) + 22); /* OK */
return;
}

REFERENCES
Origin: Misra Guidelines - Rule 48

Use explicit type conversions for arithmetic using signed and unsigned values [MISRA-048_e3]
DESCRIPTION
"Mixing signed and unsigned values is error prone as it subjects
operations
to numerous arithmetic conversion and integral promotion rules."
The rule reports a violation if one operand of arithmetic binary
expression
is signed type and other is unsigned type. A violation is reported only if
both operands are non constant expressions.
The following binary arithmetic operators are checked:
'+', '-', '*', '/', '%', '^', '&', '|', '>>', '<<',
'+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '>>=', '<<='

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
void foo(signed char a, unsigned char b)
{
unsigned char c = a + b;
}

// Violation

REPAIR
void foo(signed char a, unsigned char b)
{
unsigned char c = (unsigned char)a + b;
}

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 8

2. Misra Guidelines - Rule 48


3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 162

Evaluation of constant unsigned integer expressions should not lead to wrap-around [MISRA051-5]
DESCRIPTION
"Because unsigned integer expressions do not strictly overflow, but
instead
wrap-around in a modular way, any constant unsigned integer expressions
which in effect 'overflow' will not be detected by the compiler."
The rule reports a violation if a result of subtraction of two integer
constants is lower than 0.

NOTES
This rule checks only simple subtractions for unsigned integer constants.
It is not possible to checks:
- expressions other than subtraction
- complex expressions
- expressions which use Macro definition or hexadecimal values

BENEFITS
Prevents from wrap-around for unsigned integer.

EXAMPLE
#if (1u - 2u) /* Violation */
/* ... */
#endif

REPAIR
Avoid wrap-around for unsigned integer.

REFERENCES
1. Origin: Misra Guidelines - Rule 51
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.25 Expressions, AV Rule 203


3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-190
http://cwe.mitre.org/top25/#CWE-190

A null statement shall only occur on a line by itself, and shall not have any other text on the
same line [MISRA-054-3]
DESCRIPTION
"Null statements should not normally be deliberately included, but where
they
are used they shall appear on a line by themselves and not with any other
text (including comments). Following this rule enables a static checking
tool
to warn of null statements appearing on a line with other text, which
would
normally indicate a programming error."

BENEFITS
Rule provides readability and clarity of code.

EXAMPLE
void foo1()
{
;
// Violation
int a;; // Violation
/* Violation */ ;
}

REPAIR
void foo1()
{
;
// OK
int c
;
// OK
for(;;); // OK
}

REFERENCES
Origin: Misra Guidelines - Rule 54

See also: MISRA2004-14_3

Do not use labels [MISRA-055-5]


DESCRIPTION
Labels should not be used, except in switch statements.

BENEFITS
Using labels can lead to errors and confusion.

EXAMPLE
void foo(int count)
{
/* ... */
goto stop_operation;
/* ... */
stop_operation: return; /* Violation */
/* ... */
}

REPAIR
Do not use labels in your code, except in switch statements.

REFERENCES
1. Origin: Misra Guidelines - Rule 55
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 188

Do not use the break statement [MISRA-058-3]


DESCRIPTION
The break statement shall not be used
(except to terminate the cases of a switch statement).

BENEFITS
Using 'break' can lead to errors and confusion.

EXAMPLE
#define true 1
void foo(int i)
{
while (true)
{
if (i==10)
{
break; /* Violation */
}
}
switch( i )
{
case -1:
while (true)
{
if (i==10)
{
break; /* Violation */
}
}
}
}

REPAIR
#define true 1
void foo(int i)

{
switch( i )
{
case -1 :
break; /* OK */
case 0 :
break; /* OK */
default:
break; /* OK */
}
}

REFERENCES
1. Origin: Misra Guidelines - Rule 58
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 191
3. ISO/DIS 26262
point 8.4.4

Do not use floating point variables as loop counters [MISRA-065-3]


DESCRIPTION
Floating point variables shall not be used as loop counters.

BENEFITS
Prevents giving unexpected results when the variable is tested.

EXAMPLE
void foo()
{
float i;
for (i=0.;i<10.;i++)
{
}
}

/* Violation */

REPAIR
void foo()
{
int i;
for (i=0;i<10;i++) /* OK */
{
}
}

REFERENCES
1. Origin: Misra Guidelines - Rule 65
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 197

Do not use functions with variable numbers of arguments [MISRA-069-3]


DESCRIPTION
Functions with variable numbers of arguments shall not be used.

BENEFITS
Prevents from a lot of potential problems with this feature.

EXAMPLE
void foo(int x, ...)
{
}

// Violation

REPAIR
Do not use functions with variable numbers of arguments.

REFERENCES
1. Misra Guidelines - Rule 69
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.1 Function Arguments - Rule 31
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 98
4. Scott Meyers and Martin Klaus, "Examining C++ Program Analyzers",
Dr. Dobbs' Journal, the February 1997,
Chapter: "Implementation", Item 23
http://www.aristeia.com/ddjpaper1_frames.html
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 108

6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-1

Functions shall always have visible prototype at both the function definition and call [MISRA071-3]
DESCRIPTION
Functions shall always have visible prototype at both the function
definition
and call. According to the ISO/IEC 9989:1999 C standard, a function
prototype
is a declaration of a function that declares the types of its parameters.
MISRA rule 71 requires that any function must be declared before it is
called
or defined. This means that function prototype must appear before the
definition
or call. The example below illustrates cases verified by this rule.
This rule is active for C code only.

BENEFITS
Rule prevents disabling the compiler's ability to pick up certain errors
in
function calls what happens when prototypes are not used.

EXAMPLE
/* file *.c */
/* definition without prototype */
void case2goo(void) {
/* Violation */
}
/* call without prototype */
void case3goo(void);
void case3foo(void) {
/* Violation */
}
void case3goo(void) {
case3foo();
/* Violation */
}
/* definition with prototype declared after function definition */
void case6goo(void) {
/* Violation */
}

void case6goo(void);
/* call with prototype declared after function call */
void case7goo(double x);
void case7goo(double x) {
case7foo(x);
/* Violation */
}
int case7foo(double);

REPAIR
/* file *.c */
/* both function call and definition have visible prototype */
void case1foo(void);
/* prototype */
void case1goo(void);
/* prototype */
void case1goo(void) {
/* OK */
case1foo();
/* OK */
}

REFERENCES
1. Origin: Misra Guidelines - Rule 71
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8, Rule 8.1

Provide none or all identifiers for function arguments [MISRA-073-3]


DESCRIPTION
Identifiers shall either be given for all of the parameters
in a function prototype declaration, or for none.

BENEFITS
Rule improves readability and clarity of code.

EXAMPLE
void foo3(int a, int); /* Violation */
void foo4(int a, int, int b); /* Violation */

REPAIR
void foo(); /* OK */
void foo1(int, int); /* OK */
void foo2(int a, int b); /* OK */

REFERENCES
Origin: Misra Guidelines - Rule 73

Provide expression for return statement of non-void functions [MISRA-083-3]


DESCRIPTION
For each function with non-void return value, each return shall
have an expression.

BENEFITS
Rule prevents from undefined behaviour
(the compiler may not give an error).

EXAMPLE
/* compilable by 'c' compiler */
int foo2() {
return ; /* violation */
}

REPAIR
int foo3() {
return 0; /* OK */
}
void foo1() {
return; /* OK */
}

REFERENCES
Origin: Misra Guidelines - Rule 83

Avoid expressions in return statements of void functions [MISRA-084-3]


DESCRIPTION
For functions with void return type,
return statements shall not have an expression.

BENEFITS
Rule prevents from undefined behaviour (the compiler may not give an
error).

EXAMPLE
/* compilable by 'c' compiler */
void foo2() {
return 1; /* Violation */
}
void foo3() {
int a=0;
return a; /* Violation */
}
void foo4(int a) {
return a; /* Violation */
}

REPAIR
/* compilable by 'c' compiler */
void foo1() {
return;
/* OK */
}

REFERENCES
Origin: Misra Guidelines - Rule 84

Use empty parentheses when calling function with no arguments [MISRA-085-5]


DESCRIPTION
Function called with no parameters should have empty parentheses.

BENEFITS
Rule prevents errorneous code and improves quality.

EXAMPLE
int foo()
{
int iVar = 0;
if( foo == 0 ) { /* Violation */
iVar++;
}
if( 0 == foo ) { /* Violation */
iVar++;
}
return 0;
}

REPAIR
int foo()
{
int iVar = 0;
if( foo() == 0 ) { /* OK */
iVar++;
}
if( 0 == foo() ) { /* OK */
iVar++;
}
return 0;
}

REFERENCES

Origin: Misra Guidelines - Rule 85

#include directive must be followed by a filename in double-quotes or angle brackets [MISRA089-3]


DESCRIPTION
The #include directive shall be followed by either a <filename> of
"filename" sequence.

BENEFITS
Improves readability of code.

EXAMPLE
// #include "misra89.h"
#define MISRA_HEADER "misra89.h"
#include MISRA_HEADER /* Violation */

REPAIR
#include "misra89.h" /* OK */

REFERENCES
Origin: Misra Guidelines - Rule 89

Enclose in parentheses whole definition of a function-like macro [MISRA-096-3]


DESCRIPTION
In the definition of a function-like macro whole definition
shall be enclosed in parentheses.
See also: MISRA2004-19_10

BENEFITS
Improves the readability of code and ensures operations order.

EXAMPLE
#define abs( x ) (x)>=0 ? c: -(x)

/* Violation */

REPAIR
#define abs2( x ) ((x)>=0 ? c: -(x))

REFERENCES
Origin: Misra Guidelines - Rule 96

/* OK */

Use only non-ambiguous forms of defined pre-processor operator [MISRA-100-3]


DESCRIPTION
The defined pre-processor operator shall only be used in one of the two
standards forms.

BENEFITS
Prevents from undefined bahaviour.

EXAMPLE
/* EXAMPLE.H - Example header file */
#if defined TEST+1
/* Violation */
#endif

REPAIR
/* EXAMPLE.H - Example header file */
#if defined TEST
/* OK */
#endif
#if defined EXAMPLE_H
#endif
#if defined ( TEST )
#endif

/* OK */

#if !defined ( EXAMPLE_H )


#define EXAMPLE_H
/* OK */
struct Example
{
int _i;
};
#endif /* !defined( EXAMPLE_H ) */

REFERENCES
Origin: Misra Guidelines - Rule 100

Avoid pointer arithmetic [MISRA-101-5]


DESCRIPTION
Pointer arithmetic should not be used.

BENEFITS
Prevents from access to unintended or invalid memory addresses.

EXAMPLE
void foo()
{
int* a;
int* b;
int tab[10];
a=tab;
a++;
/* Violation */
--a;
/* Violation */
b = a+5;
/* Violation */
}

REPAIR
Do not use pointer arithmetic.

REFERENCES
1. Origin: Misra Guidelines - Rule 101
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 215

Do not use non-constant pointers to functions [MISRA-104-3]


DESCRIPTION
Non-constant pointers to functions shall not be used.
See also: CODSTA-CPP-03, CODSTA-CPP-38, CODSTA-CPP-43, CODSTA-CPP-44,
MISRA2004-16_7, OPT-21

BENEFITS
Prevents using non-constant pointers to functions.

EXAMPLE
void foo( );
typedef void (*PFUNC) (void);
const PFUNC pf = foo;
void bar( ) {
PFUNC f1 = foo;
}

/* Violation */

REPAIR
void foo( );
typedef void (*PFUNC) (void);
const PFUNC pf = foo;
void bar( ) {
const PFUNC f1 = foo;
}

/* OK */

REFERENCES
1. Misra Guidelines - Rule 104
2. ISO/DIS 26262
point 8.4.4

All the functions pointed to by a single pointer to function shall be identical in the number and
type of parameters and the return type [MISRA-105-3]
DESCRIPTION
The rule reports a violation if a pointer to function is:
- assigned to other pointer to function, or
- initialized by other pointer to function, or
- cast to type of pointer to function
and pointed functions are not identical.
The rule assumes that two functions are identical if they have the same
number
and types of parameters and the same return types.

NOTES
This rule is active for C code only.

BENEFITS
"Pointers to functions can easily violate type integrity,
so all pointed-to functions should be of identical type."

EXAMPLE
typedef
typedef
typedef
typedef

int(*PTF1)(int, char*);
void(*PTF2)(int, char*);
int(*PTF3)(int, int);
int(*PTF4)(int, char*, ...);

int foo1(int, char*);


void foo2(int, char*);
int foo3(int, int);
int foo4(int, char*, ...);
void test(void)
{
PTF1 p1;
PTF2 p2 = foo1; /* Violation */
PTF3 p3;
PTF4 p4;

p1
p1
p1
p1
p1
p1

=
=
=
=
=
=

p2;
p3;
(PTF1)p4;
foo2;
(PTF1)foo3;
foo4;

/*
/*
/*
/*
/*
/*

Violation
Violation
Violation
Violation
Violation
Violation

*/
*/
*/
*/
*/
*/

REPAIR
typedef
typedef
typedef
typedef

int(*PTF1)(int, char*);
void(*PTF2)(int, char*);
int(*PTF3)(int, int);
int(*PTF4)(int, char*, ...);

int foo1(int, char*);


void foo2(int, char*);
int foo3(int, int);
int foo4(int, char*, ...);
void test(void)
{
PTF1 p1;
PTF2 p2 = foo2;
PTF3 p3;
PTF4 p4;

/* OK */

p1 = (PTF1)foo1; /* OK */
p3 = foo3;
/* OK */
p4 = (PTF4)foo4; /* OK */
}

REFERENCES
Misra Guidelines - Rule 105

The NULL pointer shall not be dereferenced [MISRA-107_a-3]


DESCRIPTION
"Where a function returns a pointer and that pointer is subsequently
de-referenced, the program should first check that the pointer is not
NULL."
If a control statement contains in condition non-dereferenced pointer,
then
the rule assumes that this pointer is checked. In such cases rule does not
report violations in spite of it does not check if a control statement is
really used to prevent null pointer dereference.
See also: MISRA-107_b, BD-PB-NP

BENEFITS
Complying with this rule leads to safer code.

EXAMPLE
int* ret_ptr(int* p){
return p;
}
void func(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
/* here pointer 'ptr' should be checked */
i = *ptr;
/* Violation - pointer 'ptr' may be null */
}

REPAIR
int* ret_ptr(int* p){
return p;
}
int check(int* p){
if(p == 0)
return 0;

if(p > 0)
return 1;
}
void func1(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(ptr){
i = *ptr;
/* OK - pointer 'ptr' was checked in 'if' condition */
}
}
void func2(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(!ptr){
return;
}
i = *ptr;
/* OK - pointer 'ptr' was checked in 'if' condition */
}
void func3(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(check(ptr)){
i = *ptr;
/* OK - pointer 'ptr' was checked in 'check' function */
}
}
void func4(int i, int* par){
int* ptr;
ptr = ret_ptr(par);
if(ptr == 0){
i = *ptr;
/* OK - pointer 'ptr' was checked in 'if' condition.
The 'if' condition is not correct, but the rule
does not check such cases. To detect this issue
could be used Bug Detectiv rule - BD-PB-NP */
}

REFERENCES
1. Origin: Misra Guidelines - Rule 107
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 174
3. http://cwe.mitre.org/data/definitions/476.html
4. ISO/DIS 26262
point 8.4.4

The NULL pointer shall not be dereferenced [MISRA-107_b-3]


DESCRIPTION
"Where a function returns a pointer and that pointer is subsequently
de-referenced, the program should first check that the pointer is not
NULL."
If a control statement contains in condition non-dereferenced pointer,
then
the rule assumes that this pointer is checked. In such cases rule does not
report violations in spite of it does not check if a control statement is
really used to prevent null pointer dereference.
See also: MISRA-107_a, BD-PB-NP

BENEFITS
Complying with this rule leads to safer code.

EXAMPLE
struct S{
int si;
};
struct S* ret_ptr(struct S* p){
return p;
}
void func(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
/* here pointer 's' should be checked */
s->si = i;
/* Violation - pointer 's' may be null */
}

REPAIR
struct S{
int si;

};
struct S* ret_ptr(struct S* p){
return p;
}
int check(struct S* p){
if(p == 0)
return 0;
if(p > 0)
return 1;
}
void func1(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(s){
s->si = i;
/* OK - pointer 's' was checked in 'if' condition */
}
}
void func2(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(!s){
return;
}
s->si = i;
/* OK - pointer 's' was checked in 'if' condition */
}
void func3(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(check(s)){
s->si = i;
/* OK - pointer 's' was checked in 'check' function */
}

}
void func4(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(s == 0){
s->si = i;
/* OK - pointer 's' was checked in 'if' condition.
The 'if' condition is not correct, but the rule
does not check such cases. To detect this issue
could be used Bug Detectiv rule - BD-PB-NP */
}
}

REFERENCES
1. Origin: Misra Guidelines - Rule 107
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 174
3. http://cwe.mitre.org/data/definitions/476.html
4. ISO/DIS 26262
point 8.4.4

All members of structure or union should be fully specified [MISRA-108-3]


DESCRIPTION
In the specification of a structure or union type,
all members of the structure or union shall be
fully specified.

BENEFITS
Prevents using undefined variable types.

EXAMPLE
struct X {
int i;
};
struct Y {
struct X* x;
int i;
};

/* Violation */

REPAIR
struct X {
int i;
};
struct Y {
struct X x;
int i;
};

/* OK */

REFERENCES
Origin: Misra Guidelines rule 108

Unions shall not be used to access the sub-parts of larger data structure [MISRA-110-3]
DESCRIPTION
Unions shall not be used to access the sub-parts of larger data structure.
One mechanism in C for accessing the sub-parts of larger data structures
(e.g. the individual bits of an I/O port) is to overlay one data structure
on another using unions.
For example, a structure containing bit fields might be overlaid
on an integer.
This is not a secure mechanism for achieving the desired aim, because it
assumes too much about the way in which the different data types are
stored.
This rule triggers when an union has some bit-fields member variable,
when it includes other data structures which themselves include bitfields,
or finally when it has a member variable of type array of char where
dimension
is sizeof of some type (see examples).

BENEFITS
Prevents data loss.

EXAMPLE
typedef union { /* Violation */
struct {
unsigned int en
:1;
unsigned int dly
:1;
unsigned int tm_en
:1;
unsigned int dta_inv :1;
unsigned int clk_inv :1;
} _bitfield;
unsigned long _int;
} REG_PTR;
union A { /* Violation */
int field;
int firstTwoBits :2;

};
typedef int* TYPE;
union B { /* Violation */
TYPE t;
char bytes[sizeof(TYPE)];
};

REPAIR
Do not use union structure.

REFERENCES
Origin: Misra Guidelines - Rule 110

All the members of a structure (or union) shall be named [MISRA-113-3]


DESCRIPTION
All the members of a structure (or union) shall be named.
The "bit field" facility in C is one of the most poorly defined parts
of the language. There are two main uses to which bit-fields could be put:
1) To access individual bits, or group of bits, in larger data-types,
in conjunction with unions (see rule 110).
2) To allow flags or other short-length data to be packed to save storage
space
The packing together of short-length data to economise on storage is the
only
acceptable use of bit fields envisaged in this document.
Provided the elements of the structure are only ever accessed by their
name,
the programmer needs to make no assumptions about the way the bit fields
are stored within the structure.
This rules checks that all declared bit fields have names.

BENEFITS
Prevents using unaccessible data.

EXAMPLE
typedef signed int t;
typedef int plain;
struct tag {
unsigned t:4;
const t:5;
/* Violation */
plain r:5;
};

REPAIR

Name all the members of a structure (or union).

REFERENCES
1. Origin:

Misra Guidelines rule 113

2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.21 Operators, AV Rule 156

Standard library function names shall not be reused [MISRA-115-3]


DESCRIPTION
Standard library function names shall not be reused.
This rule requires that any new versions of standard functions are given
names different than
the original functions.
This is to avoid confusion as to whether a standard library function is
being used or
whether a modified version of that function is being used.
This rule will report violation for the redefinition of functions listed
in Annex B of the ISO/IEC 9899:1999
standard. It will also report any function definitions whose names
conflict with any of function macros
defined in the standard (see the example below).
This rule is active for C code only.

BENEFITS
Prevents writing error prone code and provides maintainability.

EXAMPLE
double sqrt(double arg)
{
return (arg);
}

/* Violation - redefined */

void strpbrk(double arg) { }

/* Violation - redefined */

/* macro redefined as function */


void offsetof(double arg) { }

/* Violation - std. macro name */

REPAIR
double sqrt(double);
void foo()
{
sqrt(123.0);
}

/* OK - just declared */
/* OK - user function */
/* OK - std. C function call */

REFERENCES
Origin: Misra Guidelines - Rule 115

Do not use locale.h header and setlocale function [MISRA-121_a-3]


DESCRIPTION
<locale.h> and the setlocale function shall not be used.

BENEFITS
Prevents changing the locate from the standard C locate.

EXAMPLE
#include <locale.h>
void foo(void)
{
/* Set the locale back to the default environment */
setlocale(LC_ALL, "C"); /* Violation */
}

REPAIR
Do not use 'setlocale' functions.

REFERENCES
1. Origin: Misra Guidelines - Rule 121
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 19

Do not use locale.h header and setlocale function [MISRA-121_b-3]


DESCRIPTION
<locale.h> and the setlocale function shall not be used.

BENEFITS
Prevents changing the locate from the standard C locate.

EXAMPLE
#include <locale.h> /* Violation */
void foo(void)
{
/* Set the locale back to the default environment */
setlocale(LC_ALL, "C");
}

REPAIR
Do not use 'setlocale' functions.

REFERENCES
Origin: Misra Guidelines - Rule 121

MISRA2004
MISRA C 2004
RULES
Avoid implicit conversions between signed and unsigned integer types
[MISRA2004-10_1_a-3]
Avoid implicit conversions between integer and floating types [MISRA200410_1_b-3]
Avoid implicit conversions of complex expressions [MISRA2004-10_1_c-3]
Avoid implicit conversions from wider to narrower types [MISRA2004-10_1_d3]
Avoid implicit conversions of function return expressions [MISRA200410_1_e-3]
Avoid implicit conversions of complex expressions [MISRA2004-10_1_f-3]
Avoid implicit conversions of function arguments [MISRA2004-10_1_g-3]
Avoid implicit conversions between signed and unsigned integer types
[MISRA2004-10_1_h-3]
Avoid implicit conversions of complex expressions [MISRA2004-10_1_i-3]
Avoid implicit conversions of float type resulting in a loss of
information [MISRA2004-10_2-3]
Avoid implicit conversions of float type resulting in a loss of
information [MISRA2004-10_2_b-3]
The value of a complex expression of integer type shall only be cast to a
type of the same signedness that is no wider than the underlying type of
the expression [MISRA2004-10_3-3]
The value of a complex expression of floating type may only be cast to a
narrower floating type [MISRA2004-10_4-3]
If the bitwise operators ~ and << are applied to an operand of underlying
type unsigned char or unsigned short, the result shall be immediately cast
to the underlying type of the operand [MISRA2004-10_5-3]
A 'U' suffix shall be applied to all constants of unsigned type
[MISRA2004-10_6-5]
Conversions shall not be performed between a pointer to a function and any
type other than an integral type [MISRA2004-11_1-3]
Conversions shall not be performed between a pointer to object and any
type other than an integral type, another pointer to object type or a
pointer to void [MISRA2004-11_2-3]
Conversions shall not be performed between a pointer to object and any
type other than an integral type, another pointer to object type or a
pointer to void [MISRA2004-11_2_b-3]
Conversions shall not be performed between a pointer to object and any
type other than an integral type, another pointer to object type or a
pointer to void [MISRA2004-11_2_c-3]
A cast should not convert a pointer type to an integral type [MISRA200411_3_a-3]

A cast should not convert an integral type to a pointer type [MISRA200411_3_b-3]


A cast should not be performed between a pointer to object type and a
different pointer to object type [MISRA2004-11_4-3]
A cast shall not be performed that removes any const or volatile
qualification from the type addressed by a pointer [MISRA2004-11_5-3]
The comma operator shall not be used [MISRA2004-12_10-3]
The underlying bit representations of floating-point values shall not be
used [MISRA2004-12_12-3]
The increment (++) and decrement (--) operators should not be mixed with
other operators in an expression [MISRA2004-12_13-3]
Limited dependence should be placed on C's operator precedence rules in
expressions [MISRA2004-12_1_a-3]
Limited dependence should be placed on C's operator precedence rules in
expressions [MISRA2004-12_1_b-5]
No parentheses are required for the operand of a unary operator
[MISRA2004-12_1_c-5]
Limited dependence should be placed on C's operator precedence rules in
expressions [MISRA2004-12_1_d-3]
Use parentheses unless all operators in the expression are the same
[MISRA2004-12_1_e-3]
Limited dependence should be placed on C's operator precedence rules in
expressions [MISRA2004-12_1_f-5]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2004-12_2_a-3]
Don't write code that depends on the order of evaluation of function
arguments [MISRA2004-12_2_b-1]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2004-12_2_c-3]
Don't write code that depends on the order of evaluation of expression
that involves a function call [MISRA2004-12_2_d-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2004-12_2_e-3]
Do not use more than one volatile in one expression [MISRA2004-12_2_f-3]
Don't write code that depends on the order of evaluation of function calls
[MISRA2004-12_2_g-3]
The sizeof operator shall not be used on expressions that contain side
effects [MISRA2004-12_3-3]
The right-hand operand of a logical && or || operator shall not contain
side effects [MISRA2004-12_4_a-3]
The second or third operand of a ternary operator '?:' shall not contain
side effects [MISRA2004-12_4_b-4]
The operands of a logical && or || shall be primary-expressions
[MISRA2004-12_5-3]

The operands of logical operators (&&, || and !) should be effectively


Boolean [MISRA2004-12_6_a-3]
Expressions that are effectively Boolean should not be used as operands to
operators other than (&&, ||, !, =, ==, !=, ?:) [MISRA2004-12_6_b-3]
Bitwise operators shall not be applied to operands whose underlying type
is signed [MISRA2004-12_7-3]
The right-hand operand of a shift operator shall lie between zero and one
less than the width in bits of the underlying type of the left-hand
operand [MISRA2004-12_8-3]
The unary minus operator shall not be applied to an expression whose
underlying type is unsigned [MISRA2004-12_9-3]
Assignment operators shall not be used in expressions that yield a Boolean
value [MISRA2004-13_1-3]
Tests of a value against zero should be made explicit, unless the operand
is effectively Boolean [MISRA2004-13_2-3]
Floating-point expressions shall not be tested for equality or inequality
[MISRA2004-13_3-3]
The controlling expression of a for statement shall not contain any
objects of floating type [MISRA2004-13_4-3]
The three expressions of a for statement shall be concerned only with loop
control [MISRA2004-13_5-3]
Do not modify for loop counter within a body of the loop [MISRA2004-13_63]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_a-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_aa-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ab-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ac-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ad-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ae-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_af-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ag-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ah-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ai-3]

Boolean operations whose results are invariant shall not be permitted


[MISRA2004-13_7_aj-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_ak-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_b-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_c-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_d-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_j-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_k-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_l-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_m-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_n-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_s-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_t-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_u-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_v-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_w-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_x-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_y-3]
Boolean operations whose results are invariant shall not be permitted
[MISRA2004-13_7_z-3]
All 'if...else-if' constructs shall be terminated with an 'else' clause
[MISRA2004-14_10-3]
There shall be no unreachable code in "else" block [MISRA2004-14_1_a-3]
There shall be no unreachable code after 'return', 'break', 'continue',
and 'goto' statements [MISRA2004-14_1_b-3]
There shall be no unreachable code in "if/else/while/for" block
[MISRA2004-14_1_c-3]

There shall be no unreachable code in switch statement [MISRA2004-14_1_d3]


There shall be no unreachable code in 'for' loop [MISRA2004-14_1_e-3]
There shall be no unreachable code after 'if' or 'switch' statement
[MISRA2004-14_1_f-3]
There shall be no unreachable code after "if" or "switch" statement inside
while/for/do...while loop [MISRA2004-14_1_g-3]
All non-null statements shall either have at least one side-effect however
executed or cause control flow to change [MISRA2004-14_2-3]
Null statement shall only occur on a line by itself or it may be followed
by a comment [MISRA2004-14_3-3]
The goto statement shall not be used [MISRA2004-14_4-3]
The continue statement shall not be used [MISRA2004-14_5-3]
For any iteration statement there shall be at most one break statement
used for loop termination [MISRA2004-14_6-3]
A function shall have a single point of exit at the end of the function
[MISRA2004-14_7-3]
The statement forming the body of a 'switch', 'while', 'do...while' or
'for' statement shall be a compound statement [MISRA2004-14_8-3]
'if' and 'else' should be followed by a compound statement [MISRA200414_9-3]
A switch statement shall only contain switch labels and switch clauses,
and no other code [MISRA2004-15_0_a-3]
A switch statement shall only contain switch labels and switch clauses,
and no other code [MISRA2004-15_0_b-3]
A switch statement shall only contain switch labels and switch clauses,
and no other code [MISRA2004-15_0_c-3]
A switch label shall only be used when the most closely-enclosing compound
statement is the body of a switch statement [MISRA2004-15_1-3]
An unconditional break statement shall terminate every non-empty switch
clause [MISRA2004-15_2-3]
The final clause of a switch statement shall be the default clause
[MISRA2004-15_3-3]
A switch expression shall not represent a value that is effectively
Boolean [MISRA2004-15_4-3]
Every switch statement shall have at least one case clause [MISRA200415_5-3]
Functions shall not be defined with a variable number of arguments
[MISRA2004-16_1-3]
If a function returns error information, then that error information shall
be tested [MISRA2004-16_10-3]
Functions shall not call themselves, either directly or indirectly
[MISRA2004-16_2-3]

Identifiers shall be given for all of the parameters in a function


prototype declaration [MISRA2004-16_3-3]
The identifiers used in the declaration and definition of a function shall
be identical [MISRA2004-16_4-3]
Functions with no parameters shall be declared with parameter type void
[MISRA2004-16_5-3]
The number of arguments passed to a function shall match the number of
parameters [MISRA2004-16_6-3]
A pointer parameter in a function prototype should be declared as pointer
to const if the pointer is not used to modify the addressed object
[MISRA2004-16_7-3]
Declare a type of parameter as typedef to pointer to const if the pointer
is not used to modify the addressed object [MISRA2004-16_7_b-3]
All exit paths from a function with non-void return type shall have an
explicit return statement with an expression [MISRA2004-16_8-3]
Do not apply arithmetic to pointers that don't address an array or array
element [MISRA2004-17_1-3]
Pointer arithmetic shall only be applied to pointers that address an array
or array element [MISRA2004-17_2-3]
>, >=, <, <= shall not be applied to pointer types except where they point
to the same array [MISRA2004-17_3-3]
Array indexing shall be the only allowed form of pointer arithmetic
[MISRA2004-17_4-3]
The declaration of objects should contain no more than 2 levels of pointer
indirection [MISRA2004-17_5_a-3]
The declaration of objects should contain no more than 2 levels of pointer
indirection [MISRA2004-17_5_b-3]
The declaration of objects should contain no more than 2 levels of pointer
indirection [MISRA2004-17_5_c-3]
The declaration of objects should contain no more than 2 levels of pointer
indirection [MISRA2004-17_5_d-3]
The address of an object with automatic storage shall not be assigned to
another object that may persist after the first object has ceased to exist
[MISRA2004-17_6-3]
All structure and union types shall be complete at the end of a
translation unit [MISRA2004-18_1-3]
An object shall not be assigned to an overlapping object [MISRA2004-18_23]
An object shall not be assigned to an overlapping object [MISRA200418_2_b-3]
Unions shall not be used [MISRA2004-18_4-3]
#include statements in a file should only be preceded by other
preprocessor directives or comments [MISRA2004-19_1-3]

In the definition of a function-like macro each instance of a parameter


shall be enclosed in parentheses unless it is used as the operand of # or
## [MISRA2004-19_10-3]
All macro identifiers in preprocessor directives shall be defined before
use, except in #ifdef and #ifndef preprocessor directives and the
defined() operator [MISRA2004-19_11-3]
There shall be at most one occurrence of the # or ## preprocessor
operators in a single macro definition [MISRA2004-19_12-3]
The # and ## preprocessor operators should not be used [MISRA2004-19_13-3]
The defined preprocessor operator shall only be used in one of the two
standard forms [MISRA2004-19_14-3]
Precautions shall be taken in order to prevent the contents of a header
file being included twice [MISRA2004-19_15-3]
Preprocessing directives shall be syntactically meaningful even when
excluded by the preprocessor [MISRA2004-19_16-3]
All #else, #elif and #endif preprocessor directives shall reside in the
same file as the #if or #ifdef directive to which they are related
[MISRA2004-19_17-3]
Non-standard characters should not occur in header file names in #include
directives [MISRA2004-19_2-3]
Avoid keywords and basic types in macros [MISRA2004-19_4-3]
Macros shall not be #define'd or #undef'd within a block [MISRA2004-19_53]
#undef shall not be used [MISRA2004-19_6-3]
A function should be used in preference to a function-like macro
[MISRA2004-19_7-3]
A function-like macro shall not be invoked without all of its arguments
[MISRA2004-19_8-3]
Arguments to a function-like macro shall not contain tokens that look like
preprocessing directives [MISRA2004-19_9-3]
The library functions atof, atoi and atol from library stdlib.h shall not
be used [MISRA2004-20_10-3]
The library functions abort, exit, getenv and system from library stdlib.h
shall not be used [MISRA2004-20_11-3]
The time handling functions of library time.h shall not be used
[MISRA2004-20_12-3]
Reserved identifiers, macros and functions in the standard library, shall
not be defined, redefined or undefined [MISRA2004-20_1_a-3]
Do not redefine reserved words [MISRA2004-20_1_b-3]
The names of standard library macros, objects and functions shall not be
reused [MISRA2004-20_2-3]
The validity of values passed to library functions shall be checked
[MISRA2004-20_3-3]

Dynamic heap memory allocation shall not be used [MISRA2004-20_4-3]


The error indicator errno shall not be used [MISRA2004-20_5-3]
The macro offsetof, in library stddef.h, shall not be used [MISRA200420_6-3]
The setjmp macro and the longjmp function shall not be used [MISRA200420_7-3]
The signal handling facilities of signal.h shall not be used [MISRA200420_8-3]
The input/output library stdio.h shall not be used [MISRA2004-20_9-3]
Assembly language shall be encapsulated and isolated [MISRA2004-2_1-3]
Source code shall only use /* ... */ style comments [MISRA2004-2_2-3]
The character sequence /* shall not be used within a comment [MISRA20042_3-3]
Sections of code should not be "commented out" [MISRA2004-2_4-4]
All uses of the #pragma directive shall be documented and explained
[MISRA2004-3_4-3]
Do not mix bit-fields and other data within the same structure [MISRA20043_5-3]
Only those escape sequences that are defined in the ISO C standard shall
be used [MISRA2004-4_1-3]
Trigraphs shall not be used [MISRA2004-4_2-3]
Identifiers (internal and external) shall not rely on the significance of
more than 31 characters [MISRA2004-5_1-3]
Identifiers in an inner scope shall not use the same name as an identifier
in an outer scope, and therefore hide that identifier [MISRA2004-5_2_a-3]
Identifiers in an inner scope shall not use the same name as an identifier
in an outer scope, and therefore hide that identifier [MISRA2004-5_2_b-3]
Do not reuse typedef names [MISRA2004-5_3_a-3]
Do not reuse typedef names as a typedef name [MISRA2004-5_3_b-3]
A tag name shall not be reused for other purpose within the program
[MISRA2004-5_4_a-3]
A tag name shall not be reused to define a different tag [MISRA2004-5_4_b3]
No object or function identifier with static storage duration should be
reused [MISRA2004-5_5_a-4]
No object or function identifier with static storage duration should be
reused [MISRA2004-5_5_b-4]
No identifier in one name space should have the same spelling as an
identifier in another name space, with the exception of structure and
union member names [MISRA2004-5_6-4]
No identifier name should be reused [MISRA2004-5_7-4]
The plain char type shall be used only for the storage and use of
character values [MISRA2004-6_1-3]

signed and unsigned char type shall be used only for the storage and use
of numeric values [MISRA2004-6_2-3]
typedefs that indicate size and signedness should be used in place of the
basic types [MISRA2004-6_3-3]
Bit fields shall only be defined to be of type unsigned int or signed int
[MISRA2004-6_4-3]
Bit fields of signed types shall be at least 2 bits long [MISRA2004-6_5-3]
Octal constants (other than zero) and octal escape sequences shall not be
used [MISRA2004-7_1-3]
The static storage class specifier shall be used in definitions and
declarations of objects and functions that have internal linkage
[MISRA2004-8_11-3]
When an array is declared with external linkage, its size shall be stated
explicitly or defined implicitly by initialisation [MISRA2004-8_12-3]
Whenever a function is declared or defined, its type shall be explicitly
stated [MISRA2004-8_2_a-3]
Whenever an object is declared or defined, its type shall be explicitly
stated [MISRA2004-8_2_b-3]
Use identical types in declaration and definition [MISRA2004-8_3_a-3]
Use identical types in declaration and definition [MISRA2004-8_3_b-3]
There shall be no definitions of objects or functions in a header file
[MISRA2004-8_5-3]
Always declare functions at file scope [MISRA2004-8_6-3]
Objects shall be defined at block scope if they are only accessed from
within a single function [MISRA2004-8_7-3]
Braces shall be used to indicate and match the structure in the non-zero
initialization of arrays and structures [MISRA2004-9_2-3]
In an enumerator list, the "=" construct shall not be used to explicitly
initialise members other than the first, unless all items are explicitly
initialised [MISRA2004-9_3-3]

Avoid implicit conversions between signed and unsigned integer types [MISRA2004-10_1_a-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = u32a;
s32b = s32a + u32a;

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = (signed int)u32a;

/* OK */

s32b = s32a + (signed int)u32b; /* OK */


}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions between integer and floating types [MISRA2004-10_1_b-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between integer and floating types are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
float f32a;
unsigned int u32a;
f32a = u32a;
f32a = f32a + u32a;
f32a = u32a + 2.5f;
}

REPAIR
void Conv1_int( ) {
float f32a;
unsigned int u32a;

/* Violation */
/* Violation */
/* Violation */

f32a = (float)u32a;
f32a = f32a + (float)u32a;
f32a = (float)u32a + 2.5f;

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of complex expressions [MISRA2004-10_1_c-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
"The intention when restricting implicit conversion of complex expressions
is to require that in a sequence of arithmetic operations within an
expression,
all operations should be conducted in exactly the same arithmetic type.
Notice that this does not imply that all operands in an expression are
of the same type.
The expression u32a + u16b + u16c is compliant - both additions will
notionally
be performed in type U32.
The expression u16a + u16b + u32c is not compliant - the first addition
is notionally performed in type U16 and the second in type U32.
The word 'notionally' is used because, in practice, the type in which
arithmetic will be conducted will depend on the implemented size of an
int."
Rule checks if implicit conversions of complex expressions are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;

u32a = u16b + u16a + u32b;


u32a = u32b + (u16a + u16b);

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
u32a = u32b + u16b + u16a;
u32a = u16b + (u16a + u32b);

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions from wider to narrower types [MISRA2004-10_1_d-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted
to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always
conducted on integer operands of type int or long (signed or unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation.
The underlying type of an integer constant expression will be determined
according to its magnitude and signedness"
The rule reports a violation if parameter/variable/expression of integral
type is implicitly converted to a narrower integral type.

SINCE
v7.0

NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
The underlying type of an integer constant is determined according
to its magnitude and signedness.

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = u32a;
u8a = u32a;

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = (unsigned short)u32a;
u8a = (unsigned char)u32a;

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6

Avoid implicit conversions of function return expressions [MISRA2004-10_1_e-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type if the expression is not constant
and is a return expression.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always conducted on integer operands of type int or long (signed or
unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation."
Rule checks if implicit conversions of function return expressions are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
unsigned int Conv_ret1( signed char a )
{
return a;
/* Violation */
}

REPAIR
unsigned int Conv_ret1( signed char a )

{
return (unsigned int)a;

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of complex expressions [MISRA2004-10_1_f-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
"The intention when restricting implicit conversion of complex expressions
is
to require that in a sequence of arithmetic operations within an
expression,
all operations should be conducted in exactly the same arithmetic type."
Rule checks if implicit conversions of complex expressions are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.

EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;

u32a = u16b + u16a;

/* Violation */

REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;
u32a = (unsigned int)(u16b + u16a);

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of function arguments [MISRA2004-10_1_g-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type if the expression is not
constant and is a function argument.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always conducted on integer operands of type int or long (signed or
unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation."
Rule checks if implicit conversions of function arguments are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double(si);
/* Violation */
takes_unsigned_int(uc);
/* Violation */
takes_signed_int(ui);
/* Violation */
}

REPAIR
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double((double) si);
takes_unsigned_int(ui);
takes_signed_int((int) ui);
}

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions between signed and unsigned integer types [MISRA2004-10_1_h-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used
when variables are initialized.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = u32a;
}

/* Violation */

REPAIR
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = (signed int)u32a;
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of complex expressions [MISRA2004-10_1_i-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
"The intention when restricting implicit conversion of complex expressions
is
to require that in a sequence of arithmetic operations within an
expression,
all operations should be conducted in exactly the same arithmetic type."
Rule checks if implicit conversions of complex expressions are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.

EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = u16b + u16a;
}

/* Violation */

REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = (unsigned int)(u16b + u16a);
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of float type resulting in a loss of information [MISRA2004-10_2-3]


DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a

=
=
=
=

f32a;
f32a;
f64a;
f32b + f32a + f64b;

REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;

//
//
//
//

Violation
Violation
Violation
Violation

u32b
s32b
f32a
f64a

=
=
=
=

(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

Avoid implicit conversions of float type resulting in a loss of information [MISRA2004-10_2_b3]


DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}

REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;

// Violation
// Violation
// Violation

float32_t f32bt = (float)f64a;


// OK
unsigned int u32a = (unsigned int)f32a;
// OK
unsigned short u16a = (unsigned short)1.0; // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

The value of a complex expression of integer type shall only be cast to a type of the same
signedness that is no wider than the underlying type of the expression [MISRA2004-10_3-3]
DESCRIPTION
Rule reports violation if the value of a complex expression of integer
type
is cast to a type that has different signedness or is wider than
the underlying type of the expression.
"The term 'complex expression' is defined to mean any expression that is
not:
- a constant expression
- an lvalue (i.e. an object)
- the return value of a function
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."

BENEFITS
The rule prevents behaviours inconsistent with developer expectations.

EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}

Violation - cast from signed to


Violation - cast from unsigned to
Violation - cast from narrower to
Violation - cast from integer to

REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =

= (unsigned int)si1 + (unsigned int)si2;


= (signed int)ui1 / (signed int)ui2;
= (unsigned int)us1 - (unsigned int)us2;
(double)ui1 * (double)ui2;

/*
/*
/*
/*

OK
OK
OK
OK

*/
*/
*/
*/

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9

The value of a complex expression of floating type may only be cast to a narrower floating
type [MISRA2004-10_4-3]
DESCRIPTION
"If a cast is to be used on any complex expression,
the type of cast that may be applied is severely restricted.
Conversions on complex expressions are often a source of
confusion and it is therefore wise to be cautious."

BENEFITS
Prevents loss of data.

EXAMPLE
typedef float
typedef double
typedef long double

float32_t;
float64_t;
float128_t;

void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float64_t)(f32a + f32b);

/* Violation */

REPAIR
typedef float
typedef double
typedef long double

float32_t;
float64_t;
float128_t;

void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float32_t)(f64a + f64b);
}

/* OK - cast to narrow float type */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7

If the bitwise operators ~ and << are applied to an operand of underlying type unsigned char
or unsigned short, the result shall be immediately cast to the underlying type of the operand
[MISRA2004-10_5-3]
DESCRIPTION
"When these operators (~ and <<) are applied to small integer types
(unsigned char or unsigned short),
the operations are preceded by integral promotion,
and the result may contain high order bits which have not been
anticipated.
A similar problem exists when the << operator is used on small integer
types
and high order bits are retained."

BENEFITS
Rule prevents high order bits retaining.

EXAMPLE
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = (~port) >> 4;
*/
result_16 = ((port << 4) & mode) >> 6;
*/
}

REPAIR
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;

/* Violation
/* Violation

void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = ((uint8_t)(~port)) >> 4 ;
result_16 = (
(uint16_t) (~(uint16_t)port)
) >> 4 ;
result_16 = ((uint16_t)((uint16_t)port << 4) & mode) >> 6;
}

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-10

A 'U' suffix shall be applied to all constants of unsigned type [MISRA2004-10_6-5]


DESCRIPTION
"The type of an integer constant is a potential source of confusion,
because it is dependent on a complex combination of factors including:
- The magnitude of the constant
- The implemented sizes of the integer types
- The presence of any suffixes
- The number base in which the value is expressed (i.e. decimal, octal or
hexadecimal)
Signedness of constants should be explicit. Consistent signedness is an
important principle in constructing well formed expressions. If a constant
is of an unsigned type, it is helpful to avoid ambiguity by applying a U
suffix. When applied to larger values, the suffix may be redundant (in the
sense that it does not influence the type of the constant); however its
presence is a valuable contribution towards clarity."
The rule checks if integer constant of unsigned type has 'U' or 'u'
suffix.
See also: MISRA-018_a, MISRA-018_b, MISRA-018_c, MISRA-018_d, MISRA200410_1_a,
MISRA2004-10_1_h

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
/* the type depends from the implemented size of the various integer types
*/
long lVar = 2147483648;
/* Violation */

REPAIR
long lVar = 2147483648U;

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. Origin: Misra Guidelines - Rule 18

Conversions shall not be performed between a pointer to a function and any type other than
an integral type [MISRA2004-11_1-3]
DESCRIPTION
"Conversion of a function pointer to a different type of pointer results
in undefined behaviour. This means that a function pointer can be
converted
to or from and integral type. No other conversion involving function
pointers
are permitted."
This rule allows conversions between two pointers to function if these
pointers
have exactly the same type.
As integral types the rule detects the following types: bool, char, short,
int, long, long long, wchar_t and typedefs to mentioned types.

BENEFITS
Prevents undefined behaviour and loss of data.

EXAMPLE
/* Examples of incorrect code */
typedef int (*func_t1)();
typedef short (*func_t2)();
void foo()
{
int (*fp1)(char* c);
func_t1 t1 ;
func_t2 t2 ;
int* ptr_int;
t1 = t2;
t1 = fp1;
t1 = (func_t2)t1;
fp1 = t2;
ptr_int = t1;
}

/*
/*
/*
/*
/*

Violation
Violation
Violation
Violation
Violation

*/
*/
*/
*/
*/

REPAIR
/* Examples of correct code */
typedef int (*func_t1)();
typedef int (*func_t2)();
int func ();

void foo()
{
func_t1 t1 ;
func_t2 t2 ;
int i;
t1 = t2;
t1 = func;
i = t1;

/* OK */
/* OK */
/* OK */

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11

Conversions shall not be performed between a pointer to object and any type other than an
integral type, another pointer to object type or a pointer to void [MISRA2004-11_2-3]
DESCRIPTION
A pointer to object can be only converted to or from:
a) an integral type
b) another pointer to object type
c) a pointer to void
See also: MISRA2004-11_2_b, MISRA2004-11_2_c

BENEFITS
Rule prevents undefined conversions.

EXAMPLE
typedef int (*FunctionPointer)(void);
struct A;
void foo(int* int_p, float fl, FunctionPointer funct_ptr) {
struct A *incomplete_type_ptr;
int_p = (int*)fl;

/* Violation - conversion between


pointer to object and floating
type */
funct_ptr = (FunctionPointer)int_p; /* Violation - conversion between
pointer to object and pointer
to function type */
int_p = incomplete_type_ptr;
/* Violation - conversion between
pointer to object and pointer
to incomplete type */
}

REPAIR
Do not perform illegal conversions.

REFERENCES

MISRA-C:2004 Guidelines for the use of the C language in critical systems


Chapter 6, Section 11

Conversions shall not be performed between a pointer to object and any type other than an
integral type, another pointer to object type or a pointer to void [MISRA2004-11_2_b-3]
DESCRIPTION
A pointer to object can be only converted to or from:
a) an integral type
b) another pointer to object type
c) a pointer to void
This rule is a complementary rule to rule MISRA2004-11_2 and reports
a violation message if illegal conversions between type of declared
function parameter and type of passed argument is found.
See also: MISRA2004-11_2, MISRA2004-11_2_c

BENEFITS
Rule prevents undefined conversions.

EXAMPLE
typedef int (*FunctionPointer)(void);
struct A;
void someFunction(int *);

void foo(FunctionPointer funct_ptr)


{
struct A *incomplete_type_ptr;
someFunction(incomplete_type_ptr); /* Violation - conversion between
pointer to object and pointer
to incomplete type */
someFunction(funct_ptr);
/* Violation - conversion between
pointer to object and pointer
to function type
*/
}

REPAIR

Do not perform illegal conversions.

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11

Conversions shall not be performed between a pointer to object and any type other than an
integral type, another pointer to object type or a pointer to void [MISRA2004-11_2_c-3]
DESCRIPTION
A pointer to object can be only converted to or from:
a) an integral type
b) another pointer to object type
c) a pointer to void
This rule is a complementary rule to rule MISRA2004-11_2 and reports
a violation message if illegal conversions between function return
type and type of returned expression is found.
See also: MISRA2004-11_2, MISRA2004-11_2_b

BENEFITS
Rule prevents undefined conversions.

EXAMPLE
typedef int (*FunctionPointer)(void);
struct A;
int* someFunction(FunctionPointer funct_ptr, int flag)
{
struct A *incomplete_type_ptr;
if(flag)
{
return incomplete_type_ptr;

}else{
return funct_ptr;

}
}

/* Violation - conversion between


pointer to object and pointer
to incomplete type */
/* Violation - conversion between
pointer to object and pointer
to function type */

REPAIR
Do not perform illegal conversions.

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11

A cast should not convert a pointer type to an integral type [MISRA2004-11_3_a-3]


DESCRIPTION
"The size of integer that is required when a pointer is converted to an
integer
is implementation-defined. Casting between a pointer and an integer type
should
be avoided where possible, but may be unavoidable when addressing memory
mapped
registers or other hardware specific features."

EXCEPTIONS
The rule allows to cast to UINT_PTR or INT_PTR type. These types are
integral
types that scale to the size of a pointer for both 32-bit and 64-bit
Windows.

BENEFITS
Prevents undefined or implementation-defined behaviour.

EXAMPLE
void foo( ) {
int* pi;
int i;
i = (int) pi;
}

// Violation

REPAIR
Do not cast pointers to non-pointers.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 11
2. Misra Guidelines rule 45
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 7
4. http://msdn2.microsoft.com/en-gb/library/aa489560.aspx
5. http://www.codeproject.com/system/64BitOSAndPortingIssues.asp
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
7. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-9
8. ISO/DIS 26262
point 8.4.4

A cast should not convert an integral type to a pointer type [MISRA2004-11_3_b-3]


DESCRIPTION
Integral types shall not be cast to pointers. Problems can arise when
an arbitrary integer is converted to a pointer.

EXCEPTIONS
The rule allows to cast integer constant '0' to pointer type.

BENEFITS
Rule prevents undefined or implementation-defined behaviour.

EXAMPLE
void foo( ) {
int* pi;
int i;
pi = (int*)i;
}

// Violation

REPAIR
Do not cast non-pointers to pointers.

REFERENCES
1. Origin: Misra Guidelines rule 45
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
4. ISO/DIS 26262

point 8.4.4

A cast should not be performed between a pointer to object type and a different pointer to
object type [MISRA2004-11_4-3]
DESCRIPTION
"A cast should not be performed between a pointer to object type and a
different
pointer to object type. Conversions of this type may be invalid if the new
pointer type requires a stricter alignment.
Pointer types can be classified as follows:
- Pointer to object
- Pointer to function
- Pointer to void
- The null pointer constant (the value 0 cast to type void *)"

NOTES
Pointers which are different only const or volatile qualifier are not
checked
by this rule.

BENEFITS
Prevents incorrect pointer alignment.

EXAMPLE
void foo( )
{
unsigned int* ui;
signed char* sc;
/* Examples of incorrect code */
ui = (unsigned int*) sc;
ui = (unsigned int*) &sc;
}

REPAIR

/* Violation */
/* Violation */

typedef unsigned int uint32_t;


void foo( )
{
unsigned int* ui;
uint32_t* ui_t;
/* Examples of correct code */
ui = (unsigned int*) ui_t;
ui = (unsigned int* const) ui_t;

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
2. Origin: Misra Guidelines rule 45
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-7
4. ISO/DIS 26262
point 8.4.4

A cast shall not be performed that removes any const or volatile qualification from the type
addressed by a pointer [MISRA2004-11_5-3]
DESCRIPTION
"Any attempt to remove the qualification associated with the addressed
type by
using casting is a violation of the principle of type qualification.
Notice that the qualification referred to here is not the same as any
qualification that may be applied to the pointer itself."

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
typedef unsigned short uint16_t;
void foo( )
{
uint16_t *pi, **ppi;
uint16_t * const * pcpi; /* pointer
const uint16_t * * ppci; /* pointer
const uint16_t * pci;
/* pointer
volatile uint16_t * pvi; /* pointer
pi = (uint16_t *)pci;
pi = (uint16_t *)pvi;
ppi = (uint16_t * *)pcpi;
ppi = (uint16_t * *)ppci;

/*
/*
/*
/*

to
to
to
to

Violation
Violation
Violation
Violation

const pointer */
pointer to const */
const */
volatile */
*/
*/
*/
*/

REPAIR
Do not cast from 'const' or 'volatile' type addressed by a pointer to
'non-const'
or 'non-volatile' type.

REFERENCES

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 11
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-5

The comma operator shall not be used [MISRA2004-12_10-3]


DESCRIPTION
"Use of the comma operator is generally detrimental to the readability of
code,
and the same effect can be achieved by other means."
See also: misra-042

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int x, y;
x = 0, y = 0;
}

// Violation

REPAIR
void foo() {
int x, y;
x = 0;
y = 0;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-18-1

The underlying bit representations of floating-point values shall not be used [MISRA200412_12-3]
DESCRIPTION
"The storage layout used for floating-point values may vary from one
compiler to
another, and therefore no floating-point manipulations shall be made which
rely
directly on the way the values are stored. The in-built operators and
functions,
which hide the storage details from the programmer, should be used."

NOTES
In many cases floating point bit fields will be flagged as syntax errors.

BENEFITS
Prevents implementation-defined behaviour.

EXAMPLE
struct S {
float f:6; // Violation
};
union U {
float f:6; // Violation
};

REPAIR
struct S {
int f:6; // OK
};
union U {
int f:6; // OK
};

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 3-9-3

The increment (++) and decrement (--) operators should not be mixed with other operators in
an expression [MISRA2004-12_13-3]
DESCRIPTION
"It is the intention of the rule that when the increment or decrement
operator
is used, it should be the only side-effect in the statement.
The use of increment and decrement operators in combination with other
arithmetic operators is not recommended because:
- It can significantly impair the readability of the code
- It introduces additional side effects into a statement with the
potential for
undefined behaviour
It is safer to use these operations in isolation from any other arithmetic
operators."

BENEFITS
Improves readability and maintainability.
Reduces risk of potential undefined behaviour
caused by additional side effects

EXAMPLE
void foo() {
int x, y;
x = --y + x++;
}

/* Violation */

REPAIR
void foo() {
int x, y;
--y;
x = y + x;
x++;
}

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-10

Limited dependence should be placed on C's operator precedence rules in expressions


[MISRA2004-12_1_a-3]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
Parentheses are required for the right-hand operand because the right-hand
side itself contains an assignment expression.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int a, b;
b = a = 0;// Violation
}

REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C's operator precedence rules in expressions


[MISRA2004-12_1_b-5]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it.
It is easy to make a mistake with the rather complicated precedence rules
of C,
and this approach helps to avoid such errors, and helps to make the code
easier
to read. However, do not add too many parentheses so as to clutter the
code and
make it unreadable."
"No parentheses are required for the right-hand operand of an assignment
operator unless the right-hand side itself contains an assignment
expression."

NOTES
Macro's body is excluded from checking.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int a, b;
b = (a = 0);// OK
b = (a + 0);// Violation
}

REPAIR
void foo() {
int a, b;

b = (a = 0);// OK
b = a + 0;// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

No parentheses are required for the operand of a unary operator [MISRA2004-12_1_c-5]


DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
The rule detects parentheses which are not required for the operand
of a unary operator.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( )
{
int a, b;
b = a * (-1);
}

// Violation

REPAIR
void foo( )
{
int a, b;
b = a * -1;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C's operator precedence rules in expressions


[MISRA2004-12_1_d-3]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
"If all operators are the same, parentheses may be used to control the
order of
operation. Some operators (e.g. addition and multiplication) that are
associative in algebra are not necessarily associative in C. Similarly,
integer
operations involving mixed types (prohibited by several rules) may produce
different results because of the integral promotions. The following
example
written for a 16-bit implementation demonstrates that addition is not
associative and that it is important to be clear about the structure of an
expression:"

SINCE
v7.0

BENEFITS
Rule increases safety in arithmetic operations.

EXAMPLE
#ifdef _MSC_VER
typedef unsigned __int16 uint16;

typedef unsigned __int32 uint32;


#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus( ) {
uint16 a = 10;
uint16 b = 65535;
uint32 c = 0;
uint32 d;
d = (a + b) + c; /* Violation d is 9; a + b wraps modulo 65536 */
}
void fooMultiply( ) {
uint16 a = 10;
uint16 b = 65535;
uint32 c = 0;
uint32 d;
d = (a * b) * c; /* Violation d is 65526; a * b wraps modulo 65536 */
}

REPAIR
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus(
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a + (b
}

) {
10;
65535;
0;
+ c); /* OK d is 65545 */

void fooMultiply( ) {

uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a * (b

10;
65535;
0;
* c); /* OK d is 655350 */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Use parentheses unless all operators in the expression are the same [MISRA2004-12_1_e-3]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it unreadable.
Use parentheses unless all operators in the expression are the same."
See also: MISRA2004-12_5, CODSTA-90

NOTES
The operands of a logical && and || are checked by the rule MISRA2004-12_5

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( ) {
int a, b;
b = a * a + a;
}

// Violation

REPAIR
void foo( ) {
int a, b;
b = (a * a) + a;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C's operator precedence rules in expressions


[MISRA2004-12_1_f-5]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
If parentheses are nested too deeply then you may hit a translation limit
but
if this happens the expression is probably too complicated anyway and
should be
split. The rule checks the number of nested parentheses - if the nesting
level
exceeds 10 rule reports a violation message.

Note:
Nested parentheses level is set on 10 but can be changed. To change the
default level of the nested parentheses modify the main "Count" expression
of the rule (Collector A) from "$$ > 9" to "$$ > N" using desired
threshold
value for N. Rule's header should be also changed accordingly.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( )
{
int a, b,c,d;
a=(((((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8)/(b+d))+3; // Violation

REPAIR
void foo( )
{
int a, b,c,d;
int h;
h = (((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8;
a =(h*(b+d))+3;
}

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2004-12_2_a-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
As an example of what can go wrong, consider x = b[i] + i++; This will
give
different results depending on whether b[i] is evaluated before i++ or
vice
versa. The problem could be avoided by putting the increment operation
in a separate statement."
The rule reports a violation if a variable is used and
incremented/decremented
in the same statement.
See also: MISRA2004-12_4_a, MISRA2004-12_4_b

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo( )
{
int a, b[10];
a = b[a] + a++; // Violation
}

REPAIR
void foo( )
{
int a, b[10];

a = b[a] + a;
a++;

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

Don't write code that depends on the order of evaluation of function arguments [MISRA200412_2_b-1]
DESCRIPTION
The order of evaluation of function arguments is unspecified. This means
that
if arguments contain side effects then the order in which side effects
take
place is unspecified. A function call can give different results depending
on which of the function's arguments is evaluated first.
By side effect we understand accessing a volatile object, modifying an
object
or calling a function that does any of those operations.
Rule checks calls of functions that have at least two arguments.
A violation is reported if
* a volatile object is read or modified, or
* a non-volatile object is modified
during evaluation of a function argument and the same object is read or
modified during evaluation of function's other argument.

EXCEPTIONS
Only one level of function calls is checked.

BENEFITS
Rule prevents writing source code which might produce different results
between compilers.

EXAMPLE
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
Transmogrify(Bump(count),Bump(count)); // Violation
Transmogrify(count++,count);
// Violation

REPAIR
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
int temp1 = Bump(count);
Transmogrify(temp1,Bump(count)); // OK
Transmogrify(count,count);
// OK
count++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 31
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
5. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2004-12_2_c-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur. Those points in the evaluation of
an
expression at which all previous side effects can be guaranteed to have
taken
place are called sequence points. Sequence points and side effects are
described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].
Note that the order of evaluation problem is not solved by the use of
parentheses, as this is not a precedence issue."
"If a function is called via a function pointer there shall be no
dependence on
the order in which function designator and function arguments are
evaluated.
p->task_start_fn(p++);"

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p++ );
}

// Violation

REPAIR
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p );
p++;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

Don't write code that depends on the order of evaluation of expression that involves a
function call [MISRA2004-12_2_d-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
Rule reports a violation if in an expression a function is called that
takes as
an argument a pointer or a reference to a non-const variable and modifies
this
variable, and in the same expression the variable is used in some other
way.

NOTES
Rule assumes that a variable is modified in function if it is directly
modified
by assignment or body of function is not defined in current translation
unit.

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
int foo(int* ptr)
{

(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
i = foo(&j) + bar(j);
}

// Violation

REPAIR
int foo(int* ptr)
{
(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
int temp = foo(&j);
i = temp + bar(j);
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2004-12_2_e-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Assignments nested within expressions cause additional side effects. The
best
way to avoid any chance of this leading to a dependence on order of
evaluation
is to not embed assignments within expressions."

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo( int x, int y, int z ) {
x = y = z / 3; // Violation
}

REPAIR
void foo( int x, int y, int z ) {
y = z / 3; // OK
x = y;
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

Do not use more than one volatile in one expression [MISRA2004-12_2_f-3]


DESCRIPTION
"The volatile type qualifier is provided in C to denote objects whose
value can
change independently of the execution of the program (for example an input
register). If an object of volatile qualified type is accessed this may
change
its value. C compilers will not optimise out reads of a volatile. In
addition,
as far as a C program is concerned, a read of a volatile has a side effect
(changing the value of the volatile). It will usually be necessary to
access
volatile data as part of an expression, which then means there may be
dependence
on order of evaluation. Where possible though it is recommended that
volatiles
only be accessed in simple assignment statements."
The rule reports a violation if in one expression is used more than one
volatile.
See also: MISRA2004-12_2_b

SINCE
v7.0

NOTES
Rule does not report violation if in a function call are used as arguments
more than one volatile. In this case should be used rule MISRA2004-12_2_b.
void goo(int, int);
void foo()
{
volatile int v;
goo(v, v); // Violation - MISRA2004-12_2_b
}

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo( )
{
volatile int x;
int y;
y = x * x; // Violation
}

REPAIR
void foo( )
{
volatile int x;
int y;
y = x;
// OK
y = y * y;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

Don't write code that depends on the order of evaluation of function calls [MISRA2004-12_2_g3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
The rule reports a violation if in one expression are called two functions
that
use the same global or static variable and at least one function modifies
this
variable.

EXCEPTIONS
Only one level of function calls is checked.

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
int global;
int modify_global()
{
global++;

return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global() + use_global();
}

// Violation

REPAIR
int global;
int modify_global()
{
global++;
return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global();
a += use_global();
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The sizeof operator shall not be used on expressions that contain side effects [MISRA200412_3-3]
DESCRIPTION
"A possible programming error in C is to apply the sizeof operator to an
expression and expect the expression to be evaluated. However the
expression
is not evaluated: sizeof only acts on the type of the expression. To avoid
this
error, sizeof shall not be used on expressions that contain side effects,
as the side effects will not occur."
"The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."

NOTES
Rule checks only three nested level of function calls.

EXCEPTIONS
An operand of the form sizeof(i) where i is volatile is permitted.

BENEFITS
Prevents error that are caused by believing that operand of sizeof is
evaluated.

EXAMPLE
int glob;
int fun_with_se(){
glob++; // side-effect
return glob;
}
void foo1(int i){

int
j =
l =
m =

j, k, l, m;
sizeof(k = 2);
// Violation - k is not set to 2
sizeof(i++);
// Violation - i is not incremented
sizeof(fun_with_se()); // Violation - glob is not incremented

REPAIR
int fun_without_se(){
// no side-effect
return 1;
}
void foo1(int i){
int j, k, l, m, n, o;
volatile int vol;
k = 2;
j = sizeof(k);
i++;
l = sizeof(i);
// examples of correct code
m = sizeof(fun_without_se());
n = sizeof(int);
o = sizeof(vol);
}

// OK
// OK
// OK
// OK
// OK - volatile objects are permitted

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 166
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-4

The right-hand operand of a logical && or || operator shall not contain side effects
[MISRA2004-12_4_a-3]
DESCRIPTION
"There are some situations in C or C++ where certain parts of expressions
may
not be evaluated. If these sub-expressions contain side effects then those
side
effects may or may not occur, depending on the values of other sub
expressions.
The operators which can lead to this problem are && and || where the
evaluation
of the right-hand operand is conditional on the value of the left-hand
operand.
The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
See also: MISRA2004-12_2_a, MISRA2004-12_4_b

NOTES
Rule checks only three nested level of function calls.

BENEFITS
Rule prevents conditional evaluation of the right-hand operand that can
easily
cause problems if the developer relies on a side effect occurring.

EXAMPLE
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i++)) ; // Violation
}

REPAIR
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i)) i++; // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 33
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 157
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-14-1
5. ISO/DIS 26262
point 8.4.4

The second or third operand of a ternary operator '?:' shall not contain side effects
[MISRA2004-12_4_b-4]
DESCRIPTION
"There are some situations in C or C++ code where certain parts of
expressions
may not be evaluated. If these sub-expressions contain side effects then
those
side effects may or may not occur, depending on the values of other
sub-expressions.
The operators which can lead to this problem are &&, || and ?:. In the
case of
the ?: operator, either the second or third operands are evaluated but not
both.
The ?: operator is specifically provided to choose between two subexpressions,
and is therefore less likely to lead to mistakes."
See also: MISRA2004-12_2_a, MISRA2004-12_4_a

NOTES
Rule checks only two nested level of function calls.

BENEFITS
Rule prevents conditional evaluation of the second or third operand of
ternary
operator that can easily cause problems if the developer relies on a side
effect
occurring.

EXAMPLE
int i;
int j;
int foo( ) {
return (i > j) ? j++ : i++; // Violation - developer expects 2nd and
3rd
// operand to be evaluated
}

REPAIR
int i;
int j;
int foo( ) {
if (i > j) {
++i;
return j++;
} else {
++j;
return i++;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. ISO/DIS 26262
point 8.4.4

The operands of a logical && or || shall be primary-expressions [MISRA2004-12_5-3]


DESCRIPTION
""Primary expressions" are defined in ISO 9899:1990, section 6.3.1.
Essentially they are either a single identifier, or a constant,
or a parenthesised expression. The effect of this rule is to require
that if an operand is other than a single identifier or constant then
it must be parenthesised. Where an expression consists of either
a sequence of only logical && or a sequence of only logical ||,
extra parentheses are not required"
See also: MISRA2004-12_1_e, CODSTA-90

BENEFITS
"Parentheses are important in this situation both for readability
of code and for ensuring that the behaviour is as the programmer
intended."

EXAMPLE
int foo( int
{
if ( x ||
if ( x &&
if ( foo(
return 0;
}

x, int y, int z )
y && z );
// Violation
!y );
// Violation
x, y, z ) && x ); // Violation

REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
// OK
if ( x && ( !y ) );
// OK
if ( ( foo( x, y, z ) ) && x ); // OK
return 0;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Misra Guidelines - Rule 34

The operands of logical operators (&&, || and !) should be effectively Boolean [MISRA200412_6_a-3]
DESCRIPTION
"The operands of logical operators (&&, ||, !) should be 'effectively
Boolean'.
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule does not report violation if as an operand of logical operator is
used:
- Boolean-by-construct values
- boolean constant
- integer or enum constant defined as '0' or '1'
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types

BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.

EXAMPLE

int goo();
void foo()
{
int x, y, z;
z = (x > y) && goo();
z = (x > y) || goo();
z = !(x = y);

// Violation
// Violation
// Violation

REPAIR
int goo();
void foo()
{
int x, y, z;
z
z
x
z

=
=
=
=

(x > y) && (goo() != 0);


(x > y) || (goo() != 0);
y;
(x == 0);

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 36

Expressions that are effectively Boolean should not be used as operands to operators other
than (&&, ||, !, =, ==, !=, ?:) [MISRA2004-12_6_b-3]
DESCRIPTION
"Expressions that are effectively Boolean should not be used as operands
to operators other than (&&, ||, !, =, ==, !=, ?:).
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule reports violation if as an operand of operator
other than (&&, ||, !, =, ==, !=, ?:) is used:
- Boolean-by-construct values
- boolean constant
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types

BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.

EXAMPLE
int goo();
void foo()

{
int x, y, z;
z = (x > y) & (goo()); // Violation
z = x | (goo() != 0); // Violation
z = ~(x == y);
// Violation
}

REPAIR
int goo();
void foo()
{
int x, y, z;
int tmp;
tmp = x > y;
z = tmp & goo();

// OK

tmp = goo() != 0;
z = x | tmp;

// OK

tmp = x == y;
z = ~tmp;

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 36
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 4, Rule 4-5-1

Bitwise operators shall not be applied to operands whose underlying type is signed
[MISRA2004-12_7-3]
DESCRIPTION
"Bitwise operations (~, <<, >>, &, ^ and |) are not normally meaningful on
signed integers. Problems can arise if, for example, a right shift moves
the
sign bit into the number, or a left shift moves a numeric bit
into the sign bit.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
int foo( int x, int y )
{
x = y >> 2;
// Violation
x = y & 0x0F;
// Violation
return x | 5;
// Violation
}

REPAIR
int foo( int x, int y )
{
/* Caller must make sure x and y are not negative */
x = (unsigned int)y >> 2u;
/* OK */
x = (unsigned int)y & 0x0Fu;
/* OK */
return (unsigned int)x | 5u;
/* OK */
}

REFERENCES

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 37

The right-hand operand of a shift operator shall lie between zero and one less than the width
in bits of the underlying type of the left-hand operand [MISRA2004-12_8-3]
DESCRIPTION
"If, for example, the left-hand operand of a left-shift or right-shift is
a
16-bit integer, then it is important to ensure that this is shifted only
by a
number between 0 and 15 inclusive.
There are various ways of ensuring this rule is followed. The simplest is
for
the right-hand operand to be a constant (whose value can then be
statically
checked). Use of an unsigned integer type will ensure that the operand is
non-negative, so then only the upper limit needs to be checked
(dynamically at
run-time or by review). Otherwise both limits will need to be checked."
The rule checks right-hand operand of shift operator and reports a
violation
in following cases:
- the operand is a constant with negative value or with value that exceeds
the length (in bits) of the left-hand operand
- the operand is a non-const variable and it's value is not checked by
specific
pattern.
The specific pattern recognized by the rule requires the shift operator
to be wrapped by an 'if' statement which checks the variable's value
using
comparison operators (both "greater then" and "less then" operators must
be used).

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )

uint8_t;
uint16_t;

{
uint8_t u8a;
u8a = (uint8_t) (u8a << 9); /* Violation */
u8a = (uint8_t) (u8a << p); /* Violation */
}

REPAIR
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
{
uint8_t u8a;
uint16_t u16a;

uint8_t;
uint16_t;

u16a = (uint16_t) ((uint16_t) u8a << 9); /* OK */


if (p >= 0 && p <= 8) {
u8a = (uint8_t) (u8a << p); /* OK - p range checked */
}
u8a = (uint8_t) (u8a << 4); /* OK - constant value in range */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-8-1

The unary minus operator shall not be applied to an expression whose underlying type is
unsigned [MISRA2004-12_9-3]
DESCRIPTION
"Applying the unary minus operator to an expression of type unsigned int
or
unsigned long generates a result of type unsigned int or unsigned long
respectively and is not a meaningful operation. Applying unary minus to an
operand of smaller unsigned integer type may generate a meaningful signed
result
due to integral promotion, but this is not good practice."

BENEFITS
Prevents unexpected result due to integral promotion.

EXAMPLE
void foo() {
unsigned char ui1;
signed short si2;
si2 = -ui1;
}

// Violation

REPAIR
void foo() {
unsigned char ui1;
signed short si2;
si2 = -(signed short) ui1;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12

2. Origin: Misra Guidelines - Rule 39


3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 165
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-2

Assignment operators shall not be used in expressions that yield a Boolean value
[MISRA2004-13_1-3]
DESCRIPTION
"No assignments are permitted in any expression which is considered to
have a
Boolean value. This precludes the use of both simple and compound
assignment
operators in the operands of a Boolean-valued expression. However, it does
not
preclude assigning a Boolean value to a variable. If assignments are
required
in the operands of a Boolean-valued expression then they must be performed
separately outside of those operands. This helps to avoid getting "=" and
"=="
confused, and assists the static detection of mistakes."

NOTES
An expression is considered to represent a Boolean value either because
it appears in a position where a Boolean value is expected or because it
uses an operator that gives rise to a Boolean value. Boolean values are
expected in the following contexts:
- the controlling expression of an if statement
- the controlling expression of an iteration statement
- the first operand of the conditional operator ?

BENEFITS
Rule prevents getting "=" and "==" confused.

EXAMPLE
void foo()
{
int x;
int y;
int z;
z = !(x = y);

// Violation

if ((x > y) && (x = 4));


if (!(x = y));

// Violation
// Violation

REPAIR
void foo()
{
int x;
int y;
int z;
z = !(x == y);
// OK
if ((x > y) && (x == 4)); // OK
if (!(x == y));
// OK
}

REFERENCES
1. Misra Guidelines - Rule 35
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 160
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-1

Tests of a value against zero should be made explicit, unless the operand is effectively
Boolean [MISRA2004-13_2-3]
DESCRIPTION
"Where a data value is to be tested against zero then the test should be
made
explicit. The exception to this rule is when data represents a Boolean
value,
even though in C this will in practice be an integer."
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule does not report violation if as an operand of logical operator is
used:
- Boolean-by-construct values
- boolean constant
- integer or enum constant defined as '0' or '1'
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types

NOTES
Rule does not report violations on constant expressions.

BENEFITS
"This rule is in the interests of clarity, and makes clear the distinction
between integers and logical values."

EXAMPLE
int goo()
{
return 1;
}
void foo( int x, int y )
{
if (goo()) {}// Violation
if (y) {}
// Violation
}

REPAIR
int goo()
{
return 1;
}
void foo( int x, int y )
{
if (goo() != 0) {}// OK
if (y != 0) {}
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 49

Floating-point expressions shall not be tested for equality or inequality [MISRA2004-13_3-3]


DESCRIPTION
"Floating-point expressions shall not be tested for equality or
inequality.
The recommended method for achieving deterministic floating-point
comparisons is
to write a library that implements the comparison operations. The library
should
take into account the floating-point granularity (FLT_EPSILON) and the
magnitude
of the numbers being compared."

NOTES
Rule does not detect indirect tests of equality and inequality which are
equally
problematic and are also forbidden by Misra standard:
if ( ( x <= y ) && ( x >= y ) )
{
/* ... */
}

BENEFITS
"The inherent nature of floating-point types is such that comparisons of
equality will often not evaluate to true even when they are expected to.
In
addition the behaviour of such a comparison cannot be predicted before
execution, and may well vary from one implementation to another. "

EXAMPLE
void foo() {
float x, y;
if (x == y);
if (x == 0.0f);
}

// Violation
// Violation

REPAIR
void foo( float epsilon ) {
float x, y;
if (x - epsilon <= y && y <= x + epsilon);
if (-epsilon <= x && x <= epsilon);

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 50
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 202
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-2

The controlling expression of a for statement shall not contain any objects of floating type
[MISRA2004-13_4-3]
DESCRIPTION
"The controlling expression may include a loop counter, whose value is
tested to
determine termination of the loop. Floating-point variables shall not be
used
for this purpose. Rounding and truncation errors can be propagated through
the
iterations of the loop, causing significant inaccuracies in the loop
variable,
and possibly giving unexpected results when the test is performed. For
example
the number of times the loop is performed may vary from one implementation
to
another, and may be unpredictable."

BENEFITS
Rule prevents unpredictable behaviour.

EXAMPLE
void foo( float max ) {
float y;
for (y = 0; y < max; y++);
}

// Violation

REPAIR
void foo( int max ) {
int y;
for (y = 0; y < max; y++);
}

// OK

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 13

The three expressions of a for statement shall be concerned only with loop control
[MISRA2004-13_5-3]
DESCRIPTION
"When present, the three expressions of a for statement shall be used only
for these purposes:
- First expression - Initialising the loop counter (i in the following
example)
- Second expression - Shall include testing the loop counter (i), and
optionally
other loop control variables (flag)
- Third expression - Increment or decrement of the loop counter (i)"
This rule analyzes for statements to find any variables that are used
within
initialization or update sections of the statements, but do not seem to be
concerned with loop control. Often, variables are initialized within the
for
statement even though they have nothing to do with stop condition of the
loop.
In extreme cases entire for statement blocks can be moved into the for
statement, which makes the code both error-prone and hard to read.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
void foo( )
{
int x, j;
for ( x = 5; j < 2 ; x++ );
for ( x = 5; x < 2 ; j++ );
}

REPAIR
void foo( )
{

// Violation
// Violation

int x, j;
for ( x = 5; x < 2; x++);

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 66

Do not modify for loop counter within a body of the loop [MISRA2004-13_6-3]
DESCRIPTION
"Loop counters shall not be modified in the body of the loop.
However other loop control variables representing logical values
may be modified in the loop, for example a flag to indicate that something
has been completed, which is then tested in the for statement."

NOTES
A
-

loop-counter is a loop-control-variable that is:


Initialized in, or prior to, for-init-statement; and
an operand to a relational operator in condition; and
modified in expression.

BENEFITS
Modification 'for' loop counter within a body of the loop can lead to
errors and confusion.

EXAMPLE
void foo( ) {
int i;
for ( i = 0; i < 5; i++ ) {
i = i + 3;
}
}

/* Violation */

REPAIR
void foo( ) {
int i;
for ( i = 0; i < 5; i = i + 3 ) {} /* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 67
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 201
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-5-3

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_a-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a <= 1)&&(a >= 2));
if((a < 1)&&(a > 2));
if((a >= 2)&&(a <= 1));
if((a > 2)&&(a < 1));
}

//
//
//
//

Violation
Violation
Violation
Violation

//
//
//
//

OK
OK
OK
OK

REPAIR
void myFunction(int a)
{
if((a <= 5)&&(a >= 2));
if((a < 5)&&(a > 2));
if((a >= 2)&&(a <= 5));
if((a > 2)&&(a < 5));
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_aa-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b >= 2)
if(b < 2) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b >= 2)
if(b < 7) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ab-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b < 2)
if(b >= 2) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b < 2)
if(b >= 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ac-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b <= 2)
if(b < 3) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b <= 2)
if(b < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ad-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b == 2)
if(b < 1) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b == 2)
if(a < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ae-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 > b)
if(b < 5) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 > b)
if(b < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_af-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 >= b)
if(b < 5) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 >= b)
if(b < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ag-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 < b)
if(b > 1) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 < b)
if(b > 5) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ah-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 <= b)
if(b > 1) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 <= b)
if(b > 5) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ai-3]
DESCRIPTION
The rule reports violation if a result of boolean operation with unsigned
variable is always true or always false.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunc()
{
unsigned int a;
if (a >= 0)
// Violation
a++;
}

REPAIR
void myFunc()
{
unsigned int a;
if (a >= 2)
// OK
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_aj-3]
DESCRIPTION
The rule reports violation if a result of boolean operation with variable
of char type is always true or always false.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 128)
b++;
if (a < 256)
a++;

// Violation
// Violation

REPAIR
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 127)
b++;
if (a < 255)
a++;
}

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ak-3]
DESCRIPTION
The rule reports violation if a result of boolean operation with variable
of short type is always true or always false.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65536)
a++;
if (b <= 32767)
b++;

// Violation
// Violation

REPAIR
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65535)
a++;
if (b <= 32766)
b++;
}

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_b-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > -1)&&(a < -2));
if((a >= -1)&&(a <= -2));
if((a < -2)&&(a > -1));
if((a <= -2)&&(a >= -1));
}

//
//
//
//

Violation
Violation
Violation
Violation

//
//
//
//

OK
OK
OK
OK

REPAIR
void myFunction(int a)
{
if((a > -5)&&(a < -2));
if((a >= -5)&&(a <= -2));
if((a < -2)&&(a > -5));
if((a <= -2)&&(a >= -5));
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_c-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > 0)&&(a < -1));
if((a < -1)&&(a >= 0));
if((a == -5)&&(a == 5));
if((3 < a)&&(-3 > a));
}

//
//
//
//

Violation
Violation
Violation
Violation

//
//
//
//

OK
OK
OK
OK

REPAIR
void myFunction(int a)
{
if((a < 0)&&(a > -1));
if((a > -1)&&(a <= 0));
if((a != -5)&&(a != 5));
if((3 > a)&&(-3 < a));
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_d-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a, int b)
{
if((a > b)&&(a < b));
// Violation
if((a < b)&&(a >= b)); // Violation
}

REPAIR
void myFunction(int a, int b, int c)
{
if((a > b)&&(a < c));
// OK
if((a < b)&&(a >= c)); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_j-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a >= 0)||(a < 0));
if((5 > a)||(a > 3));
if((a <= 4)||(a >= 3));
}

// Violation
// Violation
// Violation

REPAIR
void myFunction(int a)
{
if((a >= 10)||(a < 0));
if((5 > a)||(a > 13));
if((a <= 4)||(a >= 13));
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_k-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > -4)||(a < -3));
if((-1 > a)||(-3 < a));
if((a < -3)||(-5 < a));
}

// Violation
// Violation
// Violation

REPAIR
void myFunction(int a)
{
if((a > -4)||(a < -13));
if((-11 > a)||(-3 < a));
if((a < -13)||(-5 < a));
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_l-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > -2)||(a < 1));
if((4 > a)||(-3 < a));
if((a > -4)||(2 > a));
}

// Violation
// Violation
// Violation

REPAIR
void myFunction(int a)
{
if((a < -2)||(a > 1));
if((4 < a)||(-3 > a));
if((a < -4)||(2 < a));
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_m-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a, int b)
{
if((a >= b)||(a <= b)); // Violation
if((a < b)||(a >= b));
// Violation
}

REPAIR
void myFunction(int a, int b, int c)
{
if((a >= b)||(a <= c));
// OK
if((a < c)||(a >= b));
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_n-3]
DESCRIPTION
The rule reports a violation if equality operators (== and !=) or
relational
operators (<, >, <= and >=) as both operands use only constant values
or the same variable.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE > 0);
if(10 <= ONE);
if(ci > 0);
for(i = 5; i < i; i++);
if(ZERO > 10 && i > 3);
}

//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE);
for(i = 5; i < ci; i++);
if(ZERO == en);
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_s-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < GREEN); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < RED); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_t-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > YELLOW); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > RED); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_u-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(YELLOW < col); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN < col); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_v-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN > col); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(BLUE > col); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_w-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1

< 0);
< 16);
<= 15);
<= 16);
> 15);
> 16);
>= 0);
>= 16);

//
//
//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation

REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1

< 1);
< 15);
<= 0);
<= 1);
> 0);
> 1);
>= 1);

//
//
//
//
//
//
//

OK
OK
OK
OK
OK
OK
OK

if(col1 >= 15); // OK


}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_x-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(15 < col1);
if(16 < col1);
if(0 <= col1);
if(16 <= col1);
if(0 > col1);
if(16 > col1);
if(15 >= col1);
if(16 >= col1);
}

//
//
//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation

REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(0 < col1);
if(1 < col1);
if(1 <= col1);
if(15 <= col1);
if(1 > col1);
if(15 > col1);
if(0 >= col1);

//
//
//
//
//
//
//

OK
OK
OK
OK
OK
OK
OK

if(1 >= col1);


}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_y-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 14 );
if(col1 != 14 );
if(14 == col1);
if(14 != col1);

//
//
//
//

Violation
Violation
Violation
Violation

REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 15);
if(col1 != 15);
if(15 == col1);
if(15 != col1);

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_z-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int b)
{
if(b > 2)
if(b >= 1)
/* Violation */
b++;
}

REPAIR
void foo(int b)
{
if(b > 2)
if(b >= 5)
/* OK */
b++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

All 'if...else-if' constructs shall be terminated with an 'else' clause [MISRA2004-14_10-3]


DESCRIPTION
"This rule applies whenever an 'if' statement is followed by one or more
'else-if' statements; the final 'else-if' shall be followed by an 'else'
statement. In the case of a simple 'if' statement then the 'else'
statement
need not be included.
The requirement for a final 'else' statement is defensive programming.
The 'else' statement should either take appropriate action or contain
a suitable comment as to why no action is taken."
See also: CODSTA-23

BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.

EXAMPLE
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
}

// Violation

REPAIR
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}

// OK

else
{
// comment or action
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 60
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 192
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-2

There shall be no unreachable code in "else" block [MISRA2004-14_1_a-3]


DESCRIPTION
There shall be no unreachable code in "else" statement.
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
See also: MISRA2004-14_1_b, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo(int a, int b)
{
if(a == a){
a = a + b;
}
else{
// Violation
a = a - b;
}
}

REPAIR
void foo(int a, int b)
{
if(a == 3){
a = a + b;
}

else{
a = a - b;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code after 'return', 'break', 'continue', and 'goto' statements
[MISRA2004-14_1_b-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code after 'return', 'break',
'continue' and 'goto' statements.
See also: MISRA2004-14_1_a, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// Violation
foo();
case 2:
j = 3;
return j; // Violation
foo();
}
}

REPAIR
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// OK
case 2:
j = 3;
return j; // OK
}
foo();
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code in "if/else/while/for" block [MISRA2004-14_1_c-3]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code inside if/while/for/else block if in a
condition
a constant value is used.
See also: The groups of rules MISRA2004-14_1 and MISRA2004-13_7

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo()
{
int unreachable_code = 1;
if(0)
{
unreachable_code = 2;
}
}

// Violation

REPAIR
There shall be no unreachable code

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code in switch statement [MISRA2004-14_1_d-3]


DESCRIPTION
There shall be no unreachable code in "switch" statement.
Rule detects statements, expressions placed outside case and default body.
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo( int i ) {
switch (i) {
// Violation
i = 0;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}

REPAIR
void foo( int i ) {
switch (i) {
// OK
case 0:
i = 0;
break;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code in 'for' loop [MISRA2004-14_1_e-3]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation if a 'for' loop contains in condition single
relational expression 'VAR < FB', 'VAR <= FB', 'FB > VAR', 'FB >= VAR'
that result is always false, where FB is a constant or a const variable
and VAR is a variable assigned in for-init-statement.
If a result of for-condition is always false then a body is never
executed.
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_f, MISRA2004-14_1_g

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo( int i, int j )
{
for ( i = 0; i < 0; i++ )
{
j = 1;
}
}

// Violation

REPAIR
void foo( int i, int j )
{
for ( i = 0; i < 5; i++ )
{
j = 1;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code after 'if' or 'switch' statement [MISRA2004-14_1_f-3]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation if:
- the code is after 'if/else' construction, where each branch has
unconditional
'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_g

SINCE
v7.0

NOTES
This rule does not report violations on the code inside loop.
Rule MISRA2004-14_1_g reports violations on the code inside loop.

BENEFITS
Rule helps avoid useless code.

EXAMPLE
int foo1( int c ) {
if ( c > 2 ) {

// Violation

return 0;
} else {
return 1;
}
return c;

// unreachable code

}
int foo2( int i ) {
switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return 2;
}
return i;
}

// Violation

// unreachable code

REPAIR
int foo1( int
if ( c > 2
return
} else {
return
}
}

c ) {
) {
0;

// OK

c;

int foo2( int i ) {


switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return i;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

There shall be no unreachable code after "if" or "switch" statement inside while/for/do...while
loop [MISRA2004-14_1_g-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation on the code inside loop if:
- the code is after 'if/else' construction, where each branch has
unconditional
'break', 'continue' or 'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_f

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
int foo( int c ) {
while ( c > 1 ) {
if ( c > 2 ) {
continue;
} else {
break;
}

// Violation

c++;

// unreachable code

}
for (int i = 0; i > 1; i++ ) {
switch(i){
// Violation
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}
c++;
// unreachable code
}
return c;
}

REPAIR
int foo( int c ) {
while ( c > 1 ) {
c++;
if ( c > 2 ) {
continue;
} else {
break;
}
}

// OK

for (int i = 0; i > 1; i++ ) {


c++;
switch(i){
// OK
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}

}
return c;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

All non-null statements shall either have at least one side-effect however executed or cause
control flow to change [MISRA2004-14_2-3]
DESCRIPTION
"Any statement (other than a null statement) which has no side effect and
does
not result in a change of control flow will normally indicate a
programming
error, and therefore a static check for such statements shall be
performed."
A side effect and null statement are defined by ISO/IEC 9899:1999
standard.
"Accessing a volatile object, modifying an object, modifying a file,
or calling a function that does any of those operations are all side
effects,
which are changes in the state of the execution environment."
"A null statement (consisting of just a semicolon) performs no
operations."
For example, if an expression evaluation result is not used, because
a programmer forgot to use assignment operator to store the value,
or because he accidentally wrote "==" instead of "=", the statement
is considered not to have a side effect. Such programming errors
are potentially disastrous.

NOTES
Empty function body is not considered as violating this rule.
For purposes of this rule any function call is considered as
having side effects, even if no variable is modified as a result
of the function call.
The rule does not report violations on empty blocks.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE

struct tagStruct {
int _iField;
char * _p;
};
int bar( );
void foo( ) {
int i = 0;
struct tagStruct s, *ps;
/* Examples of incorrect code - no side effects: */
i + 3;
/* Violation - result not
3;
/* Violation - result not
i;
/* Violation - result not
i + bar();
/* Violation - result not
ps->_p + s._iField;
/* Violation - result not
ps->_iField << s._iField; /* Violation - result not
*(ps->_p);
/* Violation - result not
}

used
used
used
used
used
used
used

REPAIR
struct tagStruct{
int _iField;
char * _p;
};
volatile struct tagStruct volStr;
int bar( );
void foo( ) {
int i = 0;
volatile int j = 0;
struct tagStruct s, *ps;
/* Examples of correct code - with side effects: */
i = i + 3;
/* OK - assignment */
i <<= 3;
/* OK - assignment */
bar();
/* OK - function call */
j;
/* OK - volatile variable */
volStr._p;
/* OK - volatile variable */

*/
*/
*/
*/
*/
*/
*/

if(ps->_iField){}

/* OK - cause control flow to change */

;
{}

/* OK - null statement */
/* OK - empty block */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
system
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 53
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 187

Null statement shall only occur on a line by itself or it may be followed by a comment
[MISRA2004-14_3-3]
DESCRIPTION
"Null statements should not normally be deliberately included, but where
they
are used they shall appear on a line by themselves.
White-space characters may precede the null statement to preserve
indentation.
If a comment follows the null statement then at least one white-space
character
shall separate the null statement from the comment.
The use of a white-space character to separate the null statement from any
following comment is required on the grounds that it provides an important
visual cue to reviewers."
See also: MISRA-054.

BENEFITS
"Following this rule enables a static checking tool to
warn of null statements appearing on a line with other text,
which would normally indicate a programming error."

EXAMPLE
void foo()
{
/* Violation */ ;
;/* Violation */
}

REPAIR
void goo()
{
/* OK */
;

; /* OK */
;
/* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-3

The goto statement shall not be used [MISRA2004-14_4-3]


DESCRIPTION
The goto statement shall not be used.

BENEFITS
The goto statement can lead to errors and confusion.

EXAMPLE
int foo( int a ) {
if (a < 0) {
goto end;
}
a = foo(a-1);
end:
return a+1;
}

/* Violation */

REPAIR
int foo( int a ) {
/* Code was changed and does not use goto anymore */
if (a >= 0) {
a = foo(a-1);
}
return a+1;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 49

3. Misra Guidelines - Rule 56


4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 189
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1
6. HIS Source Code Metriken, version 1.3.1
Metrik "GOTO"
7. ISO/DIS 26262
point 8.4.4

The continue statement shall not be used [MISRA2004-14_5-3]


DESCRIPTION
"Avoid the use of continue. continue can be used to exit from loops.
However, code may be more comprehensible by using an else clause instead."

BENEFITS
Rule prevents using 'continue' which can lead to errors and confusion.

EXAMPLE
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
continue;
}
i /= 2;
}
}

/* Violation */

REPAIR
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
/* OK - code was changed and does not use continue anymore */
} else {
i /= 2;
}
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rec. 53
3. Origin: Misra Guidelines - Rule 57
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 190
5. ISO/DIS 26262
point 8.4.4

For any iteration statement there shall be at most one break statement used for loop
termination [MISRA2004-14_6-3]
DESCRIPTION
"For any iteration statement there shall be at most one break statement
used
for loop termination. One break statement is allowed in a loop since this
allows, for example, for dual outcome loops or for optimal coding."

BENEFITS
"This rules is in the interests of good structured programming."

EXAMPLE
void foo( ) {
int a;
for (a = 0; a < 10; a++) { /* Violation */
if (a == 5) {
break;
}
if (a == 7) {
break;
}
}
}

REPAIR
void foo( ) {
int a;
for (a = 0; a < 10; a++) { /* OK */
if (a == 5 || a == 7) {
break;
}
}
}

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 14

A function shall have a single point of exit at the end of the function [MISRA2004-14_7-3]
DESCRIPTION
Every function should have a single point of exit.

NOTES
Calls of functions exit, abort, and _Exit from standard library stdlib.h
are detected by rule as exit points.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
int foo(int i)
{
if (i == 0) {
return 0;
// Violation
} else if (i == 1) {
return 1;
// Violation
} else {
return 2;
// Violation
}
}
int foo2(int a) {
int result;
if (a > 0) {
return result;
}
}

REPAIR
int foo(int i)
{
int result = 0;

// Violation

if (i == 0) {
result = 0;
} else if (i == 1) {
result = 1;
} else {
result = 2;
}
return result;
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 82
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 113
4. ISO/DIS 26262
point 8.4.4

The statement forming the body of a 'switch', 'while', 'do...while' or 'for' statement shall be a
compound statement [MISRA2004-14_8-3]
DESCRIPTION
" The statement that forms the body of a switch statement or a while,
do ... while or for loop, shall be a compound statement (enclosed within
braces), even if that compound statement contains a single statement."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x ) {
int i;
switch(i)
;

// Violation

for (i=0; i< 10; i++) // Violation


foo( x );
while (1)
// Violation
foo( x );
do
foo( x );
while(1);

// Violation

REPAIR
void foo( int x ) {
int i;
switch(i)
{
}

// OK

for (i=0; i< 10; i++) // OK

{foo( x );}
while (1)
{foo( x );}

// OK

do

// OK

{foo( x );}
while(1);
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 59
3. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-3-1

'if' and 'else' should be followed by a compound statement [MISRA2004-14_9-3]


DESCRIPTION
"An 'if' (expression) construct shall be followed by a compound statement.
The 'else' keyword shall be followed by either a compound statement,
or another 'if' statement."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x, int
{
int i, j;
if(x > 0)
//
x = i;
else if(y > 0) //
y = i;
else
y = j;
//
x = j;
}

y )

Violation
Violation

Violation

REPAIR
void foo( int x, int y )
{
int i, j;
if(x > 0)
// OK
{
x = i;
}
else if(y > 0) // OK
{
y = i;
}
else

{
y = j;
x = j;

// OK

}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Misra Guidelines - Rule 59
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-1

A switch statement shall only contain switch labels and switch clauses, and no other code
[MISRA2004-15_0_a-3]
DESCRIPTION
"A switch statement shall only contain switch labels and switch clauses,
and no other code."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo(int a,int b)
{
int c;
switch(a)
{
case 1:
break;
c = 1;

/* Violation */

case 2:
break;
c = 2;

/* Violation */

default:
break;
c = 3;

/* Violation */

}
}

REPAIR
void foo1(int a,int b)
{

int c;
switch(a)
{
case 1:
c = 1; /* OK */
break;
case 2:
c = 2; /* OK */
break;
default:
c = 3; /* OK */
break;
}
}

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15

A switch statement shall only contain switch labels and switch clauses, and no other code
[MISRA2004-15_0_b-3]
DESCRIPTION
"A switch statement shall only contain switch labels and switch clauses,
and no other code."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo(int a,int b)
{
int c;
switch(a)
{
c = 0; /* Violation */
case 1:
break;
case 2:
break;
default:
break;
}
}

REPAIR
void foo1(int a,int b)
{
int c;
c = 0;
/* OK */
switch(a)
{
case 1:
break;
case 2:

break;
default:
break;
}
}

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15

A switch statement shall only contain switch labels and switch clauses, and no other code
[MISRA2004-15_0_c-3]
DESCRIPTION
"A switch statement shall only contain switch labels and switch clauses,
and no other code."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
#define SWITCH(a)
\
switch (a)
\
{
\
case 1:
\
break;
\
a << 2; /* Violation */\
case 2:
\
break;
\
default:
\
break;
\
}

REPAIR
#define SWITCH(a)
\
switch (a)
\
{
\
case 1:
\
a << 2; /* OK */\
break;
\
case 2:
\
break;
\
default:
\
break;
\
}

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15

A switch label shall only be used when the most closely-enclosing compound statement is the
body of a switch statement [MISRA2004-15_1-3]
DESCRIPTION
"The scope of a case or default label shall be the compound statement,
which is the body of a switch statement.
All case clauses and the default clause shall be at the same scope."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int a, int b ) {
switch(a) {
case 1:
{
case 6:
/* Violation */
;
default:
/* Violation */
break;
}
break;
case 2:
if (b == 1) {
case 3:
/* Violation */
break;
}
break;
}
}

REPAIR
Do not use nested 'case'/'default' statements.

REFERENCES

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-4

An unconditional break statement shall terminate every non-empty switch clause [MISRA200415_2-3]
DESCRIPTION
"The last statement in every switch clause shall be a break statement,
or if the switch clause is a compound statement, then the last statement
in the compound statement shall be a break statement."

NOTES
This rule allows also to use return instead break statement.

BENEFITS
Prevents unpredictable program behaviour.

EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
case 2 :
{
i = 3;
}
default:
i = 8;
}

// Violation

// Violation

// Violation

// Violation

REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
break;
}
}

// OK

// OK

// OK

// OK - empty case
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Misra Guidelines - Rule 61
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html

From: 14 Flow Control Structures - Rule 47


4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 193

The final clause of a switch statement shall be the default clause [MISRA2004-15_3-3]
DESCRIPTION
All switch statements should contain a final default clause.
"The requirement for a final default clause is defensive programming.
This clause should either take appropriate action or contain a suitable
comment as to why no action is taken."
See also: CODSTA-35

BENEFITS
Rule improves readability and maintainability of 'switch' statement.

EXAMPLE
void foo(int i)
switch(i) /*
{
case 0 :
case 1 :
}
switch(i) /*
{
case 0 :
default:
case 1 :
}
}

{
Violation */
break;
break;
Violation */
break;
break;
break;

REPAIR
void foo(int i)
switch(i) /*
{
case 0 :
case 1 :
default:
}
}

{
OK */
break;
break;
break;

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 62

A switch expression shall not represent a value that is effectively Boolean [MISRA2004-15_43]
DESCRIPTION
Values which are effectively Boolean should not be represented in
'switch' condition.
The rule forbids following operators:
a) equality operators (== and !=)
b) logical operators (!, && and ||)
c) relational operators (<, >, <= and >=)
which produce boolean-by-construct values.

BENEFITS
Rule prevents using values that are effectively Boolean in switch.

EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}

// Violation

REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 63
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 195
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-7

Every switch statement shall have at least one case clause [MISRA2004-15_5-3]
DESCRIPTION
Every switch statement shall have at least one case.
See also: OPT-21, OPT-22, CODSTA-54

BENEFITS
Provides maintainability of 'switch' statement.

EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}

/* Violation */

REPAIR
void foo(int i)
{
switch(i)
{
case 1:
{
}
default:
;
}
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 64
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-8

Functions shall not be defined with a variable number of arguments [MISRA2004-16_1-3]


DESCRIPTION
"Functions shall not be defined with a variable number of arguments.
There are a lot of potential problems with this feature. Users shall not
write additional functions that use a variable number of arguments.
This precludes the use of stdarg.h, va_arg, va_start and va_end."
Rule reports a violation message on:
- inclusion of <stdarg.h> or <cstdarg> headers
- use of va_arg/va_start/va_end macros
- definitions (but not declarations) of functions with variable number
of arguments

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include <stdarg.h>
int average( int first, ... );

/* Violation */
/* OK - Violation on definition */

int average( int first, ... ) {


int count = 0, sum = 0, i = first;
va_list marker;

/* Violation */

va_start( marker, first );


while( i != -1 ) {
sum += i;
count++;
i = va_arg( marker, int );
}
va_end( marker );
return( sum ? (sum / count) : 0 );

/* Violation */

/* Violation */
/* Violation */

REPAIR
Do not use functions with variable number of arguments.

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 16

If a function returns error information, then that error information shall be tested [MISRA200416_10-3]
DESCRIPTION
"A function (whether it is part of the standard library, a third party
library
or a user defined function) may provide some means of indicating the
occurrence
of an error. This may be via an error flag, some special return value or
some
other means. Whenever such a mechanism is provided by a function the
calling
program shall check for the indication of an error as soon as the function
returns.
However, note that the checking of input values to functions is considered
a more robust means of error prevention than trying to detect errors after
the function has completed (see Rule MISRA2004-20_3). Note also that the
use
of errno (to return error information from functions) is clumsy and should
be
used with care (see Rule MISRA2004-20_5)."

NOTES
Rules checks usage of function calls which returns char, short, int, enum,
or typedef to char, short, int, or enum value and reports violation when
this value is not assigned, checked or cast to void.

BENEFITS
Rule helps writing safety code.

EXAMPLE
int SomeFunctionReturningError( );
void foo( )
{
SomeFunctionReturningError( ); // Violation
}

REPAIR
int SomeFunctionReturningError( );
int foo( )
{
int x;
x = SomeFunctionReturningError( );
(void)SomeFunctionReturningError( );
if (SomeFunctionReturningError( ));
switch (SomeFunctionReturningError( )) {
}
return SomeFunctionReturningError( );
}

//
//
//
//

OK
OK
OK
OK

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 86
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 115
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-3-2
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 7
6. http://cwe.mitre.org/data/definitions/391.html

Functions shall not call themselves, either directly or indirectly [MISRA2004-16_2-3]


DESCRIPTION
Functions shall not call themselves, either directly or indirectly.

NOTES
This rule checks for direct recursion and simple indirect
recursion (up to three nested function calls).

BENEFITS
Prevents using recursive functions.

EXAMPLE
void foo( int l ) {
int x = l;
if (l > 0) {
foo( x - 1 );
}

/* Violation */

}
void foo3( int );
void foo4( int i ) {
if (i > 0) {
foo3( (int) i / 2 );
}
}

/* Violation */

void foo3( int i ) {


int x = i;
if (i > 0) {
foo4( x - i );
}
}

/* Violation */

REPAIR
void foo1( ) {
/* empty */
}

/* OK */

void foo2( );

/* OK */

void foo3( ) {
foo2( );
}

/* OK */

void foo7( int );


void foo4( int i ) {
foo7( i );
/* OK - cannot check complex indirect recursion */
}
void foo5( int i ) {
foo4( i );
/* OK - cannot check complex indirect recursion */
}
void foo6( int i ) {
foo5( i );
/* OK - cannot check complex indirect recursion */
}
void foo7( int i ) {
if (i > 0) {
foo6( i - 5 );
}
}

/* OK - cannot check complex indirect recursion */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 70
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 119

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-4
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1
6. HIS Source Code Metriken, version 1.3.1
Metrik "ap_cg_cycle"
7. ISO/DIS 26262
point 8.4.4

Identifiers shall be given for all of the parameters in a function prototype declaration
[MISRA2004-16_3-3]
DESCRIPTION
Names shall be given for all the parameters in the function declaration
for reasons of compatibility, clarity and maintainability.

BENEFITS
Rule improves readability and clarity of code.

EXAMPLE
void foo1( void );
void foo2( int a, int );
void foo3( int a, int ){}

/* OK */
/* Violation */
/* OK */

REPAIR
void foo1( void );
void foo2( int a, int b );
void foo3( int a, int ){}

/* OK */
/* OK */
/* OK */

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 16

The identifiers used in the declaration and definition of a function shall be identical
[MISRA2004-16_4-3]
DESCRIPTION
If identifiers are given for any of the parameters, then the identifiers
used
in the declaration and definition shall be identical.

BENEFITS
Rule improves readability and clarity of code.

EXAMPLE
void foo(int a, int b);
void foo(int x, int y ) {}

/* Violation */

REPAIR
void foo(int a, int b);
void foo(int a, int b) {}

/* OK */

/* Examples of correct code */


void foo1();
/* OK */
void foo2(int , int
); /* OK */
void foo2(int x, int y ) {}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 74
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-2

Functions with no parameters shall be declared with parameter type void [MISRA2004-16_5-3]
DESCRIPTION
"If the function has no parameters, the parameter list shall be declared
as void"

BENEFITS
Rule improves readability and clarity of code.

EXAMPLE
void foo();

/* Violation */

REPAIR
void foo(void);

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 76

The number of arguments passed to a function shall match the number of parameters
[MISRA2004-16_6-3]
DESCRIPTION
The number of parameters passed to a function shall match
prototype. According to the ISO/IEC 9989:1999 C standard,
prototype
is a declaration of a function that declares the types of
This rule requires that the number of arguments passed to

the function
a function
its parameters.
a function match

the number declared in the prototype. Rule is retained since compilers may
not
flag this constraint error.

BENEFITS
Rule improves readability and maintainability and prevents erroneous code.

EXAMPLE
void myFunction(int p)
{
foo(1);
/* Violation - no foo() prototype */
foo(2,p); /* Violation - inconsistent number of parameters:
first foo() call is treated here as foo() declaration
*/
}
void foo0( void );
void foo3( int, int, int );
void goo( ) {
foo0( 7 );
foo3( 6, 6, 6, 6);
}

REPAIR
void myFunction(int p)
{

/* Violation */
/* Violation */

int foo(int, int);


foo(2,p);

/* OK prototype */
/* OK */

}
void foo0( void );
void foo2( int, int, ... );
void foo3( int, int, int );
void goo( )
foo0( );
foo2( 6,
foo2( 6,
foo3( 6,
}

{
6 );
6, 6, 6 );
6, 6 );

/*
/*
/*
/*

OK
OK
OK
OK

*/
*/
*/
*/

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Misra Guidelines - Rule 78

A pointer parameter in a function prototype should be declared as pointer to const if the


pointer is not used to modify the addressed object [MISRA2004-16_7-3]
DESCRIPTION
"A pointer parameter in a function prototype should be declared as pointer
to
const if the pointer is not used to modify the addressed object. The const
qualification should be applied to the object pointed to, not to the
pointer,
since it is the object itself that is being protected."
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104

NOTES
There can already be overloaded function with parameter declared as
pointer
to const. Then changing the type of parameter to pointer to const will
make
the code non-compilable.

EXCEPTIONS
Violation is not reported if parameter is unnamed.

BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.

EXAMPLE
int function(int* ptr)
{
return (*ptr) + 1;
}

REPAIR

// Violation

int function(const int* ptr) // OK


{
return (*ptr) + 1;
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2

Declare a type of parameter as typedef to pointer to const if the pointer is not used to modify
the addressed object [MISRA2004-16_7_b-3]
DESCRIPTION
The rule reports a violation if a parameter in a function prototype is
declared
as typedef to pointer to non-const object and the pointer is not used to
modify
the addressed object. Then the type of parameter could be changed to
typedef
to pointer to const object.
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104

NOTES
It is not sufficient to add 'const' identifier before typedef's
name in a function declaration, because it is applied to pointer
not to pointed object.
There can already be overloaded function with parameter declared as
typedef
to pointer to const. Then changing the type of parameter to typedef to
pointer
to const will make the code non-compilable.

BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.

EXAMPLE
typedef int* PINT;
typedef const int* CINT;
int function1(PINT ptr)
{
return (*ptr) + 1;
}

// Violation

int function2(const PINT ptr)

// Violation

{
return (*ptr) + 1;
}

REPAIR
typedef int* PINT;
typedef const int* CINT;
int function1(CINT ptr)
{
return (*ptr) + 1;
}

// OK

int function2(const CINT ptr)


{
return (*ptr) + 1;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2

All exit paths from a function with non-void return type shall have an explicit return statement
with an expression [MISRA2004-16_8-3]
DESCRIPTION
"All exit paths from a function with non-void return type
shall have an explicit return statement with an expression.
This expression gives the value that the function returns.
The absence of a return with an expression leads to undefined
behaviour (and the compiler may not give an error)."

NOTES
"goto" statement is considered as exit point.
The rule does not track the flow. It assumes that each path could
be reachable independently from conditions in conditional statements.

BENEFITS
Rules prevents unpredictable function behaviour.

DRAWBACKS
Rule skips "while", "for", and "catch" sections.

EXAMPLE
int foo1(int x){ // Violation
// in second 'if' statement, 'return' statement is missing
if (x==0) {
if (x==0) {
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // Violation

// in 'switch' statement, 'default' statement is missing


switch(x){
case 0: return 1;
case 1: return 1;
case 2: return 1;
}
}
int foo3(int x){ // Violation
}
int foo4(int x){ // Violation - rule does not track the flow
if (x > 10) {
return 0;
}
if (x <= 10) {
return 1;
}
// unreachable path
}

REPAIR
int foo1(int x){ // OK
if (x==0) {
if (x==0) {
return 0;
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // OK
switch(x){
case 0: return 1;
case 1: return 1;
case 2: return 1;
default: return 1;
}
}

int foo3(int x){ // OK


return 0;
}
int foo4(int x){ // OK
if (x > 10) {
return 0;
} else {
return 1;
}
// unreachable path
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-3

Do not apply arithmetic to pointers that don't address an array or array element [MISRA200417_1-3]
DESCRIPTION
"Pointer arithmetic shall only be applied to pointers that address an
array or
array element.
Addition and subtraction of integers (including increment and decrement)
from
pointers that do not point to an array or array element results in
undefined
behaviour."
The rule reports a violation when both following conditions are met:
- variable of pointer type is used as operand in arithmetic
expression (addition, subtraction, incrementation, decrementing)
- the variable was not assigned at all in current function or
last assignment before the arithmetic expression was not from an "array
expression"
An "array expression" is an expression or variable which
- has array type (e.g. int[]), or
- expression which takes address of array or array element, or
- was previusly assigned an "array expression"
See also: PB-51

NOTES
Limitation of rule:
- complex expressions might be incorrectly recognized as "array
expression" if
it contains expression with array type. In result a valid violation might
not be reported.
- control flow ('if' etc) is not taken into consideration, only line
number,
when checking for last assignment
- violations on members (a->b, a.b) are not reported.
- recursive check of "array expression" is limited to 10 levels

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
/* example of incorrect code */
void func(int* ptr1, int a[5]){
int i;
int* ptr2 = 0;
int* ptr3 = &i;
ptr1++;
/* Violation - ptr1 may points to whatever*/
ptr1 = ptr2 + 1; /* Violation - ptr2 is a null pointer */
ptr3++;
/* Violation - ptr3 points to variable of non-array
type*/
}

REPAIR
/* example of correct code */
void func(int* ptr3, int a[5]){
int* ptr1 = &a;
int* ptr2 = &a[3];
ptr1++;
/* OK - ptr1 points to an array */
ptr3 = ptr2 + 1; /* OK - ptr2 points to an array element */
ptr3++;
/* OK - ptr3 points to an array element */
}

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 17

Pointer arithmetic shall only be applied to pointers that address an array or array element
[MISRA2004-17_2-3]
DESCRIPTION
"Subtraction of pointers only gives well-defined results if the two
pointers
point (or at least behave as if they point) into the same array object."
Drawbacks: For more complex code rule may not be able to check if there is
applied pointer arithmetic to pointers that address an array or array
element.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5

=
=
=
=
=

a; i
p1;i
p2;i
p3;i
p4;i

=
=
=
=
=

p1
p2
p3
p4
p5

a;
a;
a;
a;
a;

//
//
//
//
//

OK
OK
OK
Violation - false positive
Violation - false positive

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 - p2;
i = p2 - a;
i = p3 - a;
}

// Violation
// Violation
// OK

REPAIR
Do not apply pointer subtraction to pointers that address elements
of different arrays.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-17

>, >=, <, <= shall not be applied to pointer types except where they point to the same array
[MISRA2004-17_3-3]
DESCRIPTION
"Attempting to make comparisons between pointers will produce undefined
behaviour."

NOTES
"It is permissible to address the next element beyond the end of an array,
but accessing this element is not allowed."

EXCEPTIONS
"Both operands are of the same type and point to the same array"

BENEFITS
Rule makes the code more readable and less confusing.

DRAWBACKS
For more complex code rule may not be able to check if there is
applied pointer comparison to pointers which point the same array.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
}

=
=
=
=
=

a; i
p1;i
p2;i
p3;i
p4;i

=
=
=
=
=

p1
p2
p3
p4
p5

<
<
<
<
<

a;
a;
a;
a;
a;

//
//
//
//
//

OK
OK
OK
Violation - false positive
Violation - false positive

EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 < p2;
i = p2 < a;
i = p3 < a;

// Violation
// Violation
// OK

REPAIR
Do not apply pointer comparison to pointers that address elements
of different arrays

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 103
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 171
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-18

Array indexing shall be the only allowed form of pointer arithmetic [MISRA2004-17_4-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
BENEFITS
Rule improves safety of the code.

DRAWBACKS
For more complex code rule may not be able to check if there is indexed
pointer
which points to array. For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10];
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5

=
=
=
=
=

a;
p1;
p2;
p3;
p4;

p1[0]
p2[0]
p3[0]
p4[0]
p5[0]

=
=
=
=
=

0;
0;
0;
0;
0;

//
//
//
//
//

OK
OK
OK
Violation - false positive
Violation - false positive

EXAMPLE
void my_fn(int * p1, int p2[]) {
int index = 0;

int * p3;
int * p4;
*p1 = 0;
p1 ++;
/* Violation
p1 = p1 + 5; /* Violation
p1[5] = 0;
/* Violation
p3 = &p1[5]; /* Violation
p2[0] = 0;
index ++;
index = index + 5;
p2[index] = 0; /* OK */
p4 = &p2[5];
/* OK */

pointer increment */
pointer increment */
p1 was not declared as an array */
p1 was not declared as an array */

}
void foo() {
int a1[16];
int a2[16];
int a[10];
int * p;
my_fn(a1, a2);
my_fn(&a1[4], &a2[4]);
p = a;
*(p+5) = 0; /* Violation */
p[5] = 0;
/* OK */
}

REPAIR
Do not increment/decrement pointers that does not point to an array
Do not apply array indexing to pointers that does not point to array
elements.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-15

The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_a-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int * INTPTR;
struct s {
int *** s3;
};
struct s *** ps3;
int ** (***pfunc3)();
int *** ( **pfunc4)();
void function( int * par1,
int *** par3,
INTPTR * const * const par5
)
{

/* Violation */

/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */

int *** ptr3;


/* Violation */
INTPTR * const * const ptr5 = 0; /* Violation */
}

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4

The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_b-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int* apInt[] ;
apInt* rule12;
/* Violation */

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4

The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_c-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
int*** (*rule13)();

/* Violation */

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17

2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4

The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_d-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int* INTPTR;
void function(int ** par7[])
{
}
int*** (*xx5[])() = {0};
typedef int INTARR[];
INTARR* (**xx9[])() = {0};
int** rule21[] = {0};

/* Violation */

/* Violation */
/* Violation */
/* Violation */

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4

The address of an object with automatic storage shall not be assigned to another object that
may persist after the first object has ceased to exist [MISRA2004-17_6-3]
DESCRIPTION
"If the address of an automatic object is assigned to another automatic
object
of larger scope, or to a static object, or returned from a function then
the
object containing the address may exist beyond the time when the original
object
ceases to exist (and its address becomes invalid). For example:
int * foo( void ) {
int local_auto;
return (&local_auto);
}"

BENEFITS
Prevents loss of data

EXAMPLE
int* global;
int* foo() {
int iLocal;
static int* siLocal;
siLocal = &iLocal;
global = &iLocal;
return &iLocal;
}
void goo() {
int* piLocal;
{
int iiLocal;
piLocal = &iiLocal;
}
}

// Violation
// Violation
// Violation

// Violation

REPAIR
Do not assign local address of object to more global,
or static object or return from function.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 106
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 173
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-2

All structure and union types shall be complete at the end of a translation unit [MISRA200418_1-3]
DESCRIPTION
"A complete declaration of the structure or union shall be included within
any translation unit that reads from or writes to that structure.
A pointer to an incomplete type is itself complete and is permitted,
and therefore the use of opaque pointers is permitted"
References are treated the same way as pointers so the use of opaque
references is permitted as well.

BENEFITS
Rule prevents undefined behaviour and improves readability
and maintainability of code

EXAMPLE
extern struct st *pst1;
extern struct st *pst2;
void mc2_1801 ( void )
{
//
struct st1 s;
*/

/* Violation - not compilable with all compilers

struct {
int a;
int b [ ];
/* Violation */
} mc2_1801_st = { 1, { 2, 3, 4 } };
pst2 = pst1;
//
*/
}

*pst2 = *pst1;

REPAIR
struct st{

/* OK - Use of opaque pointer */


/* Violation - not compilable with all compilers

int stm;
};
struct st1{
int st1m;
};
extern struct st *pst1;
extern struct st *pst2;
void mc2_1801 ( void )
{
struct st1 s;
/* OK */
struct {
int a;
int b [3];
/* OK */
} mc2_1801_st = { 1, { 2, 3, 4 } };
pst2 = pst1;

/* OK - Use of opaque pointer */

*pst2 = *pst1;

/* OK */

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 18

An object shall not be assigned to an overlapping object [MISRA2004-18_2-3]


DESCRIPTION
"The behaviour is undefined when two objects are created
which have some overlap in memory and one is copied to the other."
Rule detects if two different members of the same union are assigned to
each other using the same object.

BENEFITS
Rule prevents undefined behaviour and data loss.

EXAMPLE
union U {
int
long
double
};

iValue;
lValue;
dValue;

void main( ) {
union U a, b;
union U *p;
a.dValue = a.lValue;
p->dValue = p->iValue;

/* Violation */
/* Violation */

REPAIR
union U {
int
long
double
};

iValue;
lValue;
dValue;

void main( ) {
union U a, b;
union U *p, *q;
a.dValue = b.lValue;

/* OK */

p->dValue = q->iValue;

/* OK */

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 18

An object shall not be assigned to an overlapping object [MISRA2004-18_2_b-3]


DESCRIPTION
"The behaviour is undefined when two objects are created
which have some overlap in memory and one is copied to the other."
Rule detects if two different members of the same union are copied to
each other using the same object.

BENEFITS
Rule prevents undefined behaviour and data loss.

EXAMPLE
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {
union U a, b;
union U *p;
(void)memcpy( &a.dValue, &a.lValue, 8 );
(void)memcpy( &p->dValue, &p->iValue, 8 );
return 0;
}

REPAIR
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {

/* Violation */
/* Violation */

union U a, b;
union U *p, *q;
(void)memcpy( &a.dValue, &b.lValue, 8 );
(void)memcpy( &p->dValue, &q->iValue, 8 );
return 0;

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-2-1

Unions shall not be used [MISRA2004-18_4-3]


DESCRIPTION
"Even when memory is being reused for related purposes,
there is still a risk that the data may be misinterpreted.
Therefore, this rule prohibits the use of unions for any purpose."

Note:
Rule reports a violation message on each union's declaration.

BENEFITS
Rule prevents undefined behaviour and erroneous code.

EXAMPLE
union U {
/* Violation */
int _i;
char _buf[ sizeof( int ) ];
};

REPAIR
Do not use union.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 97
3. Origin: Misra Guidelines - Rule 109

4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.20 Unions and Bit Fields, AV Rule 153
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 9, Rule 9-5-1

#include statements in a file should only be preceded by other preprocessor directives or


comments [MISRA2004-19_1-3]
DESCRIPTION
"All the #include statements in a particular code file should be grouped
together near the head of the file. The rule states that the only items
which
may precede a #include in a file are other preprocessor directives or
comments."

BENEFITS
It is important to prevent the situation of executable code coming before
a #include directive, otherwise there is danger that the code may try to
use
items which would be defined in the header.

EXAMPLE
void foo();
int g;
#include "test.h"

// Violation

REPAIR
#include "test.h"
void foo();
int g;

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-1
3. Origin: Misra Guidelines - Rule 87

In the definition of a function-like macro each instance of a parameter shall be enclosed in


parentheses unless it is used as the operand of # or ## [MISRA2004-19_10-3]
DESCRIPTION
"If parentheses are not used, then the operator precedence may not give
the desired results when the preprocessor substitutes the macro into the
code.
Within a definition of a function-like macro, the arguments shall be
enclosed
in parentheses."
See also: MISRA-096

EXCEPTIONS
If an argument of macro is used in body after '.', '->', '::' or before
'::',
then violation is not reported, because the use of paranthesis in such
cases
makes a code non-compilable. For example:
#define INIT1(member) a->member = 0 // No violation reported
#define CALL(ns,fn) ns::fn() // No violation reported

BENEFITS
Improves the readability of code and ensures operations order.

DRAWBACKS
In some cases a violation is reported, but the use of parenthesis causes a
compilation error. For example:
#define MTYPE(type, a) (type *)(a) // Violation reported
#define MT(classtype, type) classtype<type> // Violation reported

EXAMPLE
#define abs(x) ((x >= 0) ? x : -x)
void foo(int a, int b){
int z = abs(a - b);

// Violation

REPAIR
#define abs(x) (((x) >= 0) ? (x) : -(x))

// OK

void foo(int a, int b){


int z = abs(a - b);
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-6

All macro identifiers in preprocessor directives shall be defined before use, except in #ifdef
and #ifndef preprocessor directives and the defined() operator [MISRA2004-19_11-3]
DESCRIPTION
If an attempt is made to use an identifier in a preprocessor directive,
and that identifier has not been defined,
the preprocessor will sometimes not give any warning but will assume
the value zero.
#ifdef, #ifndef and defined() are provided to test the existence of a
macro,
and are therefore excluded.

BENEFITS
Complying with this rule leads to safer code
and prevents hard-to-detect errors.

DRAWBACKS
1) Currently the implementation of the rule assumes that the compliance
with
the rule is provided by following MISRA 2004 19-11 advice (p. 78):
"Consideration should be given to the use of a /#ifdef/" test before
an identifier is used."
2) If #1 is not followed, due to technical limitations we are not able
to recognize cases where preprocessor identifier is defined in different
file from that where the identifier is used. Also, we are unable to
detect
that given identifier was defined as compiler command line option.
3) If tested macro identifier was earlier defined by #define preprocessor
directive, it can not be defined in more nested #if / #elif / #else /
#endif
directives. In such cases rule can report false positives.
3) If tested macro identifier is defined within complex conditional
statement (containing
few branches #elif/#else) we cannot be sure if branch containing
definition of macro

being tested is executed. In such case rule may report false positives.

EXAMPLE
#if X
/* Violation - X undefined at this point */
#endif
#if Y
/* Violation - Y undefined at this point */
#endif
#if X + Y
/* Violation - X and Y undefined at this point */
#endif
#ifdef X
#define Y 1
#else
#define Y 3
#endif
#if Y > 2
#endif

// Violation - because of point 3

REPAIR
#define X 1
#if X
/* OK */
#endif
#ifdef Y
#if Y
/* OK - check is done in the #ifdef above */
#endif
#endif
#ifdef X
#define Y 1
#else

#define Y 3
#endif
#ifdef Y
#if Y > 2
#endif
#endif

// OK - possible workaround because of point 3

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 97
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-7

There shall be at most one occurrence of the # or ## preprocessor operators in a single macro
definition [MISRA2004-19_12-3]
DESCRIPTION
"There is an issue of unspecified order of evaluation associated
with the # and ## preprocessor operators.
To avoid this problem only one occurrence of either operator
shall be used in any single macro definition
(i.e. one #, or one ## or neither)."

BENEFITS
Rule improves readability and clarity of code.

EXAMPLE
#define TEST1(A,B,C) A # B # C
#define TEST2(A,B,C) A ## B # C
#define TEST3(A,B,C) A ## B ## C

/* Violation */
/* Violation */
/* Violation */

REPAIR
#define TESTa(A,B) A # B
#define TESTb(A,B) A ## B

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 98
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-1

The # and ## preprocessor operators should not be used [MISRA2004-19_13-3]


DESCRIPTION
"There is an issue of unspecified order of evaluation associated
with the # and ## preprocessor operators.
Compilers have been inconsistent in the implementation of these operators.
To avoid these problems do not use them."

BENEFITS
Rule prevents inconsistent implementation of # and ## operators.

EXAMPLE
#define stringer( x ) printf( #x "\n" ) /* Violation */

REPAIR
Do not use # and ## preprocessor operators.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-2

The defined preprocessor operator shall only be used in one of the two standard forms
[MISRA2004-19_14-3]
DESCRIPTION
"The only two permissible forms for the defined preprocessor operator are:
- defined ( identifier )
- defined identifier
Any other form leads to undefined behaviour.
Generation of the token defined during expansion of a #if or #elif
preprocessing directive also leads to undefined behaviour and shall be
avoided,"

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#if defined X > Y
#endif
#define DEFINED defined
#if DEFINED(X)
#endif

// Violation

// Violation

REPAIR
#if defined X
#endif
#if defined (X)
#endif

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-1-1

Precautions shall be taken in order to prevent the contents of a header file being included
twice [MISRA2004-19_15-3]
DESCRIPTION
"When a translation unit contains a complex hierarchy of nested header
files
it can happen that a particular header file is included more than once.
This can be, at best, a source of confusion. If it leads to multiple or
conflicting definitions, the result can be undefined or erroneous
behaviour."
Rule checks if any of described below mechanisms preventing the file
contents
from being included more than once is present.
#ifndef AHDR_H
#define AHDR_H
/* The following lines will be excluded by the
preprocessor if the file is included more
than once */
...
#endif
Alternatively, the following may be used:
#ifdef AHDR_H
#error Header file is already included
#else
#define AHDR_H
/* The following lines will be excluded by the
preprocessor if the file is included more
than once */
...
#endif
See also: PFO-02, PFO-07, and PFO-08.

BENEFITS
Rule prevents undefined and erroneous behaviour.

EXAMPLE
/* foo.h */
/* Violation - file contains no multi inclusion mechanism */
/* foo.hh */
/* Violation - file contains no multi inclusion mechanism */
/* foo.c */
#include "foo.h"
#include "foo.hh"

REPAIR
/* foo.h */
/* OK */
#ifndef FOO_H
#define FOO_H
/* code here */
#endif
/* foo.hh */
/* OK */
#ifdef FOO_HH
#error Header file is already included
#else
#define FOO_HH
#endif
/* foo.c */
#include "foo.h"
#include "foo.hh"

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 19

Preprocessing directives shall be syntactically meaningful even when excluded by the


preprocessor [MISRA2004-19_16-3]
DESCRIPTION
"When a section of source code is excluded by preprocessor directives,
the content of each excluded statement is ignored until a #else, #elif
or #endif directive is encountered (depending on the context).
If one of these excluded directives is badly formed, it may be ignored
without warning by a compiler with unfortunate consequences.
The requirement of this rule is that all preprocessor directives shall be
syntactically valid even when they occur within an excluded block of code.
Compilers are not always consistent in enforcing this ISO requirement."

BENEFITS
Rule prevents erroneous behaviour.

EXAMPLE
#define MAX 2
int foo(void)
{
int x = 0;
#ifndef MAX
x = 1;
#else1
x = MAX;
#endif
return x;
}

REPAIR
#define MAX 2
int foo(void)
{
int x = 0;

/* Violation */

#ifndef MAX
x = 1;
#else
x = MAX;
#endif
return x;
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-8

All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if or
#ifdef directive to which they are related [MISRA2004-19_17-3]
DESCRIPTION
"When the inclusion and exclusion of blocks of statements is controlled
by a series of preprocessor directives, confusion can arise
if all of the relevant directives do not occur within one file."
This rule requires that the number of preprocessor directives
#if/ifdef/ifndef
matches the number of #endif directives in the file.

BENEFITS
Rule improves good code structure and
prevents maintenance problems.

EXAMPLE
/* Violation */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"

REPAIR
/* OK */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"
#endif

REFERENCES

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-1-2

Non-standard characters should not occur in header file names in #include directives
[MISRA2004-19_2-3]
DESCRIPTION
"If the ', \, ", or /* characters are used between < and >
delimiters or the ', \, or /* characters are used
between the " delimiters in a header name preprocessing token,
then the behaviour is undefined."

BENEFITS
Ensures only standard characters in header file names.

EXAMPLE
#include <sys\types.h>
#include "incl\header.h"

/* Violation */
/* Violation */

REPAIR
#include <sys/types.h>
#include "incl/header.h"

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 88

Avoid keywords and basic types in macros [MISRA2004-19_4-3]


DESCRIPTION
"C macros shall only expand to a braced initialiser, a constant,
a string literal, a parenthesised expression, a type qualifier,
a storage class specifier, or a do-while-zero construct.
These are the only permitted uses of macros.
In particular macros shall not be used to define statements or parts
of statements except the use of the do-while construct. Nor shall
macros redefine the syntax of the language. All brackets of whatever
type ( ) { } [ ] in the macro replacement list shall be balanced."

NOTES
Storage class specifiers and type qualifiers include keywords such as:
typedef, extern, static, auto, register, const, volatile, restrict.

BENEFITS
Prevents from redefining the syntax of the language.

EXAMPLE
#define PI 3.14159F
#define DOUBLE_PI 2*PI
#define int64_t
long

/* OK */
/* Violation */
/* Violation */

REPAIR
#define PI 3.14159F
#define DOUBLE_PI (2*PI)
typedef long int64_t;

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19

2. Origin: Misra Guidelines - Rule 90

Macros shall not be #define'd or #undef'd within a block [MISRA2004-19_5-3]


DESCRIPTION
"While it is legal C to place #define or #undef directives anywhere in a
code
file, placing them inside blocks is misleading as it implies a scope
restricted
to that block, which is not the case."

BENEFITS
Improves the readability of code.

EXAMPLE
void foo( int* x ) {
#define CHECKPARAM(p) (p != 0)
if (CHECKPARAM(x)) {
/* ... */
}
#undef CHECKPARAM
}

// Violation

// Violation

REPAIR
#define CHECKPARAM(p) (p != 0) // OK - macro is defined outside of any
blocks
void foo( int* x ) {
if (CHECKPARAM(x)) {
/* ... */
}
}
#undef CHECKPARAM
// OK - macro is undefined outside of any
blocks

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 91
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-2

#undef shall not be used [MISRA2004-19_6-3]


DESCRIPTION
"#undef should not normally be needed.
Its use can lead to confusion with respect to the existence
or meaning of a macro when it is used in the code."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
#undef TEST

/* Violation */

REPAIR
Do not use #undef.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 92
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-3

A function should be used in preference to a function-like macro [MISRA2004-19_7-3]


DESCRIPTION
Rule reports a violation on function-like macro definition.

BENEFITS
"While macros can provide a speed advantage over functions, functions
provide
a safer and more robust mechanism. This is particularly true with respect
to the type checking of parameters, and the problem of function-like
macros
potentially evaluating parameters multiple times.
See also: CODSTA-03, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40

EXAMPLE
#define SUM(A,B) ((A)+(B))

/* Violation */

void foo( int x, int y ) {


/* ... */
SUM( x, y );
/* ... */
}

REPAIR
int sum( int a, int b ) {
return (a + b);
}
void foo( int x, int y ) {
/* ... */
sum( x, y );
/* ... */
}

REFERENCES

/* OK */

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 19
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
3. Misra Guidelines - Rule 93
4. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.5 Inline Functions - Rule 35
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 29
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-4

A function-like macro shall not be invoked without all of its arguments [MISRA2004-19_8-3]
DESCRIPTION
"This is a constraint error, but preprocessors have been known to ignore
this
problem. Each argument in a function-like macro must consist of at least
one
preprocessing token otherwise the behaviour is undefined."

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#define MAX(a, b, c)

((a < b) ? b : a)

void foo(int a, int b)


{
int c;
c = MAX(a, b);
/* Violation */
}

REPAIR
#define MAX(a, b, c)

((a < b) ? b : a)

void foo(int a, int b)


{
int c;
c = MAX(a, b, 0); /* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19

2. Origin: Misra Guidelines - Rule 94

Arguments to a function-like macro shall not contain tokens that look like preprocessing
directives [MISRA2004-19_9-3]
DESCRIPTION
"If any of the arguments act like preprocessor directives,
the behaviour when macro substitution is made can be unpredictable."

NOTES
Rule works only within file scope.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( #foo );
MACRO2( i, #foo );
MACRO2( i, "#foo" );
}

/* Violation */
/* Violation */
/* Violation */

REPAIR
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( i );
MACRO2( i, i );
}

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 95
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-5

The library functions atof, atoi and atol from library stdlib.h shall not be used [MISRA200420_10-3]
DESCRIPTION
'atof', 'atoi' and 'atol' functions from library <stdlib.h> have undefined
behaviour associated with them when the string cannot be converted.

BENEFITS
Prevents using functions which have sometimes undefined behaviour.

EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *s; double x; int i; long l;
s = " -2309.12E-15";
x = atof( s );
/* Violation */
s = " -9885 pigs";
i = atoi( s );
/* Violation */
s = "98854 dollars";
l = atol( s );
/* Violation */
}

REPAIR
Do not use atof, atoi and atol functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 125
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 23

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-2

The library functions abort, exit, getenv and system from library stdlib.h shall not be used
[MISRA2004-20_11-3]
DESCRIPTION
'abort', 'exit', 'getenv' and 'system' functions from stdlib.h, cstdlib,
or stdlib_iso.h libraries shall not be used.

BENEFITS
Prevents using functions which are not required in an embedded system.

EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *libvar;
libvar = getenv( "LIB" );
system( "dir" );
abort( );
exit( 0 );
}

/*
/*
/*
/*

Violation
Violation
Violation
Violation

*/
*/
*/
*/

REPAIR
Do not use abort, exit, getenv and system functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 126
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 24
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-3

The time handling functions of library time.h shall not be used [MISRA2004-20_12-3]
DESCRIPTION
"This library is associated with clock times.
Various aspects are implementation dependent
or unspecified, such as the formats of times."
Rule prevents inclusion of <time.h> and <ctime> headers.
See also: SECURITY-01

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include <time.h>

/* Violation */

REPAIR
Do not include time.h header.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 127
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 25
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 18, Section 7, Rule 18-0-4

Reserved identifiers, macros and functions in the standard library, shall not be defined,
redefined or undefined [MISRA2004-20_1_a-3]
DESCRIPTION
"It is generally bad practice to #undef a macro which is defined in the
standard library. It is also bad practice to #define a macro name which
is a C reserved identifier or C keyword which is the name of any macro,
object or function in the standard library.
For example, there are some specific reserved words and function names
which are known to give rise to undefined behaviour if they are redefined
or
undefined, including defined, _ _LINE_ _, _ _FILE_ _, _ _DATE_ _, _ _TIME_
_,
_ _STDC_ _, errno and assert. Generally, all identifiers that begin with
the underscore character are reserved."

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#define __A 1
// Violation
#define assert 1
// Violation
#undef __AA
// Violation
#undef assert
// Violation

REPAIR
Do not #define or #undef reserved identifiers

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114

3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1

Do not redefine reserved words [MISRA2004-20_1_b-3]


DESCRIPTION
"It is generally bad practice to #undef or #define names which are C
reserved words"

BENEFITS
Redefinition of reserved words can lead to errors and confusion.

EXAMPLE
#define break 1
#define continue 1
#undef while
#undef return

//
//
//
//

Violation
Violation
Violation
Violation

REPAIR
Do not #define or #undef reserved words

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1

The names of standard library macros, objects and functions shall not be reused [MISRA200420_2-3]
DESCRIPTION
"Where new versions of standard library macros, objects or functions are
used
by the programmer (e.g. enhanced functionality or checks of input values)
the
modified macro, object or function shall have a new name. This is to avoid
any
confusion as to whether a standard macro, object or function is being used
or
whether a modified version of that function is being used. So, for
example, if
a new version of the sqrt function is written to check that the input is
not
negative, the new function shall not be named sqrt, but shall be given a
new
name."
Rule checks if the following reserved names are used:
- macro, function, and typedef names from C standard library headers:
assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- identifiers that begin with the underscore character
See also: NAMING-33, CODSTA-92, CODSTA-93

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
int memset();

REPAIR

// Violation

int my_memset(); // OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20

The validity of values passed to library functions shall be checked [MISRA2004-20_3-3]


DESCRIPTION
"Many functions in the standard C libraries are not required by the
ISO standard to check the validity of parameters passed to them.
Even where checking is required by the standard, or where
compiler writers claim to check parameters,
there is no guarantee that adequate checking will take place.
Therefore the programmer shall provide appropriate checks
of input values for all library functions"
Implementation of this rule will search function body
prior to the library function call to see if its arguments
are used within conditional statement conditions,
or passed to any functions.
Such use will be considered as argument validation
necessary to comply with this rule.

BENEFITS
Prevents writing error prone code.

EXAMPLE
void* memcpy( void *, void*, int n );
void test( void *v ) {}
int getSomeIntValue( ) {
return 0;
}
void foo( void *p, void *q ) {
int n;
memcpy( p, q, n );
/* Violation test( q );
/* consider it
memcpy( p, q, n );
/* Violation switch( n ) {
/* consider it
case 0:
break;
}
if (p == 0) {}
/* consider it

complain about p,
a validation of q
complain about p,
a validation of n

q and n */
*/
and n */
*/

a validation of p */

memcpy( p, q, getSomeIntValue( ) );
getSomeIntValue call */
}

/* Violation - complain only about

REPAIR
void* memcpy( void *, void*, int n );
void test( void *v ) {}
int getSomeIntValue( ) {
return 0;
}
void foo( void *p, void *q ) {
int n;
test( p );
/* consider it
test( q );
/* consider it
if (n != 0) {
memcpy( p, q, n );
/* OK */
memcpy( p, q, n );
/* OK */
}
switch( n ) {
/* consider it
case 0:
break;
}
if (p == 0) {}
/* consider it
n = getSomeIntValue( );
if (n != 0) {
memcpy( p, q, n );
/* OK */
}
}

a validation of p */
a validation of q */

a validation of n */

a validation of p */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 117

Dynamic heap memory allocation shall not be used [MISRA2004-20_4-3]


DESCRIPTION
"The use of dynamic memory can lead to out-of-storage run-time failures,
which are undesirable. The built-in new and delete operators, other than
the placement versions, use dynamic heap memory. The functions calloc,
malloc, realloc and free also use dynamic heap memory."

EXCEPTIONS
The rule allows to use a placement new.

BENEFITS
"There is a range of unspecified,
behaviour associated with dynamic
of
other potential pitfalls. Dynamic
memory
leaks, data inconsistency, memory
behaviour."

undefined and implementation-defined


memory allocation, as well as a number
heap memory allocation may lead to
exhaustion, non-deterministic

EXAMPLE
void foo()
{
int * p = new int[10]; // Violation
/* ... */
delete[] p;

// Violation

REPAIR
Do not use neither 'new' and 'delete' operators nor 'calloc', 'malloc',
'realloc' and 'free' functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Misra Guidelines - Rule 118
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-4-1
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 206
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 3

The error indicator errno shall not be used [MISRA2004-20_5-3]


DESCRIPTION
"errno is a facility of C and C++, which in theory should be useful, but
which
in practice is poorly defined by the standard. A non zero value may or may
not
indicate that a problem has occurred; as a result it shall not be used.
Even for those functions for which the behaviour of errno is well defined,
it is preferable to check the values of inputs before calling the function
rather than rely on using errno to trap errors"

BENEFITS
The rule prevents undefined behaviours.

EXAMPLE
#include <errno.h>
int err_check( ) {
errno = 1;
return (errno);
}

/* Violation */
/* Violation */

REPAIR
Do not use errno.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 119
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 17

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 19, Rule 19-3-1

The macro offsetof, in library stddef.h, shall not be used [MISRA2004-20_6-3]


DESCRIPTION
"Use of this macro can lead to undefined behaviour
when the types of the operands are incompatible or
when bit fields are used."
Rule reports a violation message if the offsetof
macro is used and the file includes any of the
following headers: stddef.h, stddef, or cstddef.

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
// Violation - The macro offsetof shall not be used. Macro is in line:
[10]
#include <stddef.h>
struct S {
int x, y, z;
char buffer[ 128 ];
};
int main( ) {
int i = offsetof( struct S, buffer );
return 0;
}

REPAIR
Do not use offsetof.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20

2. Origin: Misra Guidelines - Rule 120


3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 18
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-2-1

The setjmp macro and the longjmp function shall not be used [MISRA2004-20_7-3]
DESCRIPTION
"setjmp and longjmp allow the normal function call mechanisms to be
bypassed,
and shall not be used."
Rule reports a violation message if setjmp or longjmp is used and the file
includes any of the following headers: setjmp.h, setjmp, or csetjmp.

BENEFITS
Rule prevents normal function call mechanisms from being bypassed.

EXAMPLE
#include <setjmp.h>
jmp_buf mark;
int
fperr;
void foo( void ) {
int jmpret;
jmpret = setjmp( mark );
}

/* Address for long jump to jump to */


/* Global error number */

/* Violation */

void fphandler( int sig, int num ) {


longjmp( mark, -1 );
/* Violation */
}

REPAIR
Do not use the setjmp macro and the longjmp function.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 122

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.5 Libraries, AV Rule 20
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-5
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1

The signal handling facilities of signal.h shall not be used [MISRA2004-20_8-3]


DESCRIPTION
"Signal handling contains implementation-defined and undefined behaviour."
Rule reports a violation message if a file includes any of the following
headers: signal.h, or csignal.

BENEFITS
Prevents from problems associated with implementation-defined
and undefined behaviour in signal handling.

EXAMPLE
#include <signal.h>

/* Violation */

REPAIR
Do not use <signal.h> header.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 123
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 21
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-7-1

The input/output library stdio.h shall not be used [MISRA2004-20_9-3]


DESCRIPTION
"Streams and file I/O have a large number of unspecified,
undefined and implementation-defined behaviours associated with them.
It is assumed that they will not normally be needed in production
code in embedded systems.
If any of the features of stdio.h need to be used in production code,
then the issues associated with the feature need to be understood."
The rule prevents inclusion of <stdio.h>, and <cstdio> headers.

BENEFITS
Prevents form problems associated with a large number of unspecified,
undefined and implementation-defined behaviour associated
with streams and file I/O.

EXAMPLE
#include <stdio.h>

/* Violation */

REPAIR
Do not use <stdio.h> library.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 124
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 22
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 27, Rule 27-0-1

Assembly language shall be encapsulated and isolated [MISRA2004-2_1-3]


DESCRIPTION
"Where assembly language instructions are required it is recommended
that they be encapsulated and isolated in either (a) assembler functions,
(b) C functions or (c) macros."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
/* compilable by cl.exe g++*/
void asmCall( ) {
/* Violation */
int g = 0;
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (
"mov %eax, 0x01\n\t"
"int $0x10"
);
#endif
}

REPAIR
void asmCall( ) {
/* OK */
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (

"mov %eax, 0x01\n\t"


"int $0x10"
);
#endif
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Misra Guidelines - Rule 3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-4-3

Source code shall only use /* ... */ style comments [MISRA2004-2_2-3]


DESCRIPTION
This excludes the use of // C99 style comments and C++ style comments,
since these are not permitted in C90.
Many compilers support the // style of comments as an extension to C90.

BENEFITS
The use of // in preprocessor directives (e.g. #define) can vary.
Also the mixing of /* ... */ and // is not consistent.
This is more than a style issue,
since different (pre C99) compilers may behave differently.

EXAMPLE
#define MAX 100 // Violation: bad comment
// Violation: bad comment
void foo()
{
int x;
// Violation: bad comment
}

REPAIR
#define MAX 100 /* OK */
/* OK */
void foo()
{
int x;
/* OK */
}

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 2

The character sequence /* shall not be used within a comment [MISRA2004-2_3-3]


DESCRIPTION
C does not support the nesting of comments even though
some compilers support this as a language extension.
A comment begins with /* and continues until the first */ is encountered.
Any /* occurring inside a comment is a violation of this rule.

BENEFITS
Nested comments are not supported by C and can lead to confusion.

EXAMPLE
/* some comment, end comment marker accidentally omitted
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is not compliant - Violation */

REPAIR
/* some comment, end comment marker accidentally omitted */
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is compliant - OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 9
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-1

Sections of code should not be "commented out" [MISRA2004-2_4-4]


DESCRIPTION
"Where it is required for sections of source code not to be compiled then
this should be achieved by use of conditional compilation (e.g. #if or
#ifdef constructs with a comment)."

NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.

BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."

EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}

// Violation

REPAIR
void foo()
{
int x = 5;
/* Comment without

// OK

code within */
#if 0
if (x==0){
x++;
}
#endif
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3

All uses of the #pragma directive shall be documented and explained [MISRA2004-3_4-3]
DESCRIPTION
All uses of #pragma directive shall be documented and explained.

BENEFITS
Provides readability and maintainability.

EXAMPLE
#pragma TEST

/* Violation */

/* comment in wrong place */


#pragma TEST

/* Violation */

/* comment in wrong place

*/
#pragma TEST

/* Violation */

REPAIR
// OK
#pragma TEST

/* OK */
#pragma TEST
/* OK - multiline comment
*/
#pragma TEST

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 3
2. Origin: Misra Guidelines - Rule 99
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-6-1

Do not mix bit-fields and other data within the same structure [MISRA2004-3_5-3]
DESCRIPTION
It is recommended that structures should be declared specifically
to hold the sets of bit fields, and do not include any other data
within the same structure.

BENEFITS
Rule prevents from the potential pitfalls and areas of implementationdefined
(i.e.non-portable) behaviour such as:
- the alignment of the bit fields in the storage unit is implementationdefined,
that is whether they are allocated from the high end or low end of the
storage
unit (usually a byte).
- whether or not a bit field can overlap a storage unit boundary is also
implementation-defined
(e.g. if a 6-bit field and a 4-bit field are declared in that order,
whether the 4-bit field
will start a new byte or whether it will be 2 bits in one byte and 2 bits
in the next).

EXAMPLE
struct message { /* Violation */
signed int little: 4;
unsigned int x_set: 1;
int size;
};

REPAIR
struct message { /* OK */
signed int little: 4;
unsigned int x_set: 1;
};

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 3

Only those escape sequences that are defined in the ISO C standard shall be used
[MISRA2004-4_1-3]
DESCRIPTION
Only those escape sequences that are defined in the ISO C standard
shall be used.
Section 5.2.2 of the ISO C standards defines 7 escape sequences which
may be used in source code:
1. \a (alert)
2. \b (backspace)
3. \f (form feed)
4. \n (new line)
5. \r (carriage return)
6. \t (horizontal tab)
7. \v (vertical tab)

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
#include <stdio.h>
void foo( ) {
printf("ABCD\u1111");
printf("abcd\hgf");
printf("\k");
}

// Violation
// Violation
// Violation

REPAIR
Do not use escape sequences not defined in the ISO C standard.

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 4

Trigraphs shall not be used [MISRA2004-4_2-3]


DESCRIPTION
Rule reports a violation message if trigraphs are used.
All occurrences in a source file of the following sequences of three
characters (called trigraph sequences) are replaced with the corresponding
single character.
??= #
??( [
??/ \
??) ]
??' ^
??< {
??! |
??> }
??- ~
If the compiler has a switch to ignore trigraphs then this
option should be used, or alternatively ensure that two
adjacent question marks are never used in the code.

BENEFITS
Trigraphs can cause accidental confusion with other uses of two question
marks and lead to unexpected behaviour.

EXAMPLE
??=define TEST 1
/* Violation
*/
void foo() {
const char* s = "(Date should be in the form ??-??-??)"; /* Violation */
}

REPAIR
#define TEST 1
OK */
void foo() {

/*

const char* s = "(Date should be in the form " "??" "-??" "-??" ")"; /*
OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 4
2. Origin: Misra Guidelines - Rule 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 11
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-3-1

Identifiers (internal and external) shall not rely on the significance of more than 31 characters
[MISRA2004-5_1-3]
DESCRIPTION
Identifiers shall not have more than 31 characters.

BENEFITS
Rule ensures porting of code between compilers/linkers without requiring
modification (shortening) of identifier names.

EXAMPLE
void this_is_not_ok_11111111111111111( );

/* Violation */

struct ThisClassHasANameThatIsTooBig11111
{
int a;
};

/* Violation */

REPAIR
void this_is_ok_11111111111( );

/* OK */

struct ThisClassHasANameThatIsOK
{
int a;
};

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 11

Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [MISRA2004-5_2_a-3]
DESCRIPTION
Do not hide names of global variables and parameters.

BENEFITS
Hiding names of global variables or parameters
can lead to errors and confusion.

EXAMPLE
int x;
void foo( ) {
int x;
/* Violation */
x = 3;
}

REPAIR
Avoid hiding names of global variables and parameters.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4

Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [MISRA2004-5_2_b-3]
DESCRIPTION
Do not hide names of local variables.

BENEFITS
Hiding names of local variables can lead to errors and confusion.

EXAMPLE
int foo( ) {
int a;
{
int a;
}
}

/* Violation */

REPAIR
Avoid hiding names of local variables.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4

Do not reuse typedef names [MISRA2004-5_3_a-3]


DESCRIPTION
Typedef names shall not be reused.

BENEFITS
Reuse of typedef names can lead to errors and confusion.

EXAMPLE
typedef int MyInt;
void foo()
{
double MyInt; /* Violation */
}

REPAIR
typedef int MyInt;
void foo()
{
double MyVar; /* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 17

Do not reuse typedef names as a typedef name [MISRA2004-5_3_b-3]


DESCRIPTION
Typedef names shall not be reused as a typedef name.

BENEFITS
Reuse of typedef names can lead to errors and confusion.

EXAMPLE
typedef unsigned char uint8_t;
void foo()
{
typedef signed char uint8_t; /* Violation */
}

REPAIR
typedef unsigned char uint8_t;
void foo()
{
typedef signed char int8_t; /* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 17

A tag name shall not be reused for other purpose within the program [MISRA2004-5_4_a-3]
DESCRIPTION
"No tag name shall be reused for any other purpose within the program.
ISO 9899:1990 does not define the behaviour when an aggregate declaration
uses a tag in different forms of type specifier."

BENEFITS
Reuse of tag names can lead to errors and confusion.

EXAMPLE
struct stag { int a; };
void stag(void){}

// Violation

REPAIR
struct stag { int a; };
void foo(void){}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4

A tag name shall not be reused to define a different tag [MISRA2004-5_4_b-3]


DESCRIPTION
"No tag name shall be reused to define a different tag.
ISO 9899:1990 does not define the behaviour when an aggregate declaration
uses
a tag in different forms of type specifier. Either all uses of the tag
should
be in structure type specifiers, or all uses should be in union type
specifiers"

BENEFITS
Reuse of tag names can lead to errors and confusion.

EXAMPLE
struct stag { int a; int b; };
void foo1()
{
union stag
}

{ int a; float b; }; // Violation

void foo2(void)
{
struct stag { int a; };
}

// Violation

REPAIR
struct stag { int a; int b; };
void foo1()
{
union union_tag
}
void foo2(void)
{

{ int a; float b; }; // OK

struct new_stag { int a; };

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4

No object or function identifier with static storage duration should be reused [MISRA20045_5_a-4]
DESCRIPTION
Static object or function identifier shall not be reused for any other
purpose within the program.

BENEFITS
Reuse of static identifiers can lead to errors and confusion.

EXAMPLE
static float a;
static void foo()
{
int a;
/* Violation */
int foo; /* Violation */
}

REPAIR
Do not use static identifiers for any other purpose within the program.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4

No object or function identifier with static storage duration should be reused [MISRA20045_5_b-4]
DESCRIPTION
Object or function identifier with static storage duration should be
unique.

BENEFITS
Reuse of identifier names can lead to errors and confusion.

EXAMPLE
static
static
{
static
static
}

float a;
void foo()
int a ; /* Violation */
int foo; /* Violation */

REPAIR
Do not use the same names for different static object or functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4

No identifier in one name space should have the same spelling as an identifier in another
name space, with the exception of structure and union member names [MISRA2004-5_6-4]
DESCRIPTION
"ISO C defines a number of different name spaces. It is technically
possible to use the same name in separate name spaces to represent
completely different items. However this practice is deprecated because
of the confusion it can cause, and so names should not be reused, even
in separate name spaces."
There are four namespaces in the C Language
1. Label names
2. Tags of structure, unions and enumerations
3. Members of structs and unions; each struct/union as a separate
namespace
4. All other identifiers; e.g. enum constants, variables, functions,
typedefs

NOTES
The output message shows only the first place (line) where the same
name is used in the other name space.

EXCEPTIONS
"An exception to this rule is the naming of members of structures,
where members names may be reused within separate structures."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
typedef struct MyStruct // tags name space
{
int Member;
// members name space
} MyStruct;
// Violation - identifiers name space

REPAIR
typedef struct MyStruct
{
int Member;
} MyStructObj;

// tags name space


// members name space
// OK - identifiers name space

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 12
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-6

No identifier name should be reused [MISRA2004-5_7-4]


DESCRIPTION
No identifier name should be reused.
Regardless of scope, no identifier should be re-used across any files
in the system. This rule checks if all members names are unique.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
struct air_speed
{
int speed;
} * x;
struct gnd_speed
{
int speed;
} * y;

/* Violation */

REPAIR
Do not use the same names for different members.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. ISO/DIS 26262
point 8.4.4

The plain char type shall be used only for the storage and use of character values
[MISRA2004-6_1-3]
DESCRIPTION
"The plain char type shall be used only for the storage and use of
character values.
The only permissible operators on plain char types are assignment
and equality operators (=, ==, != )"

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
char a = 65;
/* Violation */
void foo( ) {
a = 66;
/* Violation */
a++;
/* Violation */
if (a < 67) /* Violation */
{
}
}

REPAIR
char a = 'A';
/* OK */
void foo( ) {
a = 'B';
/* OK */
if (a == 'C') /* OK */
{
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6

2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-11

signed and unsigned char type shall be used only for the storage and use of numeric values
[MISRA2004-6_2-3]
DESCRIPTION
signed and unsigned char type shall be used only for the storage
and use of numeric values. The signedness of the plain char type is
implementation-defined and should not be relied upon.

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
signed char a = 'A';
void foo( ) {
unsigned char a = 'B';
if (a == 'C')
{
}
if (a < 'D')
{
}

/* Violation */
/* Violation */
/* Violation */

/* Violation */

REPAIR
signed char a = 65;
void foo( ) {
unsigned char a = 66;
if (a == 67)
{
}
if (a < 68)
{
}
}

/* OK */
/* OK */
/* OK */

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-12

typedefs that indicate size and signedness should be used in place of the basic types
[MISRA2004-6_3-3]
DESCRIPTION
"The basic numerical types of signed and unsigned variants of char, int,
short, long, and float, double should not be used, but specific-length
typedefs should be used."
Rule reports a violation message if basic numerical type is used
( e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA-013

EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- plain char, boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)

BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."

EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
short* v_short,
float& r_float)
{
double h;
const int z = 1;
return 1;

/* Violation (for return type) */


/* Violation */
/* Violation */
/* Violation */
/* Violation */

REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
char ch;
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}

/* OK (plain char) */
/* OK (typedef name starts with 'bool'

/* OK (bit-bield type) */
/*
/*
/*
/*
/*

OK
OK
OK
OK
OK

(plain char) */
(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */

/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 18 Portable Code - 18.1 Data Abstraction - Port. Rec. 1

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.28 Portable Code, AV Rule 209

Bit fields shall only be defined to be of type unsigned int or signed int [MISRA2004-6_4-3]
DESCRIPTION
"Bit fields shall only be defined to be of type unsigned int or signed
int.
Using int is implementation-defined because bit fields of type int can be
either signed or unsigned. The use of enum, short or char types for bit
fields
is not allowed because the behaviour is undefined."

BENEFITS
Prevents implementation-defined behaviour.

EXAMPLE
enum Enum { E1, E2};
struct Struct
{
unsigned char f1:2;
unsigned short f2:2;
unsigned long f3:2;
enum Enum
f4:2;
int
f5:2;
};

/*
/*
/*
/*
/*

Violation
Violation
Violation
Violation
Violation

REPAIR
struct Struct
{
unsigned int
unsigned int
unsigned int
signed int
signed int
};

REFERENCES

f1:2;
f2:2;
f3:2;
f4:2;
f5:2;

/*
/*
/*
/*
/*

OK
OK
OK
OK
OK

*/
*/
*/
*/
*/

*/
*/
*/
*/
*/

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 6
2. Origin: Misra Guidelines - Rule 111
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.20 Unions and Bit Fields, AV Rule 154

Bit fields of signed types shall be at least 2 bits long [MISRA2004-6_5-3]


DESCRIPTION
Avoid using bit fields of signed types which are less than two bits long.
This rule enforces that all fields of signed types are at least 2 bits
long.
See also: MISRA2004-6_4

BENEFITS
Rule prevents the potential pitfalls and erroneous code.

EXAMPLE
struct MyStruct {
signed int si01:1;
signed int si02:1;
};

/* Violation */
/* Violation */

REPAIR
struct MyStruct {
signed int si01:2;
unsigned int si02:1;
};

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. Origin: Misra Guidelines - Rule 112

Octal constants (other than zero) and octal escape sequences shall not be used [MISRA20047_1-3]
DESCRIPTION
"Any integer constant beginning with a '0' (zero) is treated as octal.
So there is a danger, for example, with writing fixed length constants.
Octal escape sequences can be problematic because the inadvertent
introduction of a decimal digit ends the octal escape and introduces
another character. It is better not to use octal constants or escape
sequences at all and to statically check for any occurrences.
The integer constant zero (written as a single numeric digit) is, strictly
speaking, an octal constant, but is a permitted exception to this rule.
Additionally \0 is the only permitted octal escape sequence."

EXCEPTIONS
Rule ignores any #pragma parasoft / codewizard directives.
Rule ignores any values inside asm blocks.

BENEFITS
Rule increases readability and maintainability.
Rule prevents using implementation-defined values.

EXAMPLE
void foo()
{
int code1;
int code2;
int code3;
code1 = 052;
/* Violation */
code2 = 071;
/* Violation */
code3 = '\100'; /* Violation */
}

REPAIR

void foo1()
{
int code1;
int code2;
int code3;
code1 = 42;
code2 = 57;
code3 = 64;

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 7
2. Origin: Misra Guidelines - Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 149
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-2

The static storage class specifier shall be used in definitions and declarations of objects and
functions that have internal linkage [MISRA2004-8_11-3]
DESCRIPTION
"It is good practice to apply the static keyword consistently to
all declarations of objects and functions with internal linkage."
See also: CODSTA-81

BENEFITS
Rule improves good programming style and readability.

EXAMPLE
/* file.h */
static int x;
/* file.c */
#include "file.h"
extern int x;

/* Violation */

REPAIR
/* file.h */
static int x;
/* file.c */
#include "file.h"
static int x;

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 138

When an array is declared with external linkage, its size shall be stated explicitly or defined
implicitly by initialisation [MISRA2004-8_12-3]
DESCRIPTION
"When an array is declared with external linkage, its size shall be stated
explicitly or defined implicitly by initialisation.
Although it is possible to declare an array of incomplete type and access
its elements, it is safer to do so when the size of the array may be
explicitly determined."

BENEFITS
Rule prevents undefined behaviour and improves safety of code.

EXAMPLE
extern int array2[ ]; /* Violation */
extern int array1[ ]; /* Violation */

REPAIR
int array2[ ] = { 0, 10, 15 };
extern int array1[ 10 ];

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-3

Whenever a function is declared or defined, its type shall be explicitly stated [MISRA20048_2_a-3]
DESCRIPTION
If return types are not explicitly declared, functions will implicitly
receive
int as the return type. However, the compiler will still generate a
warning
for a missing return type. To avoid confusion, functions that do not
return
a value should specify void as the return type. This rule detects if you
do not
explicitly declare return types in functions.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
foo1( void );
/* Violation */
static foo2( void ); /* Violation */
const foo3( void ); /* Violation */
foo4(int i){
return i;
}

/* Violation */

foo5(int i){
return;
}

/* Violation */

REPAIR
int foo1( void );
/* OK */
static int foo2( void ); /* OK */
const int foo3( void ); /* OK */
int foo4(int i){
return i;

/* OK */

}
void foo5(int i){
return;
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Misra Guidelines - Rule 75
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.2 Functions - Rec. 20
From: 9 Functions - 9.4 Return types and Values - Rule. 33

Whenever an object is declared or defined, its type shall be explicitly stated [MISRA20048_2_b-3]
DESCRIPTION
The rule reports violations on declarations of parameters and variables
where
the type is not explicitly stated.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
extern x;
const y;
z;

/* Violation
/* Violation
/* Violation

*/
*/
*/

void foo(const i); /* Violation


void foo(const i){} /* Violation

*/
*/

REPAIR
extern int x;
const int y;
int z;

/* OK
/* OK
/* OK

*/
*/
*/

void foo(const int i); /* OK


void foo(const int i){} /* OK

*/
*/

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 8

Use identical types in declaration and definition [MISRA2004-8_3_a-3]


DESCRIPTION
For each function parameter the type given in the declaration and
definition
shall be identical, and the return types shall also be identical.

BENEFITS
Rule prevents undefined behaviour and improves readability.

EXAMPLE
typedef int MyInt;
typedef MyInt MyInt2;
int foo1( );
MyInt foo1( ) {
return 0;
}

/* Violation */

MyInt2 foo2( );
int foo2( ) {
return 0;
}

/* Violation */

REPAIR
typedef int MyInt;
typedef MyInt MyInt2;
int foo1( );
int foo1( ) {
return 0;
}

/* OK */

MyInt2 foo2( );
MyInt2 foo2( ) {
return 0;
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 72

Use identical types in declaration and definition [MISRA2004-8_3_b-3]


DESCRIPTION
For each function parameter the type given in the declaration and
definition shall be identical, and the return types shall also be
identical.

BENEFITS
Rule prevents undefined behaviour and improves readability.

EXAMPLE
typedef int MyInt1;
typedef MyInt1 MyInt2;
void
void
void
void

foo1(
foo1(
foo2(
foo2(

MyInt1
int a,
int a,
int a,

a, int
MyInt1
MyInt1
MyInt2

b
b
b
b

);/* Violation */
) {}
);/* Violation */
) {}

b
b
b
b

);
/* OK */
) {}
);
/* OK */
) {}

REPAIR
typedef int MyInt1;
typedef MyInt1 MyInt2;
void
void
void
void

foo1(
foo1(
foo2(
foo2(

MyInt1
MyInt1
int a,
int a,

a, int
a, int
MyInt2
MyInt2

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 72

There shall be no definitions of objects or functions in a header file [MISRA2004-8_5-3]


DESCRIPTION
"Header files should be used to declare objects, functions, typedefs,
and macros. Header files shall not contain or produce definitions of
objects
or functions (or fragment of functions or objects) that occupy storage."
See also: PFO-01

NOTES
Rule is enabled only for C language.
"A header file is defined as any file that is included via #include,
as opposed to any file with the .h suffix."

BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.

EXAMPLE
/* file.h */
int var1;
const int var2;
static int var3;
static const int var4;
extern const int var5 = 5;

/*
/*
/*
/*
/*

Violation
Violation
Violation
Violation
Violation

*/
*/
*/
*/
*/

void foo1(){}
extern void foo2(){}
inline void foo3(){}
static void foo4(){}

/*
/*
/*
/*

Violation
Violation
Violation
Violation

*/
*/
*/
*/

/* file.c */
#include "file.h"

REPAIR
/* file.h */
extern int var1;
extern const int var2;
extern const int var5;

/* OK */
/* OK */
/* OK */

void foo1();
extern void foo2();
inline void foo3();

/* OK */
/* OK */
/* OK */

/* file.c */
#include "file.h"
int var1;
const int var2;
static int var3;
static const int var4;
const int var5 = 5;
void foo1(){}
void foo2(){}
inline void foo3(){}
static void foo4(){}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8

Always declare functions at file scope [MISRA2004-8_6-3]


DESCRIPTION
Functions shall always be declared at file scope.
Declaring functions at block scope may be confusing,
and can lead to undefined behaviour.

BENEFITS
Rule prevents undefined behaviour and improves readability.

EXAMPLE
void foo1( ) {
void foo2( );
}

/* Violation */

REPAIR
void foo2( );
void foo1( ) {
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 68
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 107
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-2

Objects shall be defined at block scope if they are only accessed from within a single function
[MISRA2004-8_7-3]
DESCRIPTION
"The scope of objects shall be restricted to functions where possible.
It is considered good practice to avoid making identifiers global
except where necessary. Whether objects are declared at the outermost
or innermost block is largely a matter of style."

NOTES
Rule checks only variables with internal linkage.
No violation is reported if variable is not used at all.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
static int max = 10; /* Violation */
void foo( ) {
while(max >= 0) {
max--;
}
}

REPAIR
void foo( ) {
int max = 10; /* OK */
while(max >= 0) {
max--;
}
}

REFERENCES

MISRA-C:2004 Guidelines for the use of the C language in critical systems


Chapter 6, Section 8

Braces shall be used to indicate and match the structure in the non-zero initialization of arrays
and structures [MISRA2004-9_2-3]
DESCRIPTION
"ISO C requires initializer lists for arrays, structures and union types
to be
enclosed in a single pair of braces (though the behaviour if this is not
done
is undefined). The rule given here goes further in requiring the use
of additional braces to indicate nested structures.
The zero initialization of arrays or structures shall only be applied
at the top level. The non-zero initialization of arrays or structures
requires an explicit initializer for each element."

NOTES
Rule checks only up to three-level nested bracket initialization.

EXCEPTIONS
"All the elements of arrays or structures can be initialized (to zero or
NULL)
by giving an explicit initializer for the first element only. If this
method
of initialization is chosen then the first element should be initialized
to zero (or NULL), and nested braces need not be used."

BENEFITS
"This forces the programmer to explicitly consider and demonstrate the
order
in which elements of complex data types are initialized"

EXAMPLE
int y[3][2] = { 1, 2, 3, 4, 5, 6 }; // Violation
struct S {
int i;

struct T {
int j;
}t;
} s = {1, 2}; // Violation

REPAIR
int y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // OK
struct S {
int i;
struct T {
int j;
}t;
} s = {1, { 2 }}; // OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Misra Guidelines - Rule 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 144
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-2

In an enumerator list, the "=" construct shall not be used to explicitly initialise members other
than the first, unless all items are explicitly initialised [MISRA2004-9_3-3]
DESCRIPTION
"In enumerator list, the '=' construct shall not be used
to explicitly initialize members other than the first,
unless all items are explicitly initialized."

BENEFITS
Helps avoid errors and confusion.

EXAMPLE
enum TEST { /* Violation */
X = 1,
Y,
Z = 3,
};
enum TEST2 { /* Violation */
X2,
Y2 = 2,
Z2,
};
enum TEST3 { /* Violation */
X3,
Y3,
Z3 = 3,
};

REPAIR
enum TEST { /* OK */
X,
Y,
Z,
};

enum TEST2 { /* OK */
X2 = 1,
Y2,
Z2,
};
enum TEST3 { /* OK */
X3 = 1,
Y3 = 2,
Z3 = 3,
};

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Origin: Misra Guidelines - Rule 32
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-3

MISRA2008
MISRA C++ 2008
RULES
Every defined function shall be called at least once [MISRA2008-0_1_10-3]
There shall be no unused parameters (named or unnamed) in nonvirtual
functions [MISRA2008-0_1_11-3]
A project shall not contain unreachable code in 'else' block [MISRA20080_1_1_a-3]
A project shall not contain unreachable code after 'return', 'break',
'continue', and 'goto' statements [MISRA2008-0_1_1_b-3]
A project shall not contain unreachable code in 'if/else/while/for' block
[MISRA2008-0_1_1_c-3]
A project shall not contain unreachable code in switch statement
[MISRA2008-0_1_1_d-3]
A project shall not contain unreachable code in 'for' loop [MISRA20080_1_1_e-3]
A project shall not contain unreachable code after 'if' or 'switch'
statement outside 'for/while/catch' block [MISRA2008-0_1_1_f-3]
A project shall not contain unreachable code after 'if' or 'switch'
statement inside 'while/for/catch' block [MISRA2008-0_1_1_g-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_a-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_b-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_c-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_d-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_e-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_f-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_g-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_h-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_i-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_j-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_k-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_l-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_m-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_n-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_o-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_p-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_q-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_r-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_rz-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_s-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_sz-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_t-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_u-3]

A project shall not contain infeasible paths [MISRA2008-0_1_2_v-3]


A project shall not contain infeasible paths [MISRA2008-0_1_2_w-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_x-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_y-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_z-3]
A project shall not contain unused variables [MISRA2008-0_1_3_a-3]
A project shall not contain unused variables [MISRA2008-0_1_3_b-3]
The value returned by a function having a non-void return type that is not
an overloaded operator shall always be used [MISRA2008-0_1_7-3]
All functions with void return type shall have external side effect(s)
[MISRA2008-0_1_8-3]
An object shall not be assigned to an overlapping object [MISRA20080_2_1_a-3]
An object shall not be assigned to an overlapping object [MISRA20080_2_1_b-3]
If a function generates error information, then that error information
shall be tested [MISRA2008-0_3_2-3]
Use of floating-point arithmetic shall be documented [MISRA2008-0_4_2-3]
Classes should not be derived from virtual bases [MISRA2008-10_1_1-4]
An accessible base class shall not be both virtual and non-virtual in the
same hierarchy [MISRA2008-10_1_3-3]
There shall be no more than one definition of each virtual function on
each path through the inheritance hierarchy [MISRA2008-10_3_1-3]
Each overriding virtual function shall be declared with the virtual
keyword [MISRA2008-10_3_2-3]
A virtual function shall only be overridden by a pure virtual function if
it is itself declared as pure virtual [MISRA2008-10_3_3-3]
Member data in non-POD class types shall be private [MISRA2008-11_0_1-3]
An object's dynamic type shall not be used from the body of its
constructor or destructor [MISRA2008-12_1_1-3]
All constructors of a class should explicitly call a constructor for all
of its immediate base classes and all virtual base classes [MISRA200812_1_2-4]
All constructors that are callable with a single argument of fundamental
type shall be declared explicit [MISRA2008-12_1_3-3]
A copy constructor shall only initialize its base classes and the
nonstatic members of the class of which it is a member [MISRA2008-12_8_13]
The copy assignment operator shall be declared protected or private in an
abstract class [MISRA2008-12_8_2-3]
A copy constructor shall be declared when there is a template constructor
with a single parameter that is a generic parameter [MISRA2008-14_5_2-3]
A copy assignment operator shall be declared when there is a template
assignment operator with a parameter that is a generic parameter

[MISRA2008-14_5_3-3]
In a class template with a dependent base, any name that may be found in
that dependent base shall be referred to using a qualified-id or this->
[MISRA2008-14_6_1-3]
All partial and explicit specializations for a template shall be declared
in the same file as the declaration of their primary template [MISRA200814_7_3-3]
Overloaded function templates shall not be explicitly specialized
[MISRA2008-14_8_1-3]
The viable function set for a function call should either contain no
function specializations, or only contain function specializations
[MISRA2008-14_8_2-4]
An exception object should not have pointer type [MISRA2008-15_0_2-4]
Control shall not be transferred into a try or catch block using a goto or
a switch statement [MISRA2008-15_0_3-3]
The assignment-expression of a throw statement shall not itself cause an
exception to be thrown [MISRA2008-15_1_1-3]
NULL shall not be thrown explicitly [MISRA2008-15_1_2-3]
An empty throw (throw;) shall only be used in the compound statement of a
catch handler [MISRA2008-15_1_3-3]
Exceptions shall be raised only after start-up and before termination of
the program [MISRA2008-15_3_1-3]
There should be at least one exception handler to catch all otherwise
unhandled exceptions [MISRA2008-15_3_2-4]
Handlers of a function-try-block implementation of a class constructor or
destructor shall not reference non-static members from this class or its
bases [MISRA2008-15_3_3-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point
[MISRA2008-15_3_4_a-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point
[MISRA2008-15_3_4_b-3]
A class type exception shall always be caught by reference [MISRA200815_3_5-3]
Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases, the
handlers shall be ordered most-derived to base class [MISRA2008-15_3_6-3]
A class destructor shall not exit with an exception [MISRA2008-15_5_1-3]
Where a function's declaration includes an exception-specification, the
function shall only be capable of throwing exceptions of the indicated
type(s) [MISRA2008-15_5_2-3]
The terminate() function shall not be called implicitly [MISRA2008-15_5_33]

#include directives in a file shall only be preceded by other preprocessor


directives or comments [MISRA2008-16_0_1-3]
Macros shall only be #define'd or #undef'd in the global namespace
[MISRA2008-16_0_2-3]
#undef shall not be used [MISRA2008-16_0_3-3]
Function-like macros shall not be defined [MISRA2008-16_0_4-3]
Arguments to a function-like macro shall not contain tokens that look like
preprocessing directives [MISRA2008-16_0_5-3]
In the definition of a function-like macro, each instance of a parameter
shall be enclosed in parentheses, unless it is used as the operand of # or
## [MISRA2008-16_0_6-3]
Undefined macro identifiers shall not be used in #if or #elif preprocessor
directives, except as operands to the defined operator [MISRA2008-16_0_73]
If the # token appears as the first token on a line, then it shall be
immediately followed by a preprocessing token [MISRA2008-16_0_8-3]
The defined preprocessor operator shall only be used in one of the two
standard forms [MISRA2008-16_1_1-3]
All #else, #elif and #endif preprocessor directives shall reside in the
same file as the #if or #ifdef directive to which they are related
[MISRA2008-16_1_2-3]
Macros shall not be used [MISRA2008-16_2_1_a-3]
The #ifndef and #endif pre-processor directives will only be used to
prevent multiple inclusions of the same header file [MISRA2008-16_2_1_b-3]
The following pre-processor directives shall not be used: #if, #elif,
#else, #ifdef, #undef, #pragma [MISRA2008-16_2_1_c-3]
C++ macros shall only be used for: include guards, type qualifiers, or
storage class specifiers [MISRA2008-16_2_2-3]
Include guards shall be provided [MISRA2008-16_2_3-3]
The ', ", /* or // characters shall not occur in a header file name
[MISRA2008-16_2_4-3]
The \ character should not occur in a header file name [MISRA2008-16_2_54]
There shall be at most one occurrence of the # or ## operators in a single
macro definition [MISRA2008-16_3_1-3]
The # and ## operators should not be used [MISRA2008-16_3_2-4]
All uses of the #pragma directive shall be documented [MISRA2008-16_6_1-3]
Reserved identifiers, macros and functions in the standard library shall
not be defined, redefined or undefined [MISRA2008-17_0_1_a-3]
Reserved identifiers, macros and functions in the standard library shall
not be defined, redefined or undefined [MISRA2008-17_0_1_b-3]
The names of standard library macros and objects shall not be reused
[MISRA2008-17_0_2-3]

The names of standard library functions shall not be overridden


[MISRA2008-17_0_3-3]
The setjmp macro and the longjmp function shall not be used [MISRA200817_0_5-3]
The C library shall not be used [MISRA2008-18_0_1-3]
The library functions atof, atoi and atol from library <cstdlib> shall not
be used [MISRA2008-18_0_2-3]
The library functions abort, exit, getenv and system from library
<cstdlib> shall not be used [MISRA2008-18_0_3-3]
The time handling functions of library <ctime> shall not be used
[MISRA2008-18_0_4-3]
The unbounded functions of library <cstring> shall not be used [MISRA200818_0_5-3]
The macro offsetof shall not be used [MISRA2008-18_2_1-3]
Dynamic heap memory allocation shall not be used [MISRA2008-18_4_1-3]
The signal handling facilities of <csignal> shall not be used [MISRA200818_7_1-3]
The error indicator errno shall not be used [MISRA2008-19_3_1-3]
The stream input/output library <cstdio> shall not be used [MISRA200827_0_1-3]
Different identifiers shall be typographically unambiguous [MISRA20082_10_1-3]
Identifiers declared in an inner scope shall not hide an identifier
declared in an outer scope [MISRA2008-2_10_2_a-3]
Identifiers declared in an inner scope shall not hide an identifier
declared in an outer scope [MISRA2008-2_10_2_b-3]
A class, union or enum name (including qualification, if any) shall be a
unique identifier [MISRA2008-2_10_4_a-3]
A class, union or enum name (including qualification, if any) shall be a
unique identifier [MISRA2008-2_10_4_b-3]
The identifier name of a non-member object or function with static storage
duration should not be reused [MISRA2008-2_10_5_a-4]
The identifier name of a non-member object or function with static storage
duration should not be reused [MISRA2008-2_10_5_b-4]
If an identifier refers to a type, it shall not also refer to an object or
a function in the same scope [MISRA2008-2_10_6-3]
Only those escape sequences that are defined in ISO/IEC 14882:2003 shall
be used [MISRA2008-2_13_1-3]
Octal constants (other than zero) and octal escape sequences (other than
"\0") shall not be used [MISRA2008-2_13_2-3]
A "U" suffix shall be applied to all octal or hexadecimal integer literals
of unsigned type [MISRA2008-2_13_3-3]
Literal suffixes shall be upper case [MISRA2008-2_13_4-3]

Narrow and wide string literals shall not be concatenated [MISRA20082_13_5-3]


Trigraphs shall not be used [MISRA2008-2_3_1-3]
Digraphs should not be used [MISRA2008-2_5_1-4]
The character sequence /* shall not be used within a C-style comment
[MISRA2008-2_7_1-3]
Sections of code shall not be "commented out" using C-style comments
[MISRA2008-2_7_2-3]
Sections of code should not be "commented out" using C++ comments
[MISRA2008-2_7_3-4]
It shall be possible to include any header file in multiple translation
units without violating the One Definition Rule [MISRA2008-3_1_1-3]
Functions shall not be declared at block scope [MISRA2008-3_1_2-3]
When an array is declared, its size shall either be stated explicitly or
defined implicitly by initialization [MISRA2008-3_1_3-3]
Objects or functions with external linkage shall be declared in a header
file [MISRA2008-3_3_1-3]
If a function has internal linkage then all re-declarations shall include
the static storage class specifier [MISRA2008-3_3_2-3]
An identifier declared to be an object or type shall be defined in a block
that minimizes its visibility [MISRA2008-3_4_1-3]
The types used for an object, a function return type, or a function
parameter shall be token-for-token identical in all declarations and redeclarations [MISRA2008-3_9_1-3]
typedefs that indicate size and signedness should be used in place of the
basic numerical types [MISRA2008-3_9_2-4]
The underlying bit representations of floating-point values shall not be
used [MISRA2008-3_9_3-3]
NULL shall not be used as an integer value [MISRA2008-4_10_1-3]
Literal zero (0) shall not be used as the null-pointer-constant
[MISRA2008-4_10_2-3]
Expressions with type bool shall not be used as operands to built-in
operators other than the assignment operator =, the logical operators &&,
||, !, the equality operators == and !=, the unary & operator, and the
conditional operator [MISRA2008-4_5_1-3]
Expressions with type enum shall not be used as operands to built-in
operators other than [ ], =, ==, !=, <, <=, >, >=, and the unary &
operator [MISRA2008-4_5_2-3]
Expressions with type (plain) char and wchar_t shall not be used as
operands to built-in operators other than the assignment operator =, the
equality operators == and !=, and the unary & operator [MISRA2008-4_5_3-3]
If the bitwise operators ~ and << are applied to an operand with an
underlying type of unsigned char or unsigned short, the result shall be
immediately cast to the underlying type of the operand [MISRA2008-5_0_10-

3]
The plain char type shall only be used for the storage and use of
character values [MISRA2008-5_0_11-3]
signed char and unsigned char type shall only be used for the storage and
use of numeric values [MISRA2008-5_0_12-3]
The condition of an if-statement and the condition of an iterationstatement shall have type bool [MISRA2008-5_0_13-3]
The first operand of a conditional-operator shall have type bool
[MISRA2008-5_0_14-3]
Array indexing shall be the only form of pointer arithmetic [MISRA20085_0_15-3]
Subtraction between pointers shall only be applied to pointers that
address elements of the same array [MISRA2008-5_0_17-3]
>, >=, <, <= shall not be applied to objects of pointer type, except where
they point to the same array [MISRA2008-5_0_18-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_a-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_b-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_c-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_d-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_a-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_b-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_c-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_d-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_e-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_f-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_g-3]
Non-constant operands to a binary bitwise operator shall have the same
underlying type [MISRA2008-5_0_20-3]
Bitwise operators shall only be applied to operands of unsigned underlying
type [MISRA2008-5_0_21-3]
Limited dependence should be placed on C++ operator precedence rules in
expressions [MISRA2008-5_0_2_a-4]

Limited dependence should be placed on C++ operator precedence rules in


expressions [MISRA2008-5_0_2_b-4]
Limited dependence should be placed on C++ operator precedence rules in
expressions [MISRA2008-5_0_2_c-4]
Limited dependence should be placed on C++ operator precedence rules in
expressions [MISRA2008-5_0_2_d-4]
Limited dependence should be placed on C++ operator precedence rules in
expressions [MISRA2008-5_0_2_e-4]
Limited dependence should be placed on C++ operator precedence rules in
expressions [MISRA2008-5_0_2_f-4]
A cvalue expression shall not be implicitly converted to a different
underlying type [MISRA2008-5_0_3_a-3]
A cvalue expression shall not be implicitly converted to a different
underlying type [MISRA2008-5_0_3_b-3]
A cvalue expression shall not be implicitly converted to a different
underlying type [MISRA2008-5_0_3_c-3]
An implicit integral conversion shall not change the signedness of the
underlying type [MISRA2008-5_0_4_a-3]
An implicit integral conversion shall not change the signedness of the
underlying type [MISRA2008-5_0_4_b-3]
There shall be no implicit floating-integral conversions [MISRA20085_0_5_a-3]
There shall be no implicit floating-integral conversions [MISRA20085_0_5_b-3]
There shall be no implicit floating-integral conversions [MISRA20085_0_5_c-3]
An implicit integral or floating-point conversion shall not reduce the
size of the underlying type [MISRA2008-5_0_6_a-3]
An implicit integral or floating-point conversion shall not reduce the
size of the underlying type [MISRA2008-5_0_6_b-3]
An implicit integral or floating-point conversion shall not reduce the
size of the underlying type [MISRA2008-5_0_6_c-3]
There shall be no explicit floating-integral conversions of a cvalue
expression [MISRA2008-5_0_7_a-3]
There shall be no explicit floating-integral conversions of a cvalue
expression [MISRA2008-5_0_7_b-3]
An explicit integral or floating-point conversion shall not increase the
size of the underlying type of a cvalue expression [MISRA2008-5_0_8-3]
An explicit integral conversion shall not change the signedness of the
underlying type of a cvalue expression [MISRA2008-5_0_9-3]
The right hand operand of a logical && or || operator shall not contain
side effects [MISRA2008-5_14_1-3]
The comma operator shall not be used [MISRA2008-5_18_1-3]

Each operand of a logical && or || shall be a postfix-expression


[MISRA2008-5_2_1-3]
The increment (++) and decrement (--) operators should not be mixed with
other operators in an expression [MISRA2008-5_2_10-4]
The comma operator, && operator and the || operator shall not be
overloaded [MISRA2008-5_2_11-3]
An identifier with array type passed as a function argument shall not
decay to a pointer [MISRA2008-5_2_12-3]
A pointer to a virtual base class shall only be cast to a pointer to a
derived class by means of dynamic_cast [MISRA2008-5_2_2-3]
Casts from a base class to a derived class should not be performed on
polymorphic types [MISRA2008-5_2_3-4]
C-style casts (other than void casts) and functional notation casts (other
than explicit constructor calls) shall not be used [MISRA2008-5_2_4-3]
A cast shall not remove any const or volatile qualification from the type
of a pointer or reference [MISRA2008-5_2_5-3]
A cast shall not convert a pointer to a function to any other pointer
type, including a pointer to function type [MISRA2008-5_2_6-3]
An object with pointer type shall not be converted to an unrelated pointer
type, either directly or indirectly [MISRA2008-5_2_7-3]
An object with integer type or pointer to void type shall not be converted
to an object with pointer type [MISRA2008-5_2_8-3]
A cast should not convert a pointer type to an integral type [MISRA20085_2_9-4]
Each operand of the ! operator, the logical && or the logical || operators
shall have type bool [MISRA2008-5_3_1-3]
The unary minus operator shall not be applied to an expression whose
underlying type is unsigned [MISRA2008-5_3_2-3]
The unary & operator shall not be overloaded [MISRA2008-5_3_3-3]
Evaluation of the operand to the sizeof operator shall not contain side
effects [MISRA2008-5_3_4-3]
The right hand operand of a shift operator shall lie between zero and one
less than the width in bits of the underlying type of the left hand
operand [MISRA2008-5_8_1-3]
Assignment operators shall not be used in sub-expressions [MISRA20086_2_1-3]
Floating-point expressions shall not be directly or indirectly tested for
equality or inequality [MISRA2008-6_2_2-3]
Before preprocessing, a null statement shall only occur on a line by
itself; it may be followed by a comment, provided that the first character
following the null statement is a white-space character [MISRA2008-6_2_33]
The statement forming the body of a switch, while, do while or for
statement shall be a compound statement [MISRA2008-6_3_1-3]

An if ( condition ) construct shall be followed by a compound statement.


The else keyword shall be followed by either a compound statement, or
another if statement [MISRA2008-6_4_1-3]
All if ... else if constructs shall be terminated with an else clause
[MISRA2008-6_4_2-3]
A switch statement shall be a well-formed switch statement [MISRA20086_4_3_a-3]
A switch statement shall be a well-formed switch statement [MISRA20086_4_3_b-3]
A switch statement shall be a well-formed switch statement [MISRA20086_4_3_c-3]
A switch statement shall be a well-formed switch statement [MISRA20086_4_3_d-3]
A switch statement shall be a well-formed switch statement [MISRA20086_4_3_e-3]
A switch-label shall only be used when the most closely-enclosing compound
statement is the body of a switch statement [MISRA2008-6_4_4-3]
An unconditional throw or break statement shall terminate every non-empty
switch-clause [MISRA2008-6_4_5-3]
The final clause of a switch statement shall be the default-clause
[MISRA2008-6_4_6-3]
The condition of a switch statement shall not have bool type [MISRA20086_4_7-3]
Every switch statement shall have at least one case-clause [MISRA20086_4_8-3]
A for loop shall contain a single loop-counter which shall not have
floating type [MISRA2008-6_5_1-3]
If loop-counter is not modified by -- or ++, then, within condition, the
loop-counter shall only be used as an operand to <=, <, > or >=
[MISRA2008-6_5_2-3]
The loop-counter shall not be modified within condition or statement
[MISRA2008-6_5_3-3]
The loop-counter shall be modified by one of: --, ++, -=n, or +=n; where n
remains constant for the duration of the loop [MISRA2008-6_5_4-3]
A loop-control-variable other than the loop-counter shall not be modified
within condition or expression [MISRA2008-6_5_5-3]
A loop-control-variable other than the loop-counter which is modified in
statement within a body of the loop shall have type bool [MISRA2008-6_5_63]
Any label referenced by a goto statement shall be declared in the same
block, or in a block enclosing the goto statement [MISRA2008-6_6_1-3]
The goto statement shall jump to a label declared later in the same
function body [MISRA2008-6_6_2-3]

The continue statement shall only be used within a well-formed for loop
[MISRA2008-6_6_3-3]
For any iteration statement there shall be no more than one break or goto
statement used for loop termination [MISRA2008-6_6_4-3]
A function shall have a single point of exit at the end of the function
[MISRA2008-6_6_5-3]
A variable which is not modified shall be const qualified [MISRA20087_1_1-3]
A pointer parameter in a function shall be declared as pointer to const if
the corresponding object is not modified [MISRA2008-7_1_2_a-3]
A reference parameter in a function shall be declared as reference to
const if the corresponding object is not modified [MISRA2008-7_1_2_b-3]
Declare a type of parameter as typedef to pointer to const if the pointer
is not used to modify the addressed object [MISRA2008-7_1_2_c-3]
The global namespace shall only contain main, namespace declarations and
extern "C" declarations [MISRA2008-7_3_1-3]
The identifier main shall not be used for a function other than the global
function main [MISRA2008-7_3_2-3]
There shall be no unnamed namespaces in header files [MISRA2008-7_3_3-3]
using-directives shall not be used [MISRA2008-7_3_4-3]
Multiple declarations for an identifier in the same namespace shall not
straddle a using-declaration for that identifier [MISRA2008-7_3_5-3]
All usage of assembler shall be documented [MISRA2008-7_4_1-3]
Assembler instructions shall only be introduced using the asm declaration
[MISRA2008-7_4_2-3]
Assembly language shall be encapsulated and isolated [MISRA2008-7_4_3-3]
A function shall not return a reference or a pointer to an automatic
variable (including parameters), defined within the function [MISRA20087_5_1-3]
The address of an object with automatic storage shall not be assigned to
another object that may persist after the first object has ceased to exist
[MISRA2008-7_5_2-3]
A function shall not return a reference or a pointer to a parameter that
is passed by reference or const reference [MISRA2008-7_5_3-3]
Functions should not call themselves, either directly or indirectly
[MISRA2008-7_5_4-4]
An init-declarator-list or a member-declarator-list shall consist of a
single init-declarator or member-declarator respectively [MISRA2008-8_0_13]
Parameters in an overriding virtual function shall either use the same
default arguments as the function they override, or else shall not specify
any default arguments [MISRA2008-8_3_1-3]
Functions shall not be defined using the ellipsis notation [MISRA20088_4_1-3]

The identifiers used for the parameters in a re-declaration of a function


shall be identical to those in the declaration [MISRA2008-8_4_2-3]
All exit paths from a function with non-void return type shall have an
explicit return statement with an expression [MISRA2008-8_4_3-3]
All variables shall have a defined value before they are used [MISRA20088_5_1-3]
Braces shall be used to indicate and match the structure in the non-zero
initialization of arrays and structures [MISRA2008-8_5_2-3]
In an enumerator list, the = construct shall not be used to explicitly
initialize members other than the first, unless all items are explicitly
initialized [MISRA2008-8_5_3-3]
const member functions shall not return non-const pointers or references
to class-data [MISRA2008-9_3_1-3]
Protected member functions shall not return non-const handles to classdata [MISRA2008-9_3_2_a-3]
Public member functions shall not return non-const handles to class-data
[MISRA2008-9_3_2_b-3]
If a member function can be made static then it shall be made static,
otherwise if it can be made const then it shall be made const [MISRA20089_3_3-3]
Unions shall not be used [MISRA2008-9_5_1-3]
Bit-fields shall be either bool type or an explicitly unsigned or signed
integral type [MISRA2008-9_6_2-3]
Bit-fields shall not have enum type [MISRA2008-9_6_3-3]
Named bit-fields with signed integer type shall have a length of more than
one bit [MISRA2008-9_6_4-3]

Every defined function shall be called at least once [MISRA2008-0_1_10-3]


DESCRIPTION
"Every defined function shall be called at least once."
The rule reports a violation if a defined function is not used in provided
translation units

SINCE
v7.2

NOTES
The rule checks following functions:
- in C:
- static functions,
- in C++:
- non-template global static functions,
- non-template global functions in anonymous namespaces,
- non-template non-static non-operator private member functions

BENEFITS
"Functions or procedures that are not called may be symptomatic of a
serious
problem, such as missing paths."

EXAMPLE
static void foo() // Violation
{
/* ... */
}
int main()
{
return (0);
}

REPAIR
static void foo() // OK
{
/* ... */
}
int main()
{
foo();
return (0);
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-10

There shall be no unused parameters (named or unnamed) in nonvirtual functions


[MISRA2008-0_1_11-3]
DESCRIPTION
"There shall be no unused parameters (named or unnamed) in non-virtual
functions."

SINCE
v7.2

EXCEPTIONS
"An unnamed parameter in the definition of a function that is used as
a callback does not violate this rule."

BENEFITS
"Unused function parameters are often due to design changes and can
lead to mismatched parameter lists."

EXAMPLE
int Foo(int i, int k)
{
i = 5;
return i;
}

// Violation

REPAIR
int Foo(int i)
{
i = 5;
return i;
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-11

A project shall not contain unreachable code in 'else' block [MISRA2008-0_1_1_a-3]


DESCRIPTION
There shall be no unreachable code in "else" statement.
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
See also: MISRA2004-14_1_b, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo(int a, int b)
{
if(a == a){
a = a + b;
}
else{
// Violation
a = a - b;
}
}

REPAIR
void foo(int a, int b)
{
if(a == 3){
a = a + b;
}

else{
a = a - b;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

A project shall not contain unreachable code after 'return', 'break', 'continue', and 'goto'
statements [MISRA2008-0_1_1_b-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code after 'return', 'break',
'continue' and 'goto' statements.
See also: MISRA2004-14_1_a, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// Violation
foo();
case 2:
j = 3;
return j; // Violation
foo();
}
}

REPAIR
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// OK
case 2:
j = 3;
return j; // OK
}
foo();
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

A project shall not contain unreachable code in 'if/else/while/for' block [MISRA2008-0_1_1_c-3]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code inside if/while/for/else block if in a
condition
a constant value is used.
See also: The groups of rules MISRA2004-14_1 and MISRA2004-13_7

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo()
{
int unreachable_code = 1;
if(0)
{
unreachable_code = 2;
}
}

// Violation

REPAIR
There shall be no unreachable code

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

A project shall not contain unreachable code in switch statement [MISRA2008-0_1_1_d-3]


DESCRIPTION
There shall be no unreachable code in "switch" statement.
Rule detects statements, expressions placed outside case and default body.
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo( int i ) {
switch (i) {
// Violation
i = 0;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}

REPAIR
void foo( int i ) {
switch (i) {
// OK
case 0:
i = 0;
break;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

A project shall not contain unreachable code in 'for' loop [MISRA2008-0_1_1_e-3]


DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation if a 'for' loop contains in condition single
relational expression 'VAR < FB', 'VAR <= FB', 'FB > VAR', 'FB >= VAR'
that result is always false, where FB is a constant or a const variable
and VAR is a variable assigned in for-init-statement.
If a result of for-condition is always false then a body is never
executed.
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_f, MISRA2004-14_1_g

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
void foo( int i, int j )
{
for ( i = 0; i < 0; i++ )
{
j = 1;
}
}

// Violation

REPAIR
void foo( int i, int j )
{
for ( i = 0; i < 5; i++ )
{
j = 1;
}
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

A project shall not contain unreachable code after 'if' or 'switch' statement outside
'for/while/catch' block [MISRA2008-0_1_1_f-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation if:
- the code is after 'if/else' construction, where each branch has
unconditional
'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_g

SINCE
v7.0

NOTES
This rule does not report violations on the code inside loop.
Rule MISRA2004-14_1_g reports violations on the code inside loop.

BENEFITS
Rule helps avoid useless code.

EXAMPLE
int foo1( int c ) {

if ( c > 2 ) {
return 0;
} else {
return 1;
}
return c;

// Violation

// unreachable code

}
int foo2( int i ) {
switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return 2;
}
return i;
}

// Violation

// unreachable code

REPAIR
int foo1( int
if ( c > 2
return
} else {
return
}
}

c ) {
) {
0;

// OK

c;

int foo2( int i ) {


switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return i;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

A project shall not contain unreachable code after 'if' or 'switch' statement inside
'while/for/catch' block [MISRA2008-0_1_1_g-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation on the code inside loop if:
- the code is after 'if/else' construction, where each branch has
unconditional
'break', 'continue' or 'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_f

SINCE
v7.0

BENEFITS
Rule helps avoid useless code.

EXAMPLE
int foo( int c ) {
while ( c > 1 ) {
if ( c > 2 ) {
continue;
} else {
break;
}

// Violation

c++;

// unreachable code

}
for (int i = 0; i > 1; i++ ) {
switch(i){
// Violation
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}
c++;
// unreachable code
}
return c;
}

REPAIR
int foo( int c ) {
while ( c > 1 ) {
c++;
if ( c > 2 ) {
continue;
} else {
break;
}
}

// OK

for (int i = 0; i > 1; i++ ) {


c++;
switch(i){
// OK
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}

}
return c;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1

A project shall not contain infeasible paths [MISRA2008-0_1_2_a-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a <= 1)&&(a >= 2));
if((a < 1)&&(a > 2));
if((a >= 2)&&(a <= 1));
if((a > 2)&&(a < 1));
}

//
//
//
//

Violation
Violation
Violation
Violation

//
//
//
//

OK
OK
OK
OK

REPAIR
void myFunction(int a)
{
if((a <= 5)&&(a >= 2));
if((a < 5)&&(a > 2));
if((a >= 2)&&(a <= 5));
if((a > 2)&&(a < 5));
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_b-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b >= 2)
if(b < 2) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b >= 2)
if(b < 7) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_c-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b < 2)
if(b >= 2) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b < 2)
if(b >= 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_d-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b <= 2)
if(b < 3) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b <= 2)
if(b < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_e-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(b == 2)
if(b < 1) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(b == 2)
if(a < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_f-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 > b)
if(b < 5) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 > b)
if(b < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_g-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 >= b)
if(b < 5) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 >= b)
if(b < 1) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_h-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 < b)
if(b > 1) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 < b)
if(b > 5) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_i-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int a, int b)
{
if(2 <= b)
if(b > 1) /* Violation */
a++;
}

REPAIR
void foo(int a, int b)
{
if(2 <= b)
if(b > 5) /* OK */
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_j-3]


DESCRIPTION
The rule reports violation if a result of boolean operation with unsigned
variable is always true or always false.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunc()
{
unsigned int a;
if (a >= 0)
// Violation
a++;
}

REPAIR
void myFunc()
{
unsigned int a;
if (a >= 2)
// OK
a++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_k-3]


DESCRIPTION
The rule reports violation if a result of boolean operation with variable
of char type is always true or always false.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 128)
b++;
if (a < 256)
a++;

// Violation
// Violation

REPAIR
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 127)
b++;
if (a < 255)
a++;
}

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_l-3]


DESCRIPTION
The rule reports violation if a result of boolean operation with variable
of short type is always true or always false.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65536)
a++;
if (b <= 32767)
b++;

// Violation
// Violation

REPAIR
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65535)
a++;
if (b <= 32766)
b++;
}

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_m-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > -1)&&(a < -2));
if((a >= -1)&&(a <= -2));
if((a < -2)&&(a > -1));
if((a <= -2)&&(a >= -1));
}

//
//
//
//

Violation
Violation
Violation
Violation

//
//
//
//

OK
OK
OK
OK

REPAIR
void myFunction(int a)
{
if((a > -5)&&(a < -2));
if((a >= -5)&&(a <= -2));
if((a < -2)&&(a > -5));
if((a <= -2)&&(a >= -5));
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_n-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > 0)&&(a < -1));
if((a < -1)&&(a >= 0));
if((a == -5)&&(a == 5));
if((3 < a)&&(-3 > a));
}

//
//
//
//

Violation
Violation
Violation
Violation

//
//
//
//

OK
OK
OK
OK

REPAIR
void myFunction(int a)
{
if((a < 0)&&(a > -1));
if((a > -1)&&(a <= 0));
if((a != -5)&&(a != 5));
if((3 > a)&&(-3 < a));
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_o-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a, int b)
{
if((a > b)&&(a < b));
// Violation
if((a < b)&&(a >= b)); // Violation
}

REPAIR
void myFunction(int a, int b, int c)
{
if((a > b)&&(a < c));
// OK
if((a < b)&&(a >= c)); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_p-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a >= 0)||(a < 0));
if((5 > a)||(a > 3));
if((a <= 4)||(a >= 3));
}

// Violation
// Violation
// Violation

REPAIR
void myFunction(int a)
{
if((a >= 10)||(a < 0));
if((5 > a)||(a > 13));
if((a <= 4)||(a >= 13));
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_q-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > -4)||(a < -3));
if((-1 > a)||(-3 < a));
if((a < -3)||(-5 < a));
}

// Violation
// Violation
// Violation

REPAIR
void myFunction(int a)
{
if((a > -4)||(a < -13));
if((-11 > a)||(-3 < a));
if((a < -13)||(-5 < a));
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_r-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a)
{
if((a > -2)||(a < 1));
if((4 > a)||(-3 < a));
if((a > -4)||(2 > a));
}

// Violation
// Violation
// Violation

REPAIR
void myFunction(int a)
{
if((a < -2)||(a > 1));
if((4 < a)||(-3 > a));
if((a < -4)||(2 < a));
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_rz-3]


DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.

NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void foo(int b)
{
if(b > 2)
if(b >= 1)
/* Violation */
b++;
}

REPAIR
void foo(int b)
{
if(b > 2)
if(b >= 5)
/* OK */
b++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_s-3]


DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."

EXAMPLE
void myFunction(int a, int b)
{
if((a >= b)||(a <= b)); // Violation
if((a < b)||(a >= b));
// Violation
}

REPAIR
void myFunction(int a, int b, int c)
{
if((a >= b)||(a <= c));
// OK
if((a < c)||(a >= b));
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_sz-3]


DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN > col); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(BLUE > col); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_t-3]


DESCRIPTION
The rule reports a violation if equality operators (== and !=) or
relational
operators (<, >, <= and >=) as both operands use only constant values
or the same variable.

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE > 0);
if(10 <= ONE);
if(ci > 0);
for(i = 5; i < i; i++);
if(ZERO > 10 && i > 3);
}

//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE);
for(i = 5; i < ci; i++);
if(ZERO == en);
}

// OK
// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_u-3]


DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < GREEN); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < RED); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_v-3]


DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > YELLOW); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > RED); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_w-3]


DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(YELLOW < col); // Violation
}

REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN < col); // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_x-3]


DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1

< 0);
< 16);
<= 15);
<= 16);
> 15);
> 16);
>= 0);
>= 16);

//
//
//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation

REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1

< 1);
< 15);
<= 0);
<= 1);
> 0);
> 1);
>= 1);

//
//
//
//
//
//
//

OK
OK
OK
OK
OK
OK
OK

if(col1 >= 15); // OK


}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_y-3]


DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(15 < col1);
if(16 < col1);
if(0 <= col1);
if(16 <= col1);
if(0 > col1);
if(16 > col1);
if(15 >= col1);
if(16 >= col1);
}

//
//
//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation

REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(0 < col1);
if(1 < col1);
if(1 <= col1);
if(15 <= col1);
if(1 > col1);
if(15 > col1);
if(0 >= col1);

//
//
//
//
//
//
//

OK
OK
OK
OK
OK
OK
OK

if(1 >= col1);


}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain infeasible paths [MISRA2008-0_1_2_z-3]


DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."

BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."

EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 14 );
if(col1 != 14 );
if(14 == col1);
if(14 != col1);

//
//
//
//

Violation
Violation
Violation
Violation

REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 15);
if(col1 != 15);
if(15 == col1);
if(15 != col1);

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2

A project shall not contain unused variables [MISRA2008-0_1_3_a-3]


DESCRIPTION
This rule checks if all declared local variables are used. The rule
assumes that
a local variable is used if this variable is found inside body of function
after
definition.
See also: OPT-03, OPT-06

NOTES
Objects can perform some actions in their constructors. Even if they are
not
used later they might have done their job during creation. This rule does
not
consider such objects as "used" and will report a violation.

BENEFITS
Eliminating unused local variables increases efficiency and legibility.

EXAMPLE
class A {
public:
void displBalance();
};
void foo( ) {
A a;
}

// Violation

int func(int j) {
int i = 0; // Violation
return j;
}

REPAIR
class A {
public:
void displBalance( );
};
void foo( ) {
A a;
a.displBalance( );
}
int func(int j) {
int i = j + 1;
return i;
}

// OK

// OK

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3

A project shall not contain unused variables [MISRA2008-0_1_3_b-3]


DESCRIPTION
The rule reports a violation if a declared local variable is not used
inside
a body of function or is used only in expressions where it could be
removed
without a change of functionality.
See also: OPT-02, OPT-03

NOTES
The rule does not report violations on variables of type class/struct that
have explicitly declared constructor or destructor.

BENEFITS
Eliminating local variables that are not useful increases efficiency
and legibility of code.

EXAMPLE
class A {
};
int func(int p) {
A a;
// Violation
int i = 0; // Violation
i = p;
i++;
return p;
}

REPAIR
class A {
public:
A();

};
int func(int p) {
A a;
// OK - implicit call of constructor can cause additional
action
int i = 0; // OK
i = p;
i++;
return i;
}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3

The value returned by a function having a non-void return type that is not an overloaded
operator shall always be used [MISRA2008-0_1_7-3]
DESCRIPTION
"In C++ it is possible to call a function without using the return value,
which may be an error. The return value of a function shall always be
used."

SINCE
v7.2

EXCEPTIONS
"The return value of a function may be discarded by use of a (void) cast.
Overloaded operators are excluded, as they should behave in the same way
as built-in operators."

BENEFITS
Rule improves readability of code

EXAMPLE
short func ( short para1 )
{
return para1;
}
void discarded ( short para2 )
{
func ( para2 );
// Violation
}

REPAIR
short func ( short para1 )
{

return para1;
}
void discarded ( short para2 )
{
(void)func ( para2 );
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-7

All functions with void return type shall have external side effect(s) [MISRA2008-0_1_8-3]
DESCRIPTION
A function which does not return a value and which does not have external
side
effects will only consume time and will not contribute to the generation
of any
outputs, which may not meet developer expectations.
The following are examples of external side effects:
- Reading or writing to a file, stream, etc.;
- Changing the value of a non local variable;
- Changing the value of an argument having reference type;
- Using a volatile object;
- Raising an exception.

SINCE
v7.2

BENEFITS
Rule prevents unnecessary time consumption.

EXAMPLE
void foo( void ) // Violation
{
int local;
local = 0;
}

REPAIR
int foo( int p ) // OK
{
int local;
local = 10*p;
/* ... */
return local;

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-8

An object shall not be assigned to an overlapping object [MISRA2008-0_2_1_a-3]


DESCRIPTION
"The behaviour is undefined when two objects are created
which have some overlap in memory and one is copied to the other."
Rule detects if two different members of the same union are copied to
each other using the same object.

BENEFITS
Rule prevents undefined behaviour and data loss.

EXAMPLE
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {
union U a, b;
union U *p;
(void)memcpy( &a.dValue, &a.lValue, 8 );
(void)memcpy( &p->dValue, &p->iValue, 8 );
return 0;
}

REPAIR
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {

/* Violation */
/* Violation */

union U a, b;
union U *p, *q;
(void)memcpy( &a.dValue, &b.lValue, 8 );
(void)memcpy( &p->dValue, &q->iValue, 8 );
return 0;

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-2-1

An object shall not be assigned to an overlapping object [MISRA2008-0_2_1_b-3]


DESCRIPTION
"An object shall not be assigned to an overlapping object."
Rule detects if two different members of the same union are assigned
to each other using the same object

SINCE
v7.2

BENEFITS
"Assigning between objects that have an overlap in their physical storage
leads to undefined behaviour."

EXAMPLE
union U {
int
long
double
};

iValue;
lValue;
dValue;

void main( ) {
union U a, b;
union U *p;
a.dValue = a.lValue;
p->dValue = p->iValue;
}

REPAIR
union U {
int
long
double
};

iValue;
lValue;
dValue;

// Violation
// Violation

void main( ) {
union U a, b;
union U *p, *q;
a.dValue = b.lValue;
p->dValue = q->iValue;
}

// OK
// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-2-1

If a function generates error information, then that error information shall be tested
[MISRA2008-0_3_2-3]
DESCRIPTION
"A function (whether it is part of the standard library, a third party
library
or a user defined function) may provide some means of indicating the
occurrence
of an error. This may be via an error flag, some special return value or
some
other means. Whenever such a mechanism is provided by a function the
calling
program shall check for the indication of an error as soon as the function
returns.
However, note that the checking of input values to functions is considered
a more robust means of error prevention than trying to detect errors after
the function has completed (see Rule MISRA2004-20_3). Note also that the
use
of errno (to return error information from functions) is clumsy and should
be
used with care (see Rule MISRA2004-20_5)."

NOTES
Rules checks usage of function calls which returns char, short, int, enum,
or typedef to char, short, int, or enum value and reports violation when
this value is not assigned, checked or cast to void.

BENEFITS
Rule helps writing safety code.

EXAMPLE
int SomeFunctionReturningError( );
void foo( )
{
SomeFunctionReturningError( ); // Violation
}

REPAIR
int SomeFunctionReturningError( );
int foo( )
{
int x;
x = SomeFunctionReturningError( );
(void)SomeFunctionReturningError( );
if (SomeFunctionReturningError( ));
switch (SomeFunctionReturningError( )) {
}
return SomeFunctionReturningError( );
}

//
//
//
//

OK
OK
OK
OK

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 86
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 115
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-3-2
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 7
6. http://cwe.mitre.org/data/definitions/391.html

Use of floating-point arithmetic shall be documented [MISRA2008-0_4_2-3]


DESCRIPTION
"If floating-point is to be used, then the following issues need to be
covered
as part of the deviation process:
- A justification explaining why floating-point is the appropriate
or only solution.
- Demonstrate that appropriate skills are available.
- Demonstrate that an appropriate process is being applied.
- Document the floating-point implementation."
Rule checks if in previous or the same line as floating-point arithmetic
expression there is a comment.

SINCE
v7.2

BENEFITS
"The safe use of floating-point arithmetic requires a high level of
numerical
analysis skills and indepth knowledge of the compiler and target
hardware."

EXAMPLE
// Violation in line: double d = d1 + d2;
double add(double d1, double d2)
{
double d = d1 + d2;
}

REPAIR
double add(double d1, double d2)
{
double d = d1 + d2; // OK - floating point arithmetic
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-4-2

Classes should not be derived from virtual bases [MISRA2008-10_1_1-4]


DESCRIPTION
"The use of virtual bases is not recommended."

SINCE
v7.2

BENEFITS
"The use of virtual base classes can introduce a number of undefined
and potentially confusing behaviours."

EXAMPLE
class B {};
class D: public virtual B {}; // Violation

REPAIR
Do not inherit from virtual base classes

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-1-1

An accessible base class shall not be both virtual and non-virtual in the same hierarchy
[MISRA2008-10_1_3-3]
DESCRIPTION
A base class shall not be both virtual and non-virtual
in the same hierarchy.

SINCE
v7.1

BENEFITS
Hierarchy becomes easier to comprehend and use.

EXAMPLE
class A {};
class B : virtual A {};
class C : B, A {};

// Violation

REPAIR
class A {};
class B : virtual A {};
class C : B, virtual A {};

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 89
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-1-3
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

There shall be no more than one definition of each virtual function on each path through the
inheritance hierarchy [MISRA2008-10_3_1-3]
DESCRIPTION
"The main aim of this rule is clarity for maintainers and reviewers,
by ensuring that the version of a function that can be executed from
any point in a class hierarchy is unambiguous."

SINCE
v7.2

EXCEPTIONS
"Destructors may be declared virtual in multiple members of a class
hierarchy.
If a function is declared pure and defined in the same class, then that
definition is ignored for this rule."

BENEFITS
"Additionally, where classes form a diamond hierarchy, call
by dominance may occur resulting in a call to a function that
is inconsistent with developer expectations.
This rule also prevents call by dominance."

EXAMPLE
/* Examples of incorrect code */
class A
{
public:
virtual void f1 ( );
virtual void f2 ( ) { }
};
void A::f1 ( )
{
}

class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
};
void B::f2 ( )
{
}

// Violation

// Violation

REPAIR
/* Examples of
class A
{
public:
virtual
virtual
virtual
};
void A::f2 ( )
{
}

correct code */

void f1 ( );
void f2 ( ) = 0;
~A(){}

class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
virtual ~B(){}
};
void B::f2 ( )
{
}

// OK
// OK
// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-1

Each overriding virtual function shall be declared with the virtual keyword [MISRA200810_3_2-3]
DESCRIPTION
Using the virtual keyword whenever a subclass implements a virtual
function
makes the code more readable, because the reader does not have to refer
back
to the base class to see that the function is virtual. This rule detects
if a subclass implements a virtual function without using a virtual
keyword.

BENEFITS
Readability, as well as more intuitive behavior for deep inheritance
hierarchies, in that functions that are virtual in a base class will
remain virtual in all inherited classes.

EXAMPLE
class A {
public:
virtual int foo( );
};
class B : public A {
public:
int foo( );
};
int B::foo() {
return 5;
}

REPAIR
class A {
public:
virtual int foo( );
};

// Violation

class B : public A {
public:
virtual int foo( );
};

// OK

int B::foo() {
return 5;
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-3-2

A virtual function shall only be overridden by a pure virtual function if it is itself declared as
pure virtual [MISRA2008-10_3_3-3]
DESCRIPTION
"A virtual function shall only be overridden by a pure
virtual function if it is itself declared as pure virtual."

SINCE
v7.2

BENEFITS
Rule prevents writing a code contrary to developer expectations.

EXAMPLE
class A
{
public:
virtual void foo ( );
};
class B: public A
{
public:
virtual void foo ( ) = 0; // Violation
};

REPAIR
Do not override non-pure virtual functions by pure virtual functions

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-3

Member data in non-POD class types shall be private [MISRA2008-11_0_1-3]


DESCRIPTION
"Member data in non-POD class types shall be private."
non-POD class types are such for which at least one
of following conditions is met:
- is a class (classes are not PODs)
- is a struct/union that:
+ has user declared constructor
+ has private or protected non-static data member
+ has base class
+ has virtual function
+ has non-static member with type non-POD (or array of non-POD)
+ has non-static member with type reference
+ has user declared copy assignment operator
+ has user declared destructor

SINCE
v7.2

BENEFITS
"By implementing class interfaces with member functions,
the implementation retains more control over how the object
state can be modified, and helps to allow a class to be
maintained without affecting clients.

EXAMPLE
typedef signed int int32_t;
class C
{
public:
int32_t b; // Violation
protected:
int32_t c; // Violation
};

REPAIR
typedef signed int int32_t;
class C
{
private:
int32_t b; // OK
int32_t c; // OK
protected:
const int32_t access_b();
const int32_t access_c();
};

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 11, Rule 11-0-1

An object's dynamic type shall not be used from the body of its constructor or destructor
[MISRA2008-12_1_1-3]
DESCRIPTION
"During construction and destruction of an object, its final type
may be different to that of the completely constructed object."
"Member functions (including virtual member functions) can be called for
an
object under construction. Similarly, an object under construction can be
the
operand of the typeid operator or of a dynamic_cast. However, if these
operations are performed in a ctor-initializer (or in a function called
directly or indirectly from a ctor-initializer) before all the meminitializers
for base classes have completed, the result of the operation is
undefined."

SINCE
v7.2

BENEFITS
"The result of using an object's dynamic type in a constructor or
destructor may not be consistent with developer expectations."

EXAMPLE
/* Examples of incorrect code */
#include <typeinfo>
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
typeid ( B2 );
// Violation
foo ( );
// Violation
dynamic_cast< B2* > ( this ); // Violation

}
};

REPAIR
/* Examples of correct code */
#include <typeinfo>
class B1
{
public:
B1 ( )
{
typeid ( B1 ); // OK - B1 not polymorphic
}
};
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
B2::foo ( );
// OK - not a virtual call
}
};

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-1
2. ISO/DIS 26262
point 8.4.4

All constructors of a class should explicitly call a constructor for all of its immediate base
classes and all virtual base classes [MISRA2008-12_1_2-4]
DESCRIPTION
"All constructors of a class should explicitly call a constructor for all
of
its immediate base classes and all virtual base classes."

SINCE
v7.2

NOTES
Rule will also report a violation if class does not define any
constructors
and has a base class with a constructor.

BENEFITS
This rule reduces confusion over which constructor will be used,
and with what parameters.

EXAMPLE
class A
{
public:
A ( )
{
}
};

class B : public A
{
public:
B ( ) // Violation
{

}
};

REPAIR
class A
{
public:
A ( )
{
}
};

class B : public A
{
public:
B ( ): A() // OK
{
}
};

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-2

All constructors that are callable with a single argument of fundamental type shall be declared
explicit [MISRA2008-12_1_3-3]
DESCRIPTION
"All constructors that are callable with a single argument
of fundamental type shall be declared explicit."

SINCE
v7.2

NOTES
The following types are fundamental: bool, char, short, int,
long, long long, float, double, long double, wchar_t.

BENEFITS
Rule prevents the constructor from being used to implicitly
convert from a fundamental type to the class type.

EXAMPLE
class C
{
public:
C ( int a ) // Violation
{
}
};

REPAIR
class C
{
public:
explicit C ( int a ) // OK
{

}
};

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-3

A copy constructor shall only initialize its base classes and the nonstatic members of the
class of which it is a member [MISRA2008-12_8_1-3]
DESCRIPTION
"If a compiler implementation detects that a call to a copy constructor
is redundant, then it is permitted to omit that call, even if the copy
constructor has a side effect other than to construct a copy of the
object."
Rule reports a violation if global or static member variable is modified
within a copy constructor.

SINCE
v7.2

NOTES
Rule checks only one nested level of function call.

BENEFITS
"It is therefore important to ensure that a copy constructor does not
modify
the program state as the number of such modifications may be
indeterminate."

EXAMPLE
class A
{
public:
A ( A const & rhs )
: m_i ( rhs.m_i )
{
++m_static;
// Violation
}
private:
int m_i;
static int m_static;

};

REPAIR
Do not modify global or static member variable within a copy constructor.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-1

The copy assignment operator shall be declared protected or private in an abstract class
[MISRA2008-12_8_2-3]
DESCRIPTION
"An abstract class represents the interface part of a hierarchy.
Invoking the copy assignment operator from the top of such
a hierarchy bypasses the underlying implementation resulting
in only the base subobjects being copied."

SINCE
v7.2

NOTES
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.

BENEFITS
"Making the abstract copy assignment operator protected allows
access from the derived classes but not from outside the hierarchy.
Making the copy assignment operator private is a common idiom used
to restrict copying objects of the class type."

EXAMPLE
typedef int int32_t;
class B1
{
public:
virtual void f( ) = 0;
B1 & operator= ( B1 const & rhs );
};

REPAIR

// Violation

typedef int int32_t;


class B1
{
public:
virtual void f( ) = 0;
protected:
B1 & operator= ( B1 const & rhs );
};

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-2

A copy constructor shall be declared when there is a template constructor with a single
parameter that is a generic parameter [MISRA2008-14_5_2-3]
DESCRIPTION
"Contrary to possible developer expectations, a template constructor
will not suppress the compiler generated copy constructor."

SINCE
v7.2

NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].

BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.

EXAMPLE
typedef signed int int32_t;
class A
{
public:
A ( );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};

// Violation

REPAIR
typedef signed int int32_t;
class A
{
public:
A ( );
A ( A const & rhs );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A copy assignment operator shall be declared when there is a template assignment operator
with a parameter that is a generic parameter [MISRA2008-14_5_3-3]
DESCRIPTION
"Contrary to possible developer expectations, a template assignment
operator will not suppress the compiler generated copy assignment
operator."

SINCE
v7.2

NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.

BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.

EXAMPLE
typedef signed int int32_t;
class A
// Violation
{
public:
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;

}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}

REPAIR
typedef signed int int32_t;
class A
// OK
{
public:
A & operator= ( A const & rhs )
{
i = rhs.i;
return *this;
}
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;
}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems

Chapter 6, Section 14, Rule 14-5-3


2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

In a class template with a dependent base, any name that may be found in that dependent
base shall be referred to using a qualified-id or this-> [MISRA2008-14_6_1-3]
DESCRIPTION
"In a class template with a dependent base, any name that may be found in
that
dependent base shall be referred to using a qualified-id or this->"

SINCE
v7.2

BENEFITS
"Using a qualified-id or prefixing the identifier with this-> ensures that
the entity chosen is consistent with developer expectations."

EXAMPLE
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
TYPE t = 0; // Violation
g ( );
// Violation
i++;
// Violation
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );

int i;
};
template class A<int>;

REPAIR
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
::TYPE t1 = 0; // OK ::g ( );
// OK ::i++;
// OK typename B<T>::TYPE t2
this->g ( );
this->i;
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );
int i;
};
template class A<int>;

explicit use
explicit use
explicit use
= 0; // OK // OK // OK -

global TYPE
global func
global var
explicit use base TYPE
explicit use base "g"
explicit use base "i"

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-6-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff

Document issued on: January 11, 2002

All partial and explicit specializations for a template shall be declared in the same file as the
declaration of their primary template [MISRA2008-14_7_3-3]
DESCRIPTION
"It is undefined behaviour if, for a set of template-arguments, an
implicit
instantiation is generated by the compiler, and a partial or explicit
specialization is declared or defined elsewhere in the program that would
match the set of template-arguments."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
// file.h
template <typename T> void foo () {}
// file.cpp
#include "file.h"
template <> void foo<int> () {} // Violation

REPAIR
// file.h
template <typename T> void foo () {}
template <> void foo<int> () {} // OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-7-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Overloaded function templates shall not be explicitly specialized [MISRA2008-14_8_1-3]


DESCRIPTION
"Overloaded function templates shall not be explicitly specialized.
Explicit specializations will be considered only after overload resolution
has chosen a best match from the set of primary function templates."

SINCE
v7.2

BENEFITS
"Where a template is not overloaded with other templates, or is overloaded
with non-template functions then it can be explicitly specialized, as it
is
consistent with developer expectation that the explicit specializations
will only be considered if that primary template is chosen."

EXAMPLE
template <typename T> void f ( T );
template <typename T> void f ( T* );
template <> void f<int*> ( int* ); // Violation

REPAIR
template <typename T> void f ( T );
template <> void f<int*> ( int* ); // OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff

Document issued on: January 11, 2002

The viable function set for a function call should either contain no function specializations, or
only contain function specializations [MISRA2008-14_8_2-4]
DESCRIPTION
"The viable function set for a function call should either contain no
function
specializations, or only contain function specializations. If a function
and a specialization of a function template are deemed equivalent after
overload resolution, the non-specialized function will be chosen over the
function specialization"

SINCE
v7.2

EXCEPTIONS
"Rule does not apply to copy constructors or copy assignment operators."

BENEFITS
Rule prevents writing of code that may be inconsistent
with developer expectations.

EXAMPLE
void f ( short b){}
template <typename T> void f ( T ){}

// Example 1
// Example 2

void b ( short s )
{
f ( s );
// Violation - Calls Example 1
f ( s + 1 ); // Violation - Calls Example 2
}

REPAIR
void f ( short b){}

// Example 1

template <typename T> void f ( T ){}

// Example 2

void b ( short s )
{
f<> ( s );
// OK - Calls Example 2
f<> ( s + 1 ); // OK - Calls Example 2
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

An exception object should not have pointer type [MISRA2008-15_0_2-4]


DESCRIPTION
"If an exception object of pointer type is thrown and that pointer refers
to a dynamically created object, then it may be unclear which function
is responsible for destroying it, and when."

SINCE
v7.2

BENEFITS
Prevents memory management problems

EXAMPLE
typedef short int16_t;
class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( &a1 ); // Violation pointer type thrown
}
else
{
throw ( a2 ); // Violation pointer type thrown
}
}

REPAIR
typedef short int16_t;

class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( a1 ); // OK
}
else
{
throw ( *a2 ); // OK
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. ISO/DIS 26262
point 8.4.4

Control shall not be transferred into a try or catch block using a goto or a switch statement
[MISRA2008-15_0_3-3]
DESCRIPTION
"A program is ill-formed if control is transferred into a try or catch
block
using a goto or switch statement; however, not all compilers issue
a diagnostic message."

SINCE
v7.2

BENEFITS
Rule detects errors not reported by all compilers

EXAMPLE
/* The code is compilable with MSVC 6.0 */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
try
{
Label_10: // Violation
case 2:
// Violation
break;
}
catch ( Exception e )
{
}
}

REPAIR
/* The example of correct code */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
// OK
try
{
// ...
}
catch ( Exception e )
{
}
case 2:
// OK
break;
}
Label_10:
// OK
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The assignment-expression of a throw statement shall not itself cause an exception to be


thrown [MISRA2008-15_1_1-3]
DESCRIPTION
"If an exception is thrown when constructing the exception object, or when
evaluating the assignment expression that initializes the exception
object,
it is that exception that propagates in preference to the one that was
about
to be thrown."

SINCE
v7.2

BENEFITS
Rule improves readability of code

EXAMPLE
class E
{
public:
E ( )
{
throw 10;
}
};
int foo1()
{
try
{
if ( 0 )
{
throw E ( ); // Violation
}
}
catch(...)
{

}
}

REPAIR
class E
{
public:
E ( ){ }
};
int foo()
{
try
{
if ( 0 )
{
throw E ( ); // OK
}
}
catch(...)
{
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

NULL shall not be thrown explicitly [MISRA2008-15_1_2-3]


DESCRIPTION
"throw(NULL) (equivalent to throw(0)) is never a throw of the
null-pointer-constant and so is only ever caught by an integer handler.
This may be inconsistent with developer expectations, particularly if
the program only has handlers for pointer-to-type exceptions."

SINCE
v7.2

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
#define NULL 0
void foo()
{
try
{
throw ( NULL ); // Violation
}
catch ( int i )
// NULL exception handled here
{
// ...
}
}

REPAIR
#define NULL 0
void foo()
{
try
{
throw ( 0 ); // OK

}
catch ( int i ) // NULL exception handled here
{
// ...
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

An empty throw (throw;) shall only be used in the compound statement of a catch handler
[MISRA2008-15_1_3-3]
DESCRIPTION
"An empty throw re-throws the temporary object that represents an
exception.
Its use is intended to enable the handling of an exception to be split
across
two or more handlers.
However, syntactically, there is nothing to prevent throw; being used
outside
a catch handler, where there is no exception object to re-throw. This may
lead
to an implementation-defined program termination."

SINCE
v7.2

BENEFITS
Rule prevents implementation-defined behaviour.

EXAMPLE
class Exception{};
void foo(int a)
{
Exception E;
if(a)
{
throw;
// Violation
}
}

REPAIR
class Exception{};
void foo(int a)

{
Exception E;
if(a)
{
throw E;
}

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Exceptions shall be raised only after start-up and before termination of the program
[MISRA2008-15_3_1-3]
DESCRIPTION
"Before the program starts executing the body of main, it is in a start-up
phase, constructing and initializing static objects. Similarly, after main
has
returned, it is in a termination phase where static objects are being
destroyed. If an exception is thrown in either of these phases it leads to
the
program being terminated in an implementation-defined manner."

SINCE
v7.2

NOTES
Rule checks only one level of nested function calls.

BENEFITS
"Throwing an exception during start-up or termination results in the
program
being terminated in an implementation-defined manner."

EXAMPLE
class C
{
public:
C ( )
{
throw ( 0 ); // Violation thrown before main starts
}
~C ( )
{
throw ( 0 ); // Violation thrown after main exits
}

};
C c;
int main( ... )
{
// ...
}

REPAIR
Exceptions should not be throwing during start-up or termination phase.

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

There should be at least one exception handler to catch all otherwise unhandled exceptions
[MISRA2008-15_3_2-4]
DESCRIPTION
"If a program throws an unhandled exception it terminates
in an implementation-defined manner. In particular, it is
implementation-defined whether the call stack is unwound, before
termination,
so the destructors of any automatic objects may or may not be executed.
By enforcing the provision of a "last-ditch catch-all", the developer can
ensure that the program terminates in a consistent manner."
Rule checks if outermost statement of the 'main' function is a try
statement
with catch-all handler.

SINCE
v7.2

NOTES
Rule check if a try statement with catch-all handler is implemented
directly
in 'main' function. Statements which are implemented in functions that are
called from 'main' function are not detected.

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
class Exception{};
int main( )
{
try // Violation
{
// ...
}

catch ( Exception e )
{
// ...
}
return 0;
}

REPAIR
class Exception{};
int main( )
{
try // OK
{
// ...
}
catch ( Exception e )
{
// ...
}
catch ( ... )
{
// ...
}
return 0;
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-2
2. http://cwe.mitre.org/data/definitions/391.html

Handlers of a function-try-block implementation of a class constructor or destructor shall not


reference non-static members from this class or its bases [MISRA2008-15_3_3-3]
DESCRIPTION
Accessing a non-static member of a class or a base class in the
handler (i.e. the catch part) of a function-try-block of a class
constructor/destructor is not allowed.

SINCE
v7.2

BENEFITS
"The effect of accessing a non-static member of a class or a base class in
the
handler (i.e. the catch part) of a function-try-block of a class
constructor/destructor is undefined. For example, if a memory allocation
exception is thrown during creation of the object, the object will not
exist
when the handler attempts to access its members. Conversely, in the
destructor,
the object may have been successfully destroyed before the exception is
handled, so again will not be available to the handler. By contrast, the
lifetime of a static member is greater than that of the object itself, so
the
static member is guaranteed to exist when the handler accesses it."

EXAMPLE
typedef int int32_t;
class C
{
public:
int32_t x;
C( )
try
{
// Action that may raise an exception
}

catch ( ... ) // Violation


{
if ( 0 == x ) // Non-compliant x may not exist at this point
{
// Action dependent on value of x
}
}
~C ( )
try
{
// Action that may raise an exception
}
catch ( ... ) // Violation
{
if ( 0 == x ) // Non-compliant x may not exist at this point
{
// Action dependent on value of x
}
}
};

REPAIR
Do not use non-static member of a class or a base class in the handler
of a function-try-block of a class constructor/destructor

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [MISRA2008-15_3_4_a-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown from body
of function 'main' or from body of function that does not have any
exception
on an exception specification list.
see also: EXCEPT-18

SINCE
v7.2

NOTES
Rule checks only one level of nested function calls.

BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."

EXAMPLE
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{

if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // Violation
}
}
catch ( A const & )
{
}
}

REPAIR
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // OK
}
}
catch ( A const & )
{
}
catch ( B const & )
{
}
}

REFERENCES

1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [MISRA2008-15_3_4_b-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown while
a non-local object is declared or initialized.
see also: EXCEPT-13

SINCE
v7.2

NOTES
Rule checks only one level of nested function calls.

BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."

EXAMPLE
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10 )
{

throw A ( );
}
else
{
throw B ( );
}
}
catch ( A const & )
{
}
}
};
A a; // Violation - unhandled exception of class B

REPAIR
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10
{
throw A
}
else
{
throw B
}
}
catch ( A const
{
}
catch ( B const
{
}
}
};
A a; // OK

)
( );

( );

& )

& )

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4

A class type exception shall always be caught by reference [MISRA2008-15_3_5-3]


DESCRIPTION
"If a class type exception object is caught by value, slicing occurs. That
is,
if the exception object is of a derived class and is caught as the base,
only the base classs functions (including virtual functions) can be
called.
Also, any additional member data in the derived class cannot be accessed."
Rule detects class or struct type exception object that is caught by
value.

SINCE
v7.2

BENEFITS
"If the exception is caught by reference, slicing does not occur."

EXAMPLE
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase b ) // Violation - derived type objects will be
// caught as the base type
{
}
}

REPAIR
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase &b ) // OK - exceptions caught by reference
{
}
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Where multiple handlers are provided in a single try-catch statement or function-try-block for
a derived class and some or all of its bases, the handlers shall be ordered most-derived to
base class [MISRA2008-15_3_6-3]
DESCRIPTION
"Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases,
the handlers shall be ordered most-derived to base class.
When testing to see if the type of an exception matches the type of a
handler,
a derived class exception will match with a handler for its base class.
If the base class handler is found before the handler for the derived
class,
the base class handler will be used. The derived class handler is
unreachable
code and can never be executed."

SINCE
v7.2

BENEFITS
Rule prevents writing unreachable code.

EXAMPLE
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( B &b )
{
// ...

}
catch ( D &d ) // Violation
{
// ...
}
}

REPAIR
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( D &d ) // OK - Derived class caught before base class
{
// ...
}
catch ( B &b ) // OK - Base class caught after derived class
{
// ...
}
}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A class destructor shall not exit with an exception [MISRA2008-15_5_1-3]


DESCRIPTION
This rule checks if you throw from within a destructor.
This rule is for C++ programming language only.

BENEFITS
Prevents throwing from within a destructor. It may lead to memory leaks
and improper object destruction.

EXAMPLE
class Foo {
public:
Foo( ) { }
~Foo( ) {
throw;
}
};

// Violation

REPAIR
class Exception {};
class Foo {
public:
Foo( ) { }
~Foo( ) {
try {
// OK
} catch (Exception& e) {
// caught all exceptions
}
}
};

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve

Your Programs and Design", Third Edition, Addison-Wesley,


(C) 2005 Pearson Education, Inc., Chapter 2, Item 8
2. http://www.cs.helsinki.fi/u/vihavain/s03/cpp/items/CppStyleRules2.html
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 15, Rule 15-5-1
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Where a function's declaration includes an exception-specification, the function shall only be


capable of throwing exceptions of the indicated type(s) [MISRA2008-15_5_2-3]
DESCRIPTION
"If a function declared with an exception-specification throws an
exception
of a type not included in the specification, the function unexpected()
is called. The behaviour of this function can be overridden within a
project,
but by default causes an exception of std::bad_exception to be thrown.
If std::bad_exception is not listed in the exception-specification,
then terminate() will be called, leading to implementation-defined
termination of the program."

SINCE
v7.2

NOTES
Rule checks only two levels of nested function calls

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception )
{
foo ( );
}

// Violation

REPAIR
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception, int ) // OK
{
foo ( );
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The terminate() function shall not be called implicitly [MISRA2008-15_5_3-3]


DESCRIPTION
"It is implementation-defined whether the call stack is unwound before
terminate() is called, so the destructors of any automatic objects may
or may not be executed."

SINCE
v7.2

BENEFITS
Rule prevents implementation-defined behaviour.

EXAMPLE
class C
{
public:
C() { throw 1; }
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}

REPAIR
class C
{

// Violation

public:
C()
{
try
{
/* ... */
throw 1;
}
catch(...)
{
/* ... */
}
}
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-3

#include directives in a file shall only be preceded by other preprocessor directives or


comments [MISRA2008-16_0_1-3]
DESCRIPTION
"All the #include statements in a particular code file should be grouped
together near the head of the file. The rule states that the only items
which
may precede a #include in a file are other preprocessor directives or
comments."

BENEFITS
It is important to prevent the situation of executable code coming before
a #include directive, otherwise there is danger that the code may try to
use
items which would be defined in the header.

EXAMPLE
void foo();
int g;
#include "test.h"

// Violation

REPAIR
#include "test.h"
void foo();
int g;

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-1
3. Origin: Misra Guidelines - Rule 87

Macros shall only be #define'd or #undef'd in the global namespace [MISRA2008-16_0_2-3]


DESCRIPTION
"While it is legal C to place #define or #undef directives anywhere in a
code
file, placing them inside blocks is misleading as it implies a scope
restricted
to that block, which is not the case."

BENEFITS
Improves the readability of code.

EXAMPLE
void foo( int* x ) {
#define CHECKPARAM(p) (p != 0)
if (CHECKPARAM(x)) {
/* ... */
}
#undef CHECKPARAM
}

// Violation

// Violation

REPAIR
#define CHECKPARAM(p) (p != 0) // OK - macro is defined outside of any
blocks
void foo( int* x ) {
if (CHECKPARAM(x)) {
/* ... */
}
}
#undef CHECKPARAM
// OK - macro is undefined outside of any
blocks

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 91
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-2

#undef shall not be used [MISRA2008-16_0_3-3]


DESCRIPTION
"#undef should not normally be needed.
Its use can lead to confusion with respect to the existence
or meaning of a macro when it is used in the code."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
#undef TEST

/* Violation */

REPAIR
Do not use #undef.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 92
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-3

Function-like macros shall not be defined [MISRA2008-16_0_4-3]


DESCRIPTION
Rule reports a violation on function-like macro definition.

BENEFITS
"While macros can provide a speed advantage over functions, functions
provide
a safer and more robust mechanism. This is particularly true with respect
to the type checking of parameters, and the problem of function-like
macros
potentially evaluating parameters multiple times.
See also: CODSTA-03, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40

EXAMPLE
#define SUM(A,B) ((A)+(B))

/* Violation */

void foo( int x, int y ) {


/* ... */
SUM( x, y );
/* ... */
}

REPAIR
int sum( int a, int b ) {
return (a + b);
}
void foo( int x, int y ) {
/* ... */
sum( x, y );
/* ... */
}

REFERENCES

/* OK */

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 19
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
3. Misra Guidelines - Rule 93
4. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.5 Inline Functions - Rule 35
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 29
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-4

Arguments to a function-like macro shall not contain tokens that look like preprocessing
directives [MISRA2008-16_0_5-3]
DESCRIPTION
"If any of the arguments act like preprocessor directives,
the behaviour when macro substitution is made can be unpredictable."

NOTES
Rule works only within file scope.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( #foo );
MACRO2( i, #foo );
MACRO2( i, "#foo" );
}

/* Violation */
/* Violation */
/* Violation */

REPAIR
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( i );
MACRO2( i, i );
}

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 95
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-5

In the definition of a function-like macro, each instance of a parameter shall be enclosed in


parentheses, unless it is used as the operand of # or ## [MISRA2008-16_0_6-3]
DESCRIPTION
"If parentheses are not used, then the operator precedence may not give
the desired results when the preprocessor substitutes the macro into the
code.
Within a definition of a function-like macro, the arguments shall be
enclosed
in parentheses."
See also: MISRA-096

EXCEPTIONS
If an argument of macro is used in body after '.', '->', '::' or before
'::',
then violation is not reported, because the use of paranthesis in such
cases
makes a code non-compilable. For example:
#define INIT1(member) a->member = 0 // No violation reported
#define CALL(ns,fn) ns::fn() // No violation reported

BENEFITS
Improves the readability of code and ensures operations order.

DRAWBACKS
In some cases a violation is reported, but the use of parenthesis causes a
compilation error. For example:
#define MTYPE(type, a) (type *)(a) // Violation reported
#define MT(classtype, type) classtype<type> // Violation reported

EXAMPLE
#define abs(x) ((x >= 0) ? x : -x)
void foo(int a, int b){
int z = abs(a - b);

// Violation

REPAIR
#define abs(x) (((x) >= 0) ? (x) : -(x))

// OK

void foo(int a, int b){


int z = abs(a - b);
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-6

Undefined macro identifiers shall not be used in #if or #elif preprocessor directives, except as
operands to the defined operator [MISRA2008-16_0_7-3]
DESCRIPTION
If an attempt is made to use an identifier in a preprocessor directive,
and that identifier has not been defined,
the preprocessor will sometimes not give any warning but will assume
the value zero.
#ifdef, #ifndef and defined() are provided to test the existence of a
macro,
and are therefore excluded.

BENEFITS
Complying with this rule leads to safer code
and prevents hard-to-detect errors.

DRAWBACKS
1) Currently the implementation of the rule assumes that the compliance
with
the rule is provided by following MISRA 2004 19-11 advice (p. 78):
"Consideration should be given to the use of a /#ifdef/" test before
an identifier is used."
2) If #1 is not followed, due to technical limitations we are not able
to recognize cases where preprocessor identifier is defined in different
file from that where the identifier is used. Also, we are unable to
detect
that given identifier was defined as compiler command line option.
3) If tested macro identifier was earlier defined by #define preprocessor
directive, it can not be defined in more nested #if / #elif / #else /
#endif
directives. In such cases rule can report false positives.
3) If tested macro identifier is defined within complex conditional
statement (containing
few branches #elif/#else) we cannot be sure if branch containing
definition of macro

being tested is executed. In such case rule may report false positives.

EXAMPLE
#if X
/* Violation - X undefined at this point */
#endif
#if Y
/* Violation - Y undefined at this point */
#endif
#if X + Y
/* Violation - X and Y undefined at this point */
#endif
#ifdef X
#define Y 1
#else
#define Y 3
#endif
#if Y > 2
#endif

// Violation - because of point 3

REPAIR
#define X 1
#if X
/* OK */
#endif
#ifdef Y
#if Y
/* OK - check is done in the #ifdef above */
#endif
#endif
#ifdef X
#define Y 1
#else

#define Y 3
#endif
#ifdef Y
#if Y > 2
#endif
#endif

// OK - possible workaround because of point 3

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 97
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-7

If the # token appears as the first token on a line, then it shall be immediately followed by a
preprocessing token [MISRA2008-16_0_8-3]
DESCRIPTION
"When a section of source code is excluded by preprocessor directives,
the content of each excluded statement is ignored until a #else, #elif
or #endif directive is encountered (depending on the context).
If one of these excluded directives is badly formed, it may be ignored
without warning by a compiler with unfortunate consequences.
The requirement of this rule is that all preprocessor directives shall be
syntactically valid even when they occur within an excluded block of code.
Compilers are not always consistent in enforcing this ISO requirement."

BENEFITS
Rule prevents erroneous behaviour.

EXAMPLE
#define MAX 2
int foo(void)
{
int x = 0;
#ifndef MAX
x = 1;
#else1
x = MAX;
#endif
return x;
}

REPAIR
#define MAX 2
int foo(void)
{
int x = 0;

/* Violation */

#ifndef MAX
x = 1;
#else
x = MAX;
#endif
return x;
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-8

The defined preprocessor operator shall only be used in one of the two standard forms
[MISRA2008-16_1_1-3]
DESCRIPTION
"The only two permissible forms for the defined preprocessor operator are:
- defined ( identifier )
- defined identifier
Any other form leads to undefined behaviour.
Generation of the token defined during expansion of a #if or #elif
preprocessing directive also leads to undefined behaviour and shall be
avoided,"

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#if defined X > Y
#endif
#define DEFINED defined
#if DEFINED(X)
#endif

// Violation

// Violation

REPAIR
#if defined X
#endif
#if defined (X)
#endif

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-1-1

All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if or
#ifdef directive to which they are related [MISRA2008-16_1_2-3]
DESCRIPTION
"When the inclusion and exclusion of blocks of statements is controlled
by a series of preprocessor directives, confusion can arise
if all of the relevant directives do not occur within one file."
This rule requires that the number of preprocessor directives
#if/ifdef/ifndef
matches the number of #endif directives in the file.

BENEFITS
Rule improves good code structure and
prevents maintenance problems.

EXAMPLE
/* Violation */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"

REPAIR
/* OK */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"
#endif

REFERENCES

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-1-2

Macros shall not be used [MISRA2008-16_2_1_a-3]


DESCRIPTION
Macros are generally an obsolete construct inherited from C language.
The main problems with macros are that they:
- are not type-safe
- are expanded by the preprocessor so debugging them is not possible
- can compile by pure luck creating ugly problems with the program

EXCEPTIONS
Macros are almost never necessary in C++. Exceptions to this rule are:
- #ifdef
- #ifndef
- #if
- #if defined
when used as include guards and for conditional compilation.

BENEFITS
Improves code reliability and maintainability.

EXAMPLE
#define PI 3.14

// Violation

REPAIR
const double PI = 3.14; // OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.6 Pre-Processing Directives, AV Rule 31


3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1

The #ifndef and #endif pre-processor directives will only be used to prevent multiple
inclusions of the same header file [MISRA2008-16_2_1_b-3]
DESCRIPTION
The #ifndef and #endif pre-processor directives will only be used
as defined in below example to prevent multiple inclusions of the
same header file.
#ifndef Header_filename
#define Header_filename
// Header declarations...
#endif

SINCE
v7.1

BENEFITS
Conditional code compilation should be kept to a minimum as it can
significantly obscure testing and maintenance efforts.

EXAMPLE
#ifndef MAX

// Violation

int max = 10;


#endif

// Violation

int a;

REPAIR
#ifndef FOO_H
#define FOO_H
int max = 10;
int a;

// OK

#endif

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 28
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

The following pre-processor directives shall not be used: #if, #elif, #else, #ifdef, #undef,
#pragma [MISRA2008-16_2_1_c-3]
DESCRIPTION
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include

SINCE
v7.1

BENEFITS
Limit the use of the pre-processor to those cases where it is necessary.

EXAMPLE
#pragma once // Violation

REPAIR
#ifndef FOO_H
#define FOO_H
/* ... */
#endif

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 26
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

C++ macros shall only be used for: include guards, type qualifiers, or storage class specifiers
[MISRA2008-16_2_2-3]
DESCRIPTION
"C++ macros shall only be used for include guards, type qualifiers, or
storage
class specifiers. These are the only permitted uses of macros. C++ offers
const variable and function templates, which provide a type-safe
alternative
to the preprocessor."

SINCE
v7.2

NOTES
List of type qualifiers and storage class specifiers:
// type qualifiers:
const
volatile
// storage class specifiers:
auto
register
static
extern
mutable

BENEFITS
Improves code reliability and maintainability.

EXAMPLE
#define PI 3.14

REPAIR

// Violation

#define STOR extern


// OK storage class specifier
const double PI = 3.14; // OK

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-2

Include guards shall be provided [MISRA2008-16_2_3-3]


DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-07, PFO-08, MISRA2004-19_15

BENEFITS
Rule improves maintainability and optimization of code.

EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present

REPAIR
// file foo.hh
// OK
#ifndef FOO_HH
#define FOO_HH
int i;
#endif

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 27
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-3

The ', ", /* or // characters shall not occur in a header file name [MISRA2008-16_2_4-3]
DESCRIPTION
"It is undefined behaviour if the ', ", /* or // characters are used
between < and > delimiters or the ', /* or // characters are used
between the " delimiters in a header name preprocessing token."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include "fi'le.h" // Violation

REPAIR
#include "file.h"

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-4

The \ character should not occur in a header file name [MISRA2008-16_2_5-4]


DESCRIPTION
"It is undefined behaviour if the \ character is used between < and >
delimiters or between the " delimiters in a header name preprocessing
token.
Note that this rule is only advisory, since some environments use \ as a
file
name delimiter. Compilers for these environments often support the use
of / in #include directives."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include "fi\\le.h" // Violation

REPAIR
#include "file.h"

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-5

There shall be at most one occurrence of the # or ## operators in a single macro definition
[MISRA2008-16_3_1-3]
DESCRIPTION
"There is an issue of unspecified order of evaluation associated
with the # and ## preprocessor operators.
To avoid this problem only one occurrence of either operator
shall be used in any single macro definition
(i.e. one #, or one ## or neither)."

BENEFITS
Rule improves readability and clarity of code.

EXAMPLE
#define TEST1(A,B,C) A # B # C
#define TEST2(A,B,C) A ## B # C
#define TEST3(A,B,C) A ## B ## C

/* Violation */
/* Violation */
/* Violation */

REPAIR
#define TESTa(A,B) A # B
#define TESTb(A,B) A ## B

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 98
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-1

The # and ## operators should not be used [MISRA2008-16_3_2-4]


DESCRIPTION
"There is an issue of unspecified order of evaluation associated
with the # and ## preprocessor operators.
Compilers have been inconsistent in the implementation of these operators.
To avoid these problems do not use them."

BENEFITS
Rule prevents inconsistent implementation of # and ## operators.

EXAMPLE
#define stringer( x ) printf( #x "\n" ) /* Violation */

REPAIR
Do not use # and ## preprocessor operators.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-2

All uses of the #pragma directive shall be documented [MISRA2008-16_6_1-3]


DESCRIPTION
All uses of #pragma directive shall be documented and explained.

BENEFITS
Provides readability and maintainability.

EXAMPLE
#pragma TEST

/* Violation */

/* comment in wrong place */


#pragma TEST

/* Violation */

/* comment in wrong place

*/
#pragma TEST

/* Violation */

REPAIR
// OK
#pragma TEST

/* OK */
#pragma TEST
/* OK - multiline comment
*/
#pragma TEST

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 3
2. Origin: Misra Guidelines - Rule 99
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-6-1

Reserved identifiers, macros and functions in the standard library shall not be defined,
redefined or undefined [MISRA2008-17_0_1_a-3]
DESCRIPTION
"It is generally bad practice to #undef a macro which is defined in the
standard library. It is also bad practice to #define a macro name which
is a C reserved identifier or C keyword which is the name of any macro,
object or function in the standard library.
For example, there are some specific reserved words and function names
which are known to give rise to undefined behaviour if they are redefined
or
undefined, including defined, _ _LINE_ _, _ _FILE_ _, _ _DATE_ _, _ _TIME_
_,
_ _STDC_ _, errno and assert. Generally, all identifiers that begin with
the underscore character are reserved."

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#define __A 1
// Violation
#define assert 1
// Violation
#undef __AA
// Violation
#undef assert
// Violation

REPAIR
Do not #define or #undef reserved identifiers

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114

3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1

Reserved identifiers, macros and functions in the standard library shall not be defined,
redefined or undefined [MISRA2008-17_0_1_b-3]
DESCRIPTION
"It is generally bad practice to #undef or #define names which are C
reserved words"

BENEFITS
Redefinition of reserved words can lead to errors and confusion.

EXAMPLE
#define break 1
#define continue 1
#undef while
#undef return

//
//
//
//

Violation
Violation
Violation
Violation

REPAIR
Do not #define or #undef reserved words

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1

The names of standard library macros and objects shall not be reused [MISRA2008-17_0_2-3]
DESCRIPTION
"Where the developer uses new versions of standard library macros or
objects
(e.g. to enhance functionality or add checks of input values), the
modified
macro or object shall have a new name.
This is to avoid any confusion as to whether a standard macro or object,
or a modified version of them, is being used."
Rule checks if the following reserved names are used:
- macro and typedef names from C standard library headers: assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- identifiers that begin with the underscore character
See also: NAMING-33, MISRA2004-20_2, CODSTA-93

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#define NULL ( a > b )
#define _NULL ( a > b )

// Violation
// Violation

REPAIR
#define MY_NULL ( a > b ) // OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-2

The names of standard library functions shall not be overridden [MISRA2008-17_0_3-3]


DESCRIPTION
"Where the developer uses new versions of standard library functions
(e.g. to enhance functionality or add checks of input values), the
modified
function shall have a new name. However, it is permissible to overload
the name to add new parameter types if the functionality is consistent
with those of the original. This ensures that the behaviour associated
with the name remains consistent. So, for example, if a new version of the
sqrt
function is written to check that the input is not negative, the new
function
shall not be named "sqrt", but shall be given a new name. It is
permissible
to add a new sqrt function for a type not present in the library."
Rule checks if the following reserved names are used:
- function names from C standard library headers: assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- function names that begin with the underscore character
See also: NAMING-33, MISRA2004-20_2, CODSTA-92

BENEFITS
Rule prevents undefined behaviour.

DRAWBACKS
It is not possible in static analysis to check if the functionality is
consistent
with those of the original. So, rule reports violations on all declared
functions
which names are reserved. The user should himself check if the modified
function
has the same functionality and could overload a function from standard
library.
Rule also does not have exception that permits overloading functions with

types not present in the standard library.


EXAMPLE
int printf ( int a, int b )
{
return ( ( a > b ) ? a : b );
}

// Violation

REPAIR
int my_printf ( int a, int b )
{
return ( ( a > b ) ? a : b );
}

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The setjmp macro and the longjmp function shall not be used [MISRA2008-17_0_5-3]
DESCRIPTION
"setjmp and longjmp allow the normal function call mechanisms to be
bypassed,
and shall not be used."
Rule reports a violation message if setjmp or longjmp is used and the file
includes any of the following headers: setjmp.h, setjmp, or csetjmp.

BENEFITS
Rule prevents normal function call mechanisms from being bypassed.

EXAMPLE
#include <setjmp.h>
jmp_buf mark;
int
fperr;
void foo( void ) {
int jmpret;
jmpret = setjmp( mark );
}

/* Address for long jump to jump to */


/* Global error number */

/* Violation */

void fphandler( int sig, int num ) {


longjmp( mark, -1 );
/* Violation */
}

REPAIR
Do not use the setjmp macro and the longjmp function.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 122

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.5 Libraries, AV Rule 20
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-5
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1

The C library shall not be used [MISRA2008-18_0_1-3]


DESCRIPTION
"Some C++ libraries (e.g. <cstdio>) also have corresponding C versions
(e.g. <stdio.h>). This rule requires that the C++ version is used."
The following standard C library headers are detected:
<assert.h>
<ctype.h>
<errno.h>
<float.h>
<iso646.h>
<limits.h>
<locale.h>
<math.h>
<setjmp.h>
<signal.h>
<stdarg.h>
<stddef.h>
<stdio.h>
<stdlib.h>
<string.h>
<time.h>
<wchar.h>
<wctype.h>

SINCE
v7.2

BENEFITS
Rule prevents undefined and implementation-defined behaviour.

EXAMPLE
#include <stdio.h> // Violation

REPAIR

#include <cstdio>

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The library functions atof, atoi and atol from library <cstdlib> shall not be used [MISRA200818_0_2-3]
DESCRIPTION
'atof', 'atoi' and 'atol' functions from library <stdlib.h> have undefined
behaviour associated with them when the string cannot be converted.

BENEFITS
Prevents using functions which have sometimes undefined behaviour.

EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *s; double x; int i; long l;
s = " -2309.12E-15";
x = atof( s );
/* Violation */
s = " -9885 pigs";
i = atoi( s );
/* Violation */
s = "98854 dollars";
l = atol( s );
/* Violation */
}

REPAIR
Do not use atof, atoi and atol functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 125
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 23

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-2

The library functions abort, exit, getenv and system from library <cstdlib> shall not be used
[MISRA2008-18_0_3-3]
DESCRIPTION
'abort', 'exit', 'getenv' and 'system' functions from stdlib.h, cstdlib,
or stdlib_iso.h libraries shall not be used.

BENEFITS
Prevents using functions which are not required in an embedded system.

EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *libvar;
libvar = getenv( "LIB" );
system( "dir" );
abort( );
exit( 0 );
}

/*
/*
/*
/*

Violation
Violation
Violation
Violation

*/
*/
*/
*/

REPAIR
Do not use abort, exit, getenv and system functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 126
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 24
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-3

The time handling functions of library <ctime> shall not be used [MISRA2008-18_0_4-3]
DESCRIPTION
"This library is associated with clock times.
Various aspects are implementation dependent
or unspecified, such as the formats of times."
Rule prevents inclusion of <time.h> and <ctime> headers.
See also: SECURITY-01

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include <time.h>

/* Violation */

REPAIR
Do not include time.h header.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 127
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 25
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 18, Section 7, Rule 18-0-4

The unbounded functions of library <cstring> shall not be used [MISRA2008-18_0_5-3]


DESCRIPTION
"The strcpy, strcmp, strcat, strchr, strspn, strcspn, strpbrk, strrchr,
strstr,
strtok and strlen functions within the <cstring> library can read or write
beyond the end of a buffer, resulting in undefined behaviour."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strcpy ( array, pChar ); // Violation
}

REPAIR
/* Ideally, a safe string handling library should be used.
Use of bounded functions (e.g. strncpy) is also possible. */
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strncpy ( array, pChar, 10 ); // OK
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

The macro offsetof shall not be used [MISRA2008-18_2_1-3]


DESCRIPTION
"Use of this macro can lead to undefined behaviour
when the types of the operands are incompatible or
when bit fields are used."
Rule reports a violation message if the offsetof
macro is used and the file includes any of the
following headers: stddef.h, stddef, or cstddef.

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
// Violation - The macro offsetof shall not be used. Macro is in line:
[10]
#include <stddef.h>
struct S {
int x, y, z;
char buffer[ 128 ];
};
int main( ) {
int i = offsetof( struct S, buffer );
return 0;
}

REPAIR
Do not use offsetof.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20

2. Origin: Misra Guidelines - Rule 120


3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 18
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-2-1

Dynamic heap memory allocation shall not be used [MISRA2008-18_4_1-3]


DESCRIPTION
"The use of dynamic memory can lead to out-of-storage run-time failures,
which are undesirable. The built-in new and delete operators, other than
the placement versions, use dynamic heap memory. The functions calloc,
malloc, realloc and free also use dynamic heap memory."

EXCEPTIONS
The rule allows to use a placement new.

BENEFITS
"There is a range of unspecified,
behaviour associated with dynamic
of
other potential pitfalls. Dynamic
memory
leaks, data inconsistency, memory
behaviour."

undefined and implementation-defined


memory allocation, as well as a number
heap memory allocation may lead to
exhaustion, non-deterministic

EXAMPLE
void foo()
{
int * p = new int[10]; // Violation
/* ... */
delete[] p;

// Violation

REPAIR
Do not use neither 'new' and 'delete' operators nor 'calloc', 'malloc',
'realloc' and 'free' functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Misra Guidelines - Rule 118
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-4-1
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 206
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 3

The signal handling facilities of <csignal> shall not be used [MISRA2008-18_7_1-3]


DESCRIPTION
"Signal handling contains implementation-defined and undefined behaviour."
Rule reports a violation message if a file includes any of the following
headers: signal.h, or csignal.

BENEFITS
Prevents from problems associated with implementation-defined
and undefined behaviour in signal handling.

EXAMPLE
#include <signal.h>

/* Violation */

REPAIR
Do not use <signal.h> header.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 123
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 21
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-7-1

The error indicator errno shall not be used [MISRA2008-19_3_1-3]


DESCRIPTION
"errno is a facility of C and C++, which in theory should be useful, but
which
in practice is poorly defined by the standard. A non zero value may or may
not
indicate that a problem has occurred; as a result it shall not be used.
Even for those functions for which the behaviour of errno is well defined,
it is preferable to check the values of inputs before calling the function
rather than rely on using errno to trap errors"

BENEFITS
The rule prevents undefined behaviours.

EXAMPLE
#include <errno.h>
int err_check( ) {
errno = 1;
return (errno);
}

/* Violation */
/* Violation */

REPAIR
Do not use errno.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 119
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 17

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 19, Rule 19-3-1

The stream input/output library <cstdio> shall not be used [MISRA2008-27_0_1-3]


DESCRIPTION
"Streams and file I/O have a large number of unspecified,
undefined and implementation-defined behaviours associated with them.
It is assumed that they will not normally be needed in production
code in embedded systems.
If any of the features of stdio.h need to be used in production code,
then the issues associated with the feature need to be understood."
The rule prevents inclusion of <stdio.h>, and <cstdio> headers.

BENEFITS
Prevents form problems associated with a large number of unspecified,
undefined and implementation-defined behaviour associated
with streams and file I/O.

EXAMPLE
#include <stdio.h>

/* Violation */

REPAIR
Do not use <stdio.h> library.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 124
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 22
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 27, Rule 27-0-1

Different identifiers shall be typographically unambiguous [MISRA2008-2_10_1-3]


DESCRIPTION
"Depending on the font used to display the character set, it is possible
for
certain glyphs to appear the same, even though the characters are
different.
This may lead to the developer confusing an identifier with another one.
To help reduce the chance of this, identifiers shall not differ by any
combination of:
- Only a mixture of case;
- The presence or absence of the underscore character;
- The interchange of the letter 'O', and the number '0';
- The interchange of the letter 'I', and the number '1';
- The interchange of the letter 'i', and the number '1';
- The interchange of the letter 'i', and the number 'l';
- The interchange of the letter 'I', and the letter 'l' (el);
- The interchange of the letter 'l' (el), and the number '1';
- The interchange of the letter 'S' and the number '5';
- The interchange of the letter 'Z' and the number '2';
- The interchange of the letter 'n' and the letter 'h';
- The interchange of the letter 'B' and the number '8';
- The interchange of the letter sequence 'rn' ('r' followed by 'n')
with the letter 'm'."
See also: NAMING-45.

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
typedef int id1_uint32; // Violation - interchange Z and 2
short id1_uint3Z;
// Violation - interchange Z and 2
void id2_foo(

// Violation - absence underscore

int id4_paramS, // Violation - interchange S and 5


int id4_param5
// Violation - interchange S and 5
){
int id3_abc; // Violation - mixed case
int id3_ABC; // Violation - mixed case
}
int id6_modern;

// Violation - interchange rn and m

void id2_foo_(){
// Violation - presence underscore
int id5_BO;
// Violation - interchange B and 8, O and 0
int id5_80;
// Violation - interchange B and 8, O and 0
int id6_modem; // Violation - interchange rn and m
}

REPAIR
typedef int id1_uint32_t; // OK
int id1_uint32_v;
// OK
void id2_foo_1(
// OK
int id4_param1, // OK
int id4_param2
// OK
){
int id3_abc_1; // OK
int id3_ABC_2; // OK
}
int id6_modern;

// OK

void id2_foo_2(){ // OK
int id5_BO_1; // OK
int id5_80_2; // OK
int foo_2_id6_modem; // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-10-1

Identifiers declared in an inner scope shall not hide an identifier declared in an outer scope
[MISRA2008-2_10_2_a-3]
DESCRIPTION
Do not hide names of global variables and parameters.

BENEFITS
Hiding names of global variables or parameters
can lead to errors and confusion.

EXAMPLE
int x;
void foo( ) {
int x;
/* Violation */
x = 3;
}

REPAIR
Avoid hiding names of global variables and parameters.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4

Identifiers declared in an inner scope shall not hide an identifier declared in an outer scope
[MISRA2008-2_10_2_b-3]
DESCRIPTION
Do not hide names of local variables.

BENEFITS
Hiding names of local variables can lead to errors and confusion.

EXAMPLE
int foo( ) {
int a;
{
int a;
}
}

/* Violation */

REPAIR
Avoid hiding names of local variables.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4

A class, union or enum name (including qualification, if any) shall be a unique identifier
[MISRA2008-2_10_4_a-3]
DESCRIPTION
"No tag name shall be reused for any other purpose within the program.
ISO 9899:1990 does not define the behaviour when an aggregate declaration
uses a tag in different forms of type specifier."

BENEFITS
Reuse of tag names can lead to errors and confusion.

EXAMPLE
struct stag { int a; };
void stag(void){}

// Violation

REPAIR
struct stag { int a; };
void foo(void){}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4

A class, union or enum name (including qualification, if any) shall be a unique identifier
[MISRA2008-2_10_4_b-3]
DESCRIPTION
"No tag name shall be reused to define a different tag.
ISO 9899:1990 does not define the behaviour when an aggregate declaration
uses
a tag in different forms of type specifier. Either all uses of the tag
should
be in structure type specifiers, or all uses should be in union type
specifiers"

BENEFITS
Reuse of tag names can lead to errors and confusion.

EXAMPLE
struct stag { int a; int b; };
void foo1()
{
union stag
}

{ int a; float b; }; // Violation

void foo2(void)
{
struct stag { int a; };
}

// Violation

REPAIR
struct stag { int a; int b; };
void foo1()
{
union union_tag
}
void foo2(void)

{ int a; float b; }; // OK

{
struct new_stag { int a; };

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4

The identifier name of a non-member object or function with static storage duration should
not be reused [MISRA2008-2_10_5_a-4]
DESCRIPTION
Static object or function identifier shall not be reused for any other
purpose within the program.

BENEFITS
Reuse of static identifiers can lead to errors and confusion.

EXAMPLE
static float a;
static void foo()
{
int a;
/* Violation */
int foo; /* Violation */
}

REPAIR
Do not use static identifiers for any other purpose within the program.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4

The identifier name of a non-member object or function with static storage duration should
not be reused [MISRA2008-2_10_5_b-4]
DESCRIPTION
Object or function identifier with static storage duration should be
unique.

BENEFITS
Reuse of identifier names can lead to errors and confusion.

EXAMPLE
static
static
{
static
static
}

float a;
void foo()
int a ; /* Violation */
int foo; /* Violation */

REPAIR
Do not use the same names for different static object or functions.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4

If an identifier refers to a type, it shall not also refer to an object or a function in the same
scope [MISRA2008-2_10_6-3]
DESCRIPTION
"ISO C defines a number of different name spaces. It is technically
possible to use the same name in separate name spaces to represent
completely different items. However this practice is deprecated because
of the confusion it can cause, and so names should not be reused, even
in separate name spaces."
There are four namespaces in the C Language
1. Label names
2. Tags of structure, unions and enumerations
3. Members of structs and unions; each struct/union as a separate
namespace
4. All other identifiers; e.g. enum constants, variables, functions,
typedefs

NOTES
The output message shows only the first place (line) where the same
name is used in the other name space.

EXCEPTIONS
"An exception to this rule is the naming of members of structures,
where members names may be reused within separate structures."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
typedef struct MyStruct // tags name space
{
int Member;
// members name space
} MyStruct;
// Violation - identifiers name space

REPAIR
typedef struct MyStruct
{
int Member;
} MyStructObj;

// tags name space


// members name space
// OK - identifiers name space

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 12
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-6

Only those escape sequences that are defined in ISO/IEC 14882:2003 shall be used
[MISRA2008-2_13_1-3]
DESCRIPTION
"Only those escape sequences that are defined in ISO/IEC 14882:2003
shall be used. The defined escape sequences (ISO/IEC 14882:2003) are:
\n, \t, \v, \b, \r, \f, \a, \\, \?, \', \", \<Octal Number>,
\x<Hexadecimal Number>"

SINCE
v7.2

BENEFITS
The use of an undefined escape sequence leads to undefined behaviour.

EXAMPLE
#include <stdio.h>
void foo( ) {
printf("ABCD\u1111");
printf("abcd\hgf");
printf("\k");
}

// Violation
// Violation
// Violation

REPAIR
Do not use escape sequences not defined in the ISO/IEC 14882:2003
standard.

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-1
2. General Principles of Software Validation;

Final Guidance for Industry and FDA Staff


Document issued on: January 11, 2002

Octal constants (other than zero) and octal escape sequences (other than "\0") shall not be
used [MISRA2008-2_13_2-3]
DESCRIPTION
"Any integer constant beginning with a '0' (zero) is treated as octal.
So there is a danger, for example, with writing fixed length constants.
Octal escape sequences can be problematic because the inadvertent
introduction of a decimal digit ends the octal escape and introduces
another character. It is better not to use octal constants or escape
sequences at all and to statically check for any occurrences.
The integer constant zero (written as a single numeric digit) is, strictly
speaking, an octal constant, but is a permitted exception to this rule.
Additionally \0 is the only permitted octal escape sequence."

EXCEPTIONS
Rule ignores any #pragma parasoft / codewizard directives.
Rule ignores any values inside asm blocks.

BENEFITS
Rule increases readability and maintainability.
Rule prevents using implementation-defined values.

EXAMPLE
void foo()
{
int code1;
int code2;
int code3;
code1 = 052;
/* Violation */
code2 = 071;
/* Violation */
code3 = '\100'; /* Violation */
}

REPAIR

void foo1()
{
int code1;
int code2;
int code3;
code1 = 42;
code2 = 57;
code3 = 64;

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 7
2. Origin: Misra Guidelines - Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 149
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-2

A "U" suffix shall be applied to all octal or hexadecimal integer literals of unsigned type
[MISRA2008-2_13_3-3]
DESCRIPTION
"The type of an integer is dependent on a complex combination of factors
including:
- The magnitude of the constant;
- The implemented sizes of the integer types;
- The presence of any suffixes;
- The number base in which the value is expressed.
For example, the value 0x8000 is of type unsigned int in a 16-bit
environment,
but of type (signed) int in a 32-bit environment. If an overload set
includes
candidates for an unsigned int and an int, then the overload that would be
matched by 0x8000 is therefore dependent on the implemented integer size.
Adding a "U" suffix to the value specifies that it is unsigned."

SINCE
v7.2

BENEFITS
Rule improves portability and prevents undefined behaviour.

EXAMPLE
unsigned long var = 02;

// Violation

REPAIR
unsigned long var = 02U; // OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems

Chapter 6, Section 2, Rule 2-13-3

Literal suffixes shall be upper case [MISRA2008-2_13_4-3]


DESCRIPTION
Literal suffixes shall use uppercase rather than lowercase letters.
See also: CODSTA-50

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo(long param = 64l) // Violation
{
const long a = 64l; // Violation
}

REPAIR
void foo(long param = 64L) // OK
{
const long a = 64L;
// OK
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4

Narrow and wide string literals shall not be concatenated [MISRA2008-2_13_5-3]


DESCRIPTION
Concatenation of wide and narrow string literals leads to undefined
behaviour.

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
wchar_t array[] = "Hello" L"World";

// Violation

REPAIR
wchar_t array[] = L"Hello" L"World";

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-5

Trigraphs shall not be used [MISRA2008-2_3_1-3]


DESCRIPTION
Rule reports a violation message if trigraphs are used.
All occurrences in a source file of the following sequences of three
characters (called trigraph sequences) are replaced with the corresponding
single character.
??= #
??( [
??/ \
??) ]
??' ^
??< {
??! |
??> }
??- ~
If the compiler has a switch to ignore trigraphs then this
option should be used, or alternatively ensure that two
adjacent question marks are never used in the code.

BENEFITS
Trigraphs can cause accidental confusion with other uses of two question
marks and lead to unexpected behaviour.

EXAMPLE
??=define TEST 1
/* Violation
*/
void foo() {
const char* s = "(Date should be in the form ??-??-??)"; /* Violation */
}

REPAIR
#define TEST 1
OK */
void foo() {

/*

const char* s = "(Date should be in the form " "??" "-??" "-??" ")"; /*
OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 4
2. Origin: Misra Guidelines - Rule 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 11
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-3-1

Digraphs should not be used [MISRA2008-2_5_1-4]


DESCRIPTION
The following digraphs will not be used <%, %>, <:, :>, %:, %:%:
The use of digraphs listed in this rule can obscure the meaning
of otherwise simple constructs.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
int a <: 2 :> <: 2 :> = <%<%0,1%>,<%2,3%>%>; // Violation

REPAIR
int a[2][2] = { {0,1}, {2,3} };

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-5-1

The character sequence /* shall not be used within a C-style comment [MISRA2008-2_7_1-3]
DESCRIPTION
C does not support the nesting of comments even though
some compilers support this as a language extension.
A comment begins with /* and continues until the first */ is encountered.
Any /* occurring inside a comment is a violation of this rule.

BENEFITS
Nested comments are not supported by C and can lead to confusion.

EXAMPLE
/* some comment, end comment marker accidentally omitted
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is not compliant - Violation */

REPAIR
/* some comment, end comment marker accidentally omitted */
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is compliant - OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 9
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-1

Sections of code shall not be "commented out" using C-style comments [MISRA2008-2_7_2-3]
DESCRIPTION
"Where it is required for sections of source code not to be compiled then
this should be achieved by use of conditional compilation (e.g. #if or
#ifdef constructs with a comment)."

NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.

BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."

EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}

// Violation

REPAIR
void foo()
{
int x = 5;
/* Comment without

// OK

code within */
#if 0
if (x==0){
x++;
}
#endif
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3

Sections of code should not be "commented out" using C++ comments [MISRA2008-2_7_3-4]
DESCRIPTION
"Where it is required for sections of source code not to be compiled then
this should be achieved by use of conditional compilation (e.g. #if or
#ifdef constructs with a comment)."

NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.

BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."

EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}

// Violation

REPAIR
void foo()
{
int x = 5;
/* Comment without

// OK

code within */
#if 0
if (x==0){
x++;
}
#endif
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3

It shall be possible to include any header file in multiple translation units without violating the
One Definition Rule [MISRA2008-3_1_1-3]
DESCRIPTION
"Header files should be used to declare objects, functions, inline
functions,
function templates, typedefs, macros, classes, and class templates and
shall
not contain or produce definitions of objects or functions (or fragment of
functions or objects) that occupy storage."
See also: MISRA2004-8_5

NOTES
As a headers rule detects files with extensions ".h", ".hh", ".hxx", ".i"
(e.g. "file.h", "file.hh", "file.hxx", "file.i").

EXCEPTIONS
The following definitions are allowed in a header file:
- inline functions
- function templates
- static data members of class templates
- const variables if they have internal or no linkage (C++ mode)
- static const variables

BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.

EXAMPLE
/* file.h */
void f1(){}
int var;
class C {
void f2();

// Violation
// Violation

};
void C::f2() {}

// Violation

/* file.cpp */
#include "file.h"

REPAIR
/* file.h */
void f1();
extern int var;
class C {
void f2();
};
template <typename T>
void f3 ( T ) { }

// OK
// OK

// OK

/* file.cpp */
#include "file.h"
void f1(){}
int var;
void C::f2() {}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-1
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 61
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 39

Functions shall not be declared at block scope [MISRA2008-3_1_2-3]


DESCRIPTION
Functions shall always be declared at file scope.
Declaring functions at block scope may be confusing,
and can lead to undefined behaviour.

BENEFITS
Rule prevents undefined behaviour and improves readability.

EXAMPLE
void foo1( ) {
void foo2( );
}

/* Violation */

REPAIR
void foo2( );
void foo1( ) {
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 68
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 107
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-2

When an array is declared, its size shall either be stated explicitly or defined implicitly by
initialization [MISRA2008-3_1_3-3]
DESCRIPTION
"When an array is declared with external linkage, its size shall be stated
explicitly or defined implicitly by initialisation.
Although it is possible to declare an array of incomplete type and access
its elements, it is safer to do so when the size of the array may be
explicitly determined."

BENEFITS
Rule prevents undefined behaviour and improves safety of code.

EXAMPLE
extern int array2[ ]; /* Violation */
extern int array1[ ]; /* Violation */

REPAIR
int array2[ ] = { 0, 10, 15 };
extern int array1[ 10 ];

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-3

Objects or functions with external linkage shall be declared in a header file [MISRA20083_3_1-3]
DESCRIPTION
"Placing the declarations of objects and functions with external linkage
in a header file documents that they are intended to be accessible from
other
translation units. If external linkage is not required, then the object or
function shall either be declared in an unnamed namespace or declared
static."

SINCE
v7.2

EXCEPTIONS
This rule does not apply to main, or to members of unnamed namespaces.

BENEFITS
Rule reduce the visibility of objects and functions.

EXAMPLE
// file.cpp
int a1 = 0;
void fun(){}

// Violation
// Violation

REPAIR
// file.h
extern int a1;
extern void fun();
// file.cpp
#include "file.h"
int a1 = 0;
// OK

// OK
// OK

void fun(){}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-3-1

If a function has internal linkage then all re-declarations shall include the static storage class
specifier [MISRA2008-3_3_2-3]
DESCRIPTION
"If the declaration of a function includes the static storage class
specifier,
then it has internal linkage. A re-declaration of such a function is not
required to have the static keyword, but it will still have internal
linkage.
However, this is implicit and may not be obvious to a developer. It is
therefore
good practice to apply the static keyword consistently so that the linkage
is explicitly stated."
See also: MISRA2004-8_11

SINCE
v7.2

BENEFITS
Rule improves good programming style and readability.

EXAMPLE
static void f1 ( );
void f1 ( ) { }

// Violation

REPAIR
static void f1 ( );
static void f1 ( ) { }

// OK

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-3-2

An identifier declared to be an object or type shall be defined in a block that minimizes its
visibility [MISRA2008-3_4_1-3]
DESCRIPTION
"A variable ought to be declared with the smallest possible scope to
improve
the readability of the code and so that variables are not unnecessarily
allocated. When a variable that is declared at the beginning of a function
is
used somewhere in the code, it is not easy to directly see the type of
the variable.
In addition, there is a risk that such a variable is inadvertently hidden
if a local variable, having the same name, is declared in an internal
block.
Many local variables are only used in special cases which seldom occur.
If a variable is declared at the outer level,
memory will be allocated even if it is not used. In addition, when
variables
are initialized upon declaration, more efficient code is obtained than if
values are assigned when the variable is used."

BENEFITS
Rule prevents from making the program harder to understand and maintain.

EXAMPLE
void foo( ) {
int a;
{
a = 0;
}
}

// Violation

REPAIR
void foo( ) {
{
int a;

// OK

a = 0;
}
}
void fooOK1(){
int b;
if (b > 0) {
b = 10;
}
}

// OK - variable is used in condition

void fooOK1(int j){


int b;
// OK - variable is used inside two different blocks
if (j > 0) {
b = 10;
} else {
b = 20;
}
}
void fooOK2(int p){
int c;
// OK - variable is used in the same block
c = 10;
if (p > 0) {
c++;
}
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 18
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-4-1
4. The Power of Ten - Rules for Developing Safety Critical Code.

Rule 6
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The types used for an object, a function return type, or a function parameter shall be tokenfor-token identical in all declarations and re-declarations [MISRA2008-3_9_1-3]
DESCRIPTION
"If a re-declaration has compatible types but not types which are
token-for-token identical, it may not be clear to which declaration
that re-declaration refers."

SINCE
v7.2

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
typedef int INT;
INT i;
extern int i;

// Violation

void foo(const int i);


void foo(int i){}
// Violation

REPAIR
typedef int INT;
INT i;
extern INT i;

// OK

void foo(const int i);


void foo(const int i){} // OK

REFERENCES

MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-9-1

typedefs that indicate size and signedness should be used in place of the basic numerical
types [MISRA2008-3_9_2-4]
DESCRIPTION
"The storage length of types can vary from compiler to compiler. It is
safer
if programmers work with types which they know to be of a given length."
Rule reports a violation message if basic numerical type is used
(e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA2004-6_3

EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)

BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."

EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
char* p_char,
float& r_float)
{
double h;
const int z = 1;
return 1;

/* Violation (for return type) */


/* Violation */
/* Violation */
/* Violation */
/* Violation */

REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}

/* OK (plain char) */
/* OK (typedef name starts with 'bool'

/* OK (bit-bield type) */
/*
/*
/*
/*

OK
OK
OK
OK

(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */

/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */

REFERENCES
1. Misra Guidelines - Rule 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-9-2

The underlying bit representations of floating-point values shall not be used [MISRA20083_9_3-3]
DESCRIPTION
"The storage layout used for floating-point values may vary from one
compiler to
another, and therefore no floating-point manipulations shall be made which
rely
directly on the way the values are stored. The in-built operators and
functions,
which hide the storage details from the programmer, should be used."

NOTES
In many cases floating point bit fields will be flagged as syntax errors.

BENEFITS
Prevents implementation-defined behaviour.

EXAMPLE
struct S {
float f:6; // Violation
};
union U {
float f:6; // Violation
};

REPAIR
struct S {
int f:6; // OK
};
union U {
int f:6; // OK
};

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 3-9-3

NULL shall not be used as an integer value [MISRA2008-4_10_1-3]


DESCRIPTION
"In C++, the literal 0 is both an integer type and the null-pointerconstant.
To meet developer expectations, NULL should be used as the
null-pointer-constant, and 0 for the integer zero."

SINCE
v7.2

BENEFITS
"As a result of this rule, NULL is considered to have pointer type."

EXAMPLE
#include <cstddef>
void f1( int );
void foo( )
{
f1( NULL ); // Violation
}

REPAIR
void f1( int );
void foo( )
{
f1( 0 ); // OK
}

REFERENCES

1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Literal zero (0) shall not be used as the null-pointer-constant [MISRA2008-4_10_2-3]


DESCRIPTION
"In C++, the literal 0 is both an integer type and the null-pointerconstant.
To meet developer expectations, NULL should be used as the
null-pointer-constant, and 0 for the integer zero."

SINCE
v7.2

BENEFITS
"As a result of this rule, NULL is considered to have pointer type."

EXAMPLE
#include <cstddef>
void f1( int* );
void foo( )
{
f1( 0 ); // Violation
}

REPAIR
#include <cstddef>
void f1( int* );
void foo( )
{
f1( NULL ); // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-2

Expressions with type bool shall not be used as operands to built-in operators other than the
assignment operator =, the logical operators &&, ||, !, the equality operators == and !=, the
unary & operator, and the conditional operator [MISRA2008-4_5_1-3]
DESCRIPTION
"Expressions that are effectively Boolean should not be used as operands
to operators other than (&&, ||, !, =, ==, !=, ?:).
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule reports violation if as an operand of operator
other than (&&, ||, !, =, ==, !=, ?:) is used:
- Boolean-by-construct values
- boolean constant
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types

BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.

EXAMPLE
int goo();

void foo()
{
int x, y, z;
z = (x > y) & (goo()); // Violation
z = x | (goo() != 0); // Violation
z = ~(x == y);
// Violation
}

REPAIR
int goo();
void foo()
{
int x, y, z;
int tmp;
tmp = x > y;
z = tmp & goo();

// OK

tmp = goo() != 0;
z = x | tmp;

// OK

tmp = x == y;
z = ~tmp;

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 36
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 4, Rule 4-5-1

Expressions with type enum shall not be used as operands to built-in operators other than [ ],
=, ==, !=, <, <=, >, >=, and the unary & operator [MISRA2008-4_5_2-3]
DESCRIPTION
"Expressions with type enum shall not be used as operands to built-in
operators other than the subscript operator [ ], the assignment operator
=,
the equality operators == and !=, the unary & operator, and the relational
operators <, <=, >, >=."

SINCE
v7.2

BENEFITS
"Enumerations have implementation-defined representation
and so should not be used in arithmetic contexts."

EXAMPLE
/* Examples of incorrect code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 + COLOUR_1 ) == colour ){} // Violation
}

REPAIR
/* Examples of correct code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 < colour) && (COLOUR_3 > colour ) ){} // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-2

Expressions with type (plain) char and wchar_t shall not be used as operands to built-in
operators other than the assignment operator =, the equality operators == and !=, and the
unary & operator [MISRA2008-4_5_3-3]
DESCRIPTION
"Expressions with type (plain) char and wchar_t shall not be used as
operands
to built-in operators other than the assignment operator =, the equality
operators == and !=, and the unary & operator."

SINCE
v7.2

EXCEPTIONS
Exceptionally, the following operators may be used if the associated
restriction is observed:
- The binary + operator may be used to add an integral
value in the range 0 to 9 to 0;
- The binary operator may be used to subtract character 0;
- The relational operators <, <=, >, >= may be used to determine
if a character (or wide character) represents a digit.
(Rule does not report a violation if a character constant is compared
with a variable of type plain char)

BENEFITS
"Manipulation of character data may generate results that are contrary
to developer expectations."

EXAMPLE
void foo()
{
char ch = 't';
// OK
if ( ( ch >= 'a' ) && ( ch <= 'z' ) ) // Violation
{
//...

}
}

REPAIR
void foo()
{
char ch = 't';
// OK
if ( ch == 't' ) // OK
{
//...
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-3

If the bitwise operators ~ and << are applied to an operand with an underlying type of
unsigned char or unsigned short, the result shall be immediately cast to the underlying type of
the operand [MISRA2008-5_0_10-3]
DESCRIPTION
"When these operators (~ and <<) are applied to small integer types
(unsigned char or unsigned short),
the operations are preceded by integral promotion,
and the result may contain high order bits which have not been
anticipated.
A similar problem exists when the << operator is used on small integer
types
and high order bits are retained."

BENEFITS
Rule prevents high order bits retaining.

EXAMPLE
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = (~port) >> 4;
*/
result_16 = ((port << 4) & mode) >> 6;
*/
}

REPAIR
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;

/* Violation
/* Violation

void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = ((uint8_t)(~port)) >> 4 ;
result_16 = (
(uint16_t) (~(uint16_t)port)
) >> 4 ;
result_16 = ((uint16_t)((uint16_t)port << 4) & mode) >> 6;
}

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-10

The plain char type shall only be used for the storage and use of character values
[MISRA2008-5_0_11-3]
DESCRIPTION
"The plain char type shall be used only for the storage and use of
character values.
The only permissible operators on plain char types are assignment
and equality operators (=, ==, != )"

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
char a = 65;
/* Violation */
void foo( ) {
a = 66;
/* Violation */
a++;
/* Violation */
if (a < 67) /* Violation */
{
}
}

REPAIR
char a = 'A';
/* OK */
void foo( ) {
a = 'B';
/* OK */
if (a == 'C') /* OK */
{
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6

2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-11

signed char and unsigned char type shall only be used for the storage and use of numeric
values [MISRA2008-5_0_12-3]
DESCRIPTION
signed and unsigned char type shall be used only for the storage
and use of numeric values. The signedness of the plain char type is
implementation-defined and should not be relied upon.

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
signed char a = 'A';
void foo( ) {
unsigned char a = 'B';
if (a == 'C')
{
}
if (a < 'D')
{
}

/* Violation */
/* Violation */
/* Violation */

/* Violation */

REPAIR
signed char a = 65;
void foo( ) {
unsigned char a = 66;
if (a == 67)
{
}
if (a < 68)
{
}
}

/* OK */
/* OK */
/* OK */

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-12

The condition of an if-statement and the condition of an iteration-statement shall have type
bool [MISRA2008-5_0_13-3]
DESCRIPTION
"If an expression with type other than bool is used in the condition
of an if-statement or iteration statement, then its result will be
implicitly converted to bool."

SINCE
v7.2

NOTES
Rule does not report violations if the condition expression is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.

EXCEPTIONS
"A condition of the form type-specifier-seq declarator is not required
to have type bool."

BENEFITS
"The condition expression shall contain an explicit test (yielding a
result
of type bool) in order to clarify the intentions of the developer."

EXAMPLE
void foo()
{
int i;
if (i){} // Violation
}

REPAIR
void foo()
{
int i;
if (i != 0){} // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-13

The first operand of a conditional-operator shall have type bool [MISRA2008-5_0_14-3]


DESCRIPTION
"The first operand of a conditional-operator shall have type bool.
If an expression with type other than bool is used as the first operand
of a conditional-operator, then its result will be implicitly converted
to bool."

SINCE
v7.2

BENEFITS
"The first operand shall contain an explicit test (yielding a result of
type
bool) in order to clarify the intentions of the developer."

EXAMPLE
void foo(int i, int j, int k, int l)
{
i = j ? k : l;
// Violation
}

REPAIR
void foo(int i, int j, int k, int l)
{
i = (j != 0) ? k : l;
// OK
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-14

2. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Array indexing shall be the only form of pointer arithmetic [MISRA2008-5_0_15-3]


DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
BENEFITS
Rule improves safety of the code.

DRAWBACKS
For more complex code rule may not be able to check if there is indexed
pointer
which points to array. For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10];
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5

=
=
=
=
=

a;
p1;
p2;
p3;
p4;

p1[0]
p2[0]
p3[0]
p4[0]
p5[0]

=
=
=
=
=

0;
0;
0;
0;
0;

//
//
//
//
//

OK
OK
OK
Violation - false positive
Violation - false positive

EXAMPLE
void my_fn(int * p1, int p2[]) {
int index = 0;

int * p3;
int * p4;
*p1 = 0;
p1 ++;
/* Violation
p1 = p1 + 5; /* Violation
p1[5] = 0;
/* Violation
p3 = &p1[5]; /* Violation
p2[0] = 0;
index ++;
index = index + 5;
p2[index] = 0; /* OK */
p4 = &p2[5];
/* OK */

pointer increment */
pointer increment */
p1 was not declared as an array */
p1 was not declared as an array */

}
void foo() {
int a1[16];
int a2[16];
int a[10];
int * p;
my_fn(a1, a2);
my_fn(&a1[4], &a2[4]);
p = a;
*(p+5) = 0; /* Violation */
p[5] = 0;
/* OK */
}

REPAIR
Do not increment/decrement pointers that does not point to an array
Do not apply array indexing to pointers that does not point to array
elements.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-15

Subtraction between pointers shall only be applied to pointers that address elements of the
same array [MISRA2008-5_0_17-3]
DESCRIPTION
"Subtraction of pointers only gives well-defined results if the two
pointers
point (or at least behave as if they point) into the same array object."
Drawbacks: For more complex code rule may not be able to check if there is
applied pointer arithmetic to pointers that address an array or array
element.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5

=
=
=
=
=

a; i
p1;i
p2;i
p3;i
p4;i

=
=
=
=
=

p1
p2
p3
p4
p5

a;
a;
a;
a;
a;

//
//
//
//
//

OK
OK
OK
Violation - false positive
Violation - false positive

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 - p2;
i = p2 - a;
i = p3 - a;
}

// Violation
// Violation
// OK

REPAIR
Do not apply pointer subtraction to pointers that address elements
of different arrays.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-17

>, >=, <, <= shall not be applied to objects of pointer type, except where they point to the same
array [MISRA2008-5_0_18-3]
DESCRIPTION
"Attempting to make comparisons between pointers will produce undefined
behaviour."

NOTES
"It is permissible to address the next element beyond the end of an array,
but accessing this element is not allowed."

EXCEPTIONS
"Both operands are of the same type and point to the same array"

BENEFITS
Rule makes the code more readable and less confusing.

DRAWBACKS
For more complex code rule may not be able to check if there is
applied pointer comparison to pointers which point the same array.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
}

=
=
=
=
=

a; i
p1;i
p2;i
p3;i
p4;i

=
=
=
=
=

p1
p2
p3
p4
p5

<
<
<
<
<

a;
a;
a;
a;
a;

//
//
//
//
//

OK
OK
OK
Violation - false positive
Violation - false positive

EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 < p2;
i = p2 < a;
i = p3 < a;

// Violation
// Violation
// OK

REPAIR
Do not apply pointer comparison to pointers that address elements
of different arrays

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 103
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 171
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-18

The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_a-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int * INTPTR;
struct s {
int *** s3;
};
struct s *** ps3;
int ** (***pfunc3)();
int *** ( **pfunc4)();
void function( int * par1,
int *** par3,
INTPTR * const * const par5
)
{

/* Violation */

/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */

int *** ptr3;


/* Violation */
INTPTR * const * const ptr5 = 0; /* Violation */
}

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4

The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_b-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int* apInt[] ;
apInt* rule12;
/* Violation */

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4

The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_c-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
int*** (*rule13)();

/* Violation */

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17

2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4

The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_d-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."

NOTES
Array type with unspecified length is treat as a pointer.

BENEFITS
Rule improves safety of the code.

EXAMPLE
typedef int* INTPTR;
void function(int ** par7[])
{
}
int*** (*xx5[])() = {0};
typedef int INTARR[];
INTARR* (**xx9[])() = {0};
int** rule21[] = {0};

/* Violation */

/* Violation */
/* Violation */
/* Violation */

REPAIR
Do not declare more than two levels of pointer indirection.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_a-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
As an example of what can go wrong, consider x = b[i] + i++; This will
give
different results depending on whether b[i] is evaluated before i++ or
vice
versa. The problem could be avoided by putting the increment operation
in a separate statement."
The rule reports a violation if a variable is used and
incremented/decremented
in the same statement.
See also: MISRA2004-12_4_a, MISRA2004-12_4_b

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo( )
{
int a, b[10];
a = b[a] + a++; // Violation
}

REPAIR
void foo( )
{
int a, b[10];

a = b[a] + a;
a++;

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_b-3]
DESCRIPTION
The order of evaluation of function arguments is unspecified. This means
that
if arguments contain side effects then the order in which side effects
take
place is unspecified. A function call can give different results depending
on which of the function's arguments is evaluated first.
By side effect we understand accessing a volatile object, modifying an
object
or calling a function that does any of those operations.
Rule checks calls of functions that have at least two arguments.
A violation is reported if
* a volatile object is read or modified, or
* a non-volatile object is modified
during evaluation of a function argument and the same object is read or
modified during evaluation of function's other argument.

EXCEPTIONS
Only one level of function calls is checked.

BENEFITS
Rule prevents writing source code which might produce different results
between compilers.

EXAMPLE
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
Transmogrify(Bump(count),Bump(count)); // Violation
Transmogrify(count++,count);
// Violation

REPAIR
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
int temp1 = Bump(count);
Transmogrify(temp1,Bump(count)); // OK
Transmogrify(count,count);
// OK
count++;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 31
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
5. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_c-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur. Those points in the evaluation of
an
expression at which all previous side effects can be guaranteed to have
taken
place are called sequence points. Sequence points and side effects are
described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].
Note that the order of evaluation problem is not solved by the use of
parentheses, as this is not a precedence issue."
"If a function is called via a function pointer there shall be no
dependence on
the order in which function designator and function arguments are
evaluated.
p->task_start_fn(p++);"

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p++ );
}

// Violation

REPAIR
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p );
p++;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_d-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
Rule reports a violation if in an expression a function is called that
takes as
an argument a pointer or a reference to a non-const variable and modifies
this
variable, and in the same expression the variable is used in some other
way.

NOTES
Rule assumes that a variable is modified in function if it is directly
modified
by assignment or body of function is not defined in current translation
unit.

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
int foo(int* ptr)
{

(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
i = foo(&j) + bar(j);
}

// Violation

REPAIR
int foo(int* ptr)
{
(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
int temp = foo(&j);
i = temp + bar(j);
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_e-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Assignments nested within expressions cause additional side effects. The
best
way to avoid any chance of this leading to a dependence on order of
evaluation
is to not embed assignments within expressions."

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo( int x, int y, int z ) {
x = y = z / 3; // Violation
}

REPAIR
void foo( int x, int y, int z ) {
y = z / 3; // OK
x = y;
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_f-3]
DESCRIPTION
"The volatile type qualifier is provided in C to denote objects whose
value can
change independently of the execution of the program (for example an input
register). If an object of volatile qualified type is accessed this may
change
its value. C compilers will not optimise out reads of a volatile. In
addition,
as far as a C program is concerned, a read of a volatile has a side effect
(changing the value of the volatile). It will usually be necessary to
access
volatile data as part of an expression, which then means there may be
dependence
on order of evaluation. Where possible though it is recommended that
volatiles
only be accessed in simple assignment statements."
The rule reports a violation if in one expression is used more than one
volatile.
See also: MISRA2004-12_2_b

SINCE
v7.0

NOTES
Rule does not report violation if in a function call are used as arguments
more than one volatile. In this case should be used rule MISRA2004-12_2_b.
void goo(int, int);
void foo()
{
volatile int v;
goo(v, v); // Violation - MISRA2004-12_2_b
}

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
void foo( )
{
volatile int x;
int y;
y = x * x; // Violation
}

REPAIR
void foo( )
{
volatile int x;
int y;
y = x;
// OK
y = y * y;
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_g-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
The rule reports a violation if in one expression are called two functions
that
use the same global or static variable and at least one function modifies
this
variable.

EXCEPTIONS
Only one level of function calls is checked.

BENEFITS
Rule prevents evaluation of expression dependent on compiler version.

EXAMPLE
int global;
int modify_global()
{
global++;

return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global() + use_global();
}

// Violation

REPAIR
int global;
int modify_global()
{
global++;
return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global();
a += use_global();
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1

Non-constant operands to a binary bitwise operator shall have the same underlying type
[MISRA2008-5_0_20-3]
DESCRIPTION
"Non-constant operands to a binary bitwise operator shall have the same
underlying type. The term 'underlying type' is defined as describing
the type that would be obtained from evaluating an expression if it were
not for the effects of integral promotion."

SINCE
v7.2

BENEFITS
"Using operands of the same underlying type documents that it is the
number
of bits in the final (promoted and balanced) type that are used, and not
the number of bits in the original types of the expression."

EXAMPLE
void foo()
{
unsigned char mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// Violation
}

REPAIR
void foo()
{
unsigned short mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-20

Bitwise operators shall only be applied to operands of unsigned underlying type [MISRA20085_0_21-3]
DESCRIPTION
"Bitwise operations (~, <<, <<=, >>, >>=, &, &=, ^, ^=, | and |=) are not
normally meaningful on signed integers or enumeration constants.
Additionally, an implementation-defined result is obtained if a right
shift
is applied to a negative value."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & s1;

// Violation

REPAIR
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & (unsigned short)s1;
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-21

Limited dependence should be placed on C++ operator precedence rules in expressions


[MISRA2008-5_0_2_a-4]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
Parentheses are required for the right-hand operand because the right-hand
side itself contains an assignment expression.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int a, b;
b = a = 0;// Violation
}

REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C++ operator precedence rules in expressions


[MISRA2008-5_0_2_b-4]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it.
It is easy to make a mistake with the rather complicated precedence rules
of C,
and this approach helps to avoid such errors, and helps to make the code
easier
to read. However, do not add too many parentheses so as to clutter the
code and
make it unreadable."
"No parentheses are required for the right-hand operand of an assignment
operator unless the right-hand side itself contains an assignment
expression."

NOTES
Macro's body is excluded from checking.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int a, b;
b = (a = 0);// OK
b = (a + 0);// Violation
}

REPAIR
void foo() {
int a, b;

b = (a = 0);// OK
b = a + 0;// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C++ operator precedence rules in expressions


[MISRA2008-5_0_2_c-4]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
The rule detects parentheses which are not required for the operand
of a unary operator.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( )
{
int a, b;
b = a * (-1);
}

// Violation

REPAIR
void foo( )
{
int a, b;
b = a * -1;
}

REFERENCES

// OK

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C++ operator precedence rules in expressions


[MISRA2008-5_0_2_d-4]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
"If all operators are the same, parentheses may be used to control the
order of
operation. Some operators (e.g. addition and multiplication) that are
associative in algebra are not necessarily associative in C. Similarly,
integer
operations involving mixed types (prohibited by several rules) may produce
different results because of the integral promotions. The following
example
written for a 16-bit implementation demonstrates that addition is not
associative and that it is important to be clear about the structure of an
expression:"

SINCE
v7.0

BENEFITS
Rule increases safety in arithmetic operations.

EXAMPLE
#ifdef _MSC_VER
typedef unsigned __int16 uint16;

typedef unsigned __int32 uint32;


#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus( ) {
uint16 a = 10;
uint16 b = 65535;
uint32 c = 0;
uint32 d;
d = (a + b) + c; /* Violation d is 9; a + b wraps modulo 65536 */
}
void fooMultiply( ) {
uint16 a = 10;
uint16 b = 65535;
uint32 c = 0;
uint32 d;
d = (a * b) * c; /* Violation d is 65526; a * b wraps modulo 65536 */
}

REPAIR
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus(
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a + (b
}

) {
10;
65535;
0;
+ c); /* OK d is 65545 */

void fooMultiply( ) {

uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a * (b

10;
65535;
0;
* c); /* OK d is 655350 */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C++ operator precedence rules in expressions


[MISRA2008-5_0_2_e-4]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it unreadable.
Use parentheses unless all operators in the expression are the same."
See also: MISRA2004-12_5, CODSTA-90

NOTES
The operands of a logical && and || are checked by the rule MISRA2004-12_5

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( ) {
int a, b;
b = a * a + a;
}

// Violation

REPAIR
void foo( ) {
int a, b;
b = (a * a) + a;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

Limited dependence should be placed on C++ operator precedence rules in expressions


[MISRA2008-5_0_2_f-4]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
If parentheses are nested too deeply then you may hit a translation limit
but
if this happens the expression is probably too complicated anyway and
should be
split. The rule checks the number of nested parentheses - if the nesting
level
exceeds 10 rule reports a violation message.

Note:
Nested parentheses level is set on 10 but can be changed. To change the
default level of the nested parentheses modify the main "Count" expression
of the rule (Collector A) from "$$ > 9" to "$$ > N" using desired
threshold
value for N. Rule's header should be also changed accordingly.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( )
{
int a, b,c,d;
a=(((((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8)/(b+d))+3; // Violation

REPAIR
void foo( )
{
int a, b,c,d;
int h;
h = (((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8;
a =(h*(b+d))+3;
}

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47

A cvalue expression shall not be implicitly converted to a different underlying type


[MISRA2008-5_0_3_a-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
"The intention when restricting implicit conversion of complex expressions
is to require that in a sequence of arithmetic operations within an
expression,
all operations should be conducted in exactly the same arithmetic type.
Notice that this does not imply that all operands in an expression are
of the same type.
The expression u32a + u16b + u16c is compliant - both additions will
notionally
be performed in type U32.
The expression u16a + u16b + u32c is not compliant - the first addition
is notionally performed in type U16 and the second in type U32.
The word 'notionally' is used because, in practice, the type in which
arithmetic will be conducted will depend on the implemented size of an
int."
Rule checks if implicit conversions of complex expressions are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned short u16a,u16b;

unsigned int u32a, u32b;


u32a = u16b + u16a + u32b;
u32a = u32b + (u16a + u16b);

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
u32a = u32b + u16b + u16a;
u32a = u16b + (u16a + u32b);

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4

A cvalue expression shall not be implicitly converted to a different underlying type


[MISRA2008-5_0_3_b-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
"The intention when restricting implicit conversion of complex expressions
is
to require that in a sequence of arithmetic operations within an
expression,
all operations should be conducted in exactly the same arithmetic type."
Rule checks if implicit conversions of complex expressions are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.

EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;

u32a = u16b + u16a;

/* Violation */

REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;
u32a = (unsigned int)(u16b + u16a);

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4

A cvalue expression shall not be implicitly converted to a different underlying type


[MISRA2008-5_0_3_c-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
"The intention when restricting implicit conversion of complex expressions
is
to require that in a sequence of arithmetic operations within an
expression,
all operations should be conducted in exactly the same arithmetic type."
Rule checks if implicit conversions of complex expressions are used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.

EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = u16b + u16a;

/* Violation */

REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = (unsigned int)(u16b + u16a);
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4

An implicit integral conversion shall not change the signedness of the underlying type
[MISRA2008-5_0_4_a-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = u32a;
s32b = s32a + u32a;
}

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;

s32a = (signed int)u32a;


/* OK */
s32b = s32a + (signed int)u32b; /* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4

An implicit integral conversion shall not change the signedness of the underlying type
[MISRA2008-5_0_4_b-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used
when variables are initialized.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = u32a;
}

/* Violation */

REPAIR
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = (signed int)u32a;
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4

There shall be no implicit floating-integral conversions [MISRA2008-5_0_5_a-3]


DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a

=
=
=
=

f32a;
f32a;
f64a;
f32b + f32a + f64b;

REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;

//
//
//
//

Violation
Violation
Violation
Violation

u32b
s32b
f32a
f64a

=
=
=
=

(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

There shall be no implicit floating-integral conversions [MISRA2008-5_0_5_b-3]


DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}

REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;

// Violation
// Violation
// Violation

float32_t f32bt = (float)f64a;


// OK
unsigned int u32a = (unsigned int)f32a;
// OK
unsigned short u16a = (unsigned short)1.0; // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

There shall be no implicit floating-integral conversions [MISRA2008-5_0_5_c-3]


DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between integer and floating types are
used.

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
float f32a;
unsigned int u32a;
f32a = u32a;
f32a = f32a + u32a;
f32a = u32a + 2.5f;
}

REPAIR
void Conv1_int( ) {
float f32a;
unsigned int u32a;

/* Violation */
/* Violation */
/* Violation */

f32a = (float)u32a;
f32a = f32a + (float)u32a;
f32a = (float)u32a + 2.5f;

/* OK */
/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
3. ISO/DIS 26262
point 8.4.4

An implicit integral or floating-point conversion shall not reduce the size of the underlying
type [MISRA2008-5_0_6_a-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted
to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always
conducted on integer operands of type int or long (signed or unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation.
The underlying type of an integer constant expression will be determined
according to its magnitude and signedness"
The rule reports a violation if parameter/variable/expression of integral
type is implicitly converted to a narrower integral type.

SINCE
v7.0

NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
The underlying type of an integer constant is determined according
to its magnitude and signedness.

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = u32a;
u8a = u32a;

/* Violation */
/* Violation */

REPAIR
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = (unsigned short)u32a;
u8a = (unsigned char)u32a;

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6

An implicit integral or floating-point conversion shall not reduce the size of the underlying
type [MISRA2008-5_0_6_b-3]
DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a

=
=
=
=

f32a;
f32a;
f64a;
f32b + f32a + f64b;

REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;

//
//
//
//

Violation
Violation
Violation
Violation

signed int s32a,s32b;


u32b
s32b
f32a
f64a

=
=
=
=

(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

An implicit integral or floating-point conversion shall not reduce the size of the underlying
type [MISRA2008-5_0_6_c-3]
DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."

SINCE
v7.0

BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."

EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}

REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;

// Violation
// Violation
// Violation

float32_t f32bt = (float)f64a;


// OK
unsigned int u32a = (unsigned int)f32a;
// OK
unsigned short u16a = (unsigned short)1.0; // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4

There shall be no explicit floating-integral conversions of a cvalue expression [MISRA20085_0_7_a-3]


DESCRIPTION
Rule reports violation if the value of a complex expression of integer
type
is cast to a type that has different signedness or is wider than
the underlying type of the expression.
"The term 'complex expression' is defined to mean any expression that is
not:
- a constant expression
- an lvalue (i.e. an object)
- the return value of a function
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."

BENEFITS
The rule prevents behaviours inconsistent with developer expectations.

EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}

Violation - cast from signed to


Violation - cast from unsigned to
Violation - cast from narrower to
Violation - cast from integer to

REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =

= (unsigned int)si1 + (unsigned int)si2;


= (signed int)ui1 / (signed int)ui2;
= (unsigned int)us1 - (unsigned int)us2;
(double)ui1 * (double)ui2;

/*
/*
/*
/*

OK
OK
OK
OK

*/
*/
*/
*/

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9

There shall be no explicit floating-integral conversions of a cvalue expression [MISRA20085_0_7_b-3]


DESCRIPTION
"If a cast is to be used on any complex expression,
the type of cast that may be applied is severely restricted.
Conversions on complex expressions are often a source of
confusion and it is therefore wise to be cautious."

BENEFITS
Prevents loss of data.

EXAMPLE
typedef float
typedef double
typedef long double

float32_t;
float64_t;
float128_t;

void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float64_t)(f32a + f32b);

/* Violation */

REPAIR
typedef float
typedef double
typedef long double

float32_t;
float64_t;
float128_t;

void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float32_t)(f64a + f64b);
}

/* OK - cast to narrow float type */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7

An explicit integral or floating-point conversion shall not increase the size of the underlying
type of a cvalue expression [MISRA2008-5_0_8-3]
DESCRIPTION
Rule reports violation if the value of a complex expression of integer
type
is cast to a type that has different signedness or is wider than
the underlying type of the expression.
"The term 'complex expression' is defined to mean any expression that is
not:
- a constant expression
- an lvalue (i.e. an object)
- the return value of a function
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."

BENEFITS
The rule prevents behaviours inconsistent with developer expectations.

EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}

Violation - cast from signed to


Violation - cast from unsigned to
Violation - cast from narrower to
Violation - cast from integer to

REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =

= (unsigned int)si1 + (unsigned int)si2;


= (signed int)ui1 / (signed int)ui2;
= (unsigned int)us1 - (unsigned int)us2;
(double)ui1 * (double)ui2;

/*
/*
/*
/*

OK
OK
OK
OK

*/
*/
*/
*/

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9

An explicit integral conversion shall not change the signedness of the underlying type of a
cvalue expression [MISRA2008-5_0_9-3]
DESCRIPTION
Rule reports violation if the value of a complex expression of integer
type
is cast to a type that has different signedness or is wider than
the underlying type of the expression.
"The term 'complex expression' is defined to mean any expression that is
not:
- a constant expression
- an lvalue (i.e. an object)
- the return value of a function
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."

BENEFITS
The rule prevents behaviours inconsistent with developer expectations.

EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}

Violation - cast from signed to


Violation - cast from unsigned to
Violation - cast from narrower to
Violation - cast from integer to

REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =

= (unsigned int)si1 + (unsigned int)si2;


= (signed int)ui1 / (signed int)ui2;
= (unsigned int)us1 - (unsigned int)us2;
(double)ui1 * (double)ui2;

/*
/*
/*
/*

OK
OK
OK
OK

*/
*/
*/
*/

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9

The right hand operand of a logical && or || operator shall not contain side effects
[MISRA2008-5_14_1-3]
DESCRIPTION
"There are some situations in C or C++ where certain parts of expressions
may
not be evaluated. If these sub-expressions contain side effects then those
side
effects may or may not occur, depending on the values of other sub
expressions.
The operators which can lead to this problem are && and || where the
evaluation
of the right-hand operand is conditional on the value of the left-hand
operand.
The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
See also: MISRA2004-12_2_a, MISRA2004-12_4_b

NOTES
Rule checks only three nested level of function calls.

BENEFITS
Rule prevents conditional evaluation of the right-hand operand that can
easily
cause problems if the developer relies on a side effect occurring.

EXAMPLE
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i++)) ; // Violation
}

REPAIR
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i)) i++; // OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 33
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 157
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-14-1
5. ISO/DIS 26262
point 8.4.4

The comma operator shall not be used [MISRA2008-5_18_1-3]


DESCRIPTION
"Use of the comma operator is generally detrimental to the readability of
code,
and the same effect can be achieved by other means."
See also: misra-042

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo() {
int x, y;
x = 0, y = 0;
}

// Violation

REPAIR
void foo() {
int x, y;
x = 0;
y = 0;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-18-1

Each operand of a logical && or || shall be a postfix-expression [MISRA2008-5_2_1-3]


DESCRIPTION
The rule reports a violation if an operand other than a single identifier,
constant or function call is not parenthesised.
"Parentheses are important in this situation both for readability
of code and for ensuring that the behaviour is as the developer intended."
See also: MISRA2004-12_1_e, MISRA2004-12_5

SINCE
v7.3

EXCEPTIONS
"Where an expression consists of either a sequence of only logical '&&'
or a sequence of only logical '||', extra parentheses are not required.

BENEFITS
"The effect of this rule is to require that operands are appropriately
parenthesized."

EXAMPLE
int foo( int x, int y, int z )
{
if ( x || y && z );
// Violation
if ( x && !y );
// Violation
return 0;
}

REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
if ( x && ( !y ) );

// OK
// OK

return 0;
}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-1
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 158

The increment (++) and decrement (--) operators should not be mixed with other operators in
an expression [MISRA2008-5_2_10-4]
DESCRIPTION
"It is the intention of the rule that when the increment or decrement
operator
is used, it should be the only side-effect in the statement.
The use of increment and decrement operators in combination with other
arithmetic operators is not recommended because:
- It can significantly impair the readability of the code
- It introduces additional side effects into a statement with the
potential for
undefined behaviour
It is safer to use these operations in isolation from any other arithmetic
operators."

BENEFITS
Improves readability and maintainability.
Reduces risk of potential undefined behaviour
caused by additional side effects

EXAMPLE
void foo() {
int x, y;
x = --y + x++;
}

/* Violation */

REPAIR
void foo() {
int x, y;
--y;
x = y + x;
x++;
}

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-10

The comma operator, && operator and the || operator shall not be overloaded [MISRA20085_2_11-3]
DESCRIPTION
"The built-in &&, || or, (comma) enjoy special treatment from the
compiler.
If you overload them, they become ordinary functions with very different
semantics, and this is a sure way to introduce subtle bugs and
fragilities."
This rule detects when you overload operator &&, || or ,(comma).

BENEFITS
Overloading these operators changes the way the compiler reads the
semantics of an expression, resulting in unpredictable program behavior.

EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
~A( );
int value( ) { return _i; }
private:
int _i;
};
int operator&&( A& lhs, A& rhs ) {
return lhs.value( ) && rhs.value( );
}

// Violation

REPAIR
Do not overload operator &&, || or ,(comma).

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-

Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 30
2. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 159
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-11
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

An identifier with array type passed as a function argument shall not decay to a pointer
[MISRA2008-5_2_12-3]
DESCRIPTION
"When a variable with array type decays to a pointer, its bounds are
lost."

SINCE
v7.2

BENEFITS
"If a design requires arrays of different lengths, then a class should
be used to encapsulate the array objects and so ensure that the
dimensionality
is maintained."

EXAMPLE
typedef int int32_t;
void f1( int32_t p[ 10 ] );
void f2( int32_t *p );
void b ()
{
int32_t a[ 10 ];
f1( a ); // Violation
f2( a ); // Violation
}

REPAIR
typedef int int32_t;
void f1( int32_t ( &p )[ 10 ] );

void b ()
{
int32_t a[ 10 ];
f1( a );
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-12

A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of
dynamic_cast [MISRA2008-5_2_2-3]
DESCRIPTION
"Since the virtualness of inheritance is not a property of a base class,
the layout of a derived class object, referenced through a virtual base
pointer, is unknown at compile time."
"Casting from a virtual base to a derived class, using any means
other than dynamic_cast has undefined behaviour.
The behaviour for dynamic_cast is defined."
See also: OOP-29, OOP-49

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviours.

EXAMPLE
// The code is not compilable with all compilers
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = static_cast<D*>(pB); // Violation
}

REPAIR

class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = dynamic_cast<D*>(pB);
}

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 179
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-2

Casts from a base class to a derived class should not be performed on polymorphic types
[MISRA2008-5_2_3-4]
DESCRIPTION
"A downcast occurs when a class type is converted to another class type
that is derived from that first class.
Polymorphism enables strong abstraction between the interface and
implementation
of a hierarchy. Explicit casts bypass this layer of abstraction resulting
in higher levels of coupling and dependency."
"Casting from a base class to a derived class is unsafe unless some
mechanism
is provided to ensure that the cast is legitimate."
See also: OOP-29, OOP-50

SINCE
v7.2

BENEFITS
Prevents illegal casts and ensures that abstraction layer is not bypassed.

EXAMPLE
class B
{
public:
virtual int foo( );
};
class D : public B
{
public:
int foo( );
};
void main( )
{
B *b;

D *d;
d = (D*) b; // Violation
}

REPAIR
Do not cast a pointer to a base class to a pointer to a class
that inherits from it.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-3

C-style casts (other than void casts) and functional notation casts (other than explicit
constructor calls) shall not be used [MISRA2008-5_2_4-3]
DESCRIPTION
"C-style (cast notation), and functional notation casts that do not invoke
a converting constructor are capable of performing casts between unrelated
types."

SINCE
v7.2

EXCEPTIONS
"A C-style cast to void may be used to signify that the return value
for a non-void function call is being ignored"

BENEFITS
C++ casts are more specific than C casts and are much easier to locate
and read.

EXAMPLE
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD2 = (Derived *) pB;

// Violation

REPAIR
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD1 = dynamic_cast<Derived*>( pB );
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-4

A cast shall not remove any const or volatile qualification from the type of a pointer or
reference [MISRA2008-5_2_5-3]
DESCRIPTION
"Any attempt to remove the qualification associated with the addressed
type by
using casting is a violation of the principle of type qualification.
Notice that the qualification referred to here is not the same as any
qualification that may be applied to the pointer itself."

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
typedef unsigned short uint16_t;
void foo( )
{
uint16_t *pi, **ppi;
uint16_t * const * pcpi; /* pointer
const uint16_t * * ppci; /* pointer
const uint16_t * pci;
/* pointer
volatile uint16_t * pvi; /* pointer
pi = (uint16_t *)pci;
pi = (uint16_t *)pvi;
ppi = (uint16_t * *)pcpi;
ppi = (uint16_t * *)ppci;

/*
/*
/*
/*

to
to
to
to

Violation
Violation
Violation
Violation

const pointer */
pointer to const */
const */
volatile */
*/
*/
*/
*/

REPAIR
Do not cast from 'const' or 'volatile' type addressed by a pointer to
'non-const'
or 'non-volatile' type.

REFERENCES

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 11
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-5

A cast shall not convert a pointer to a function to any other pointer type, including a pointer to
function type [MISRA2008-5_2_6-3]
DESCRIPTION
"Conversion of a function pointer to a non-function pointer type causes
undefined behaviour. Undefined behaviour may arise if a function call is
made using a pointer that is the result of a function pointer conversion."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
void f ( int )
{
reinterpret_cast< void (*)( ) >( &f ); // Violation
reinterpret_cast< void * >( &f );
// Violation
}

REPAIR
Do not cast a pointer to a function to any other pointer type.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-6

An object with pointer type shall not be converted to an unrelated pointer type, either directly
or indirectly [MISRA2008-5_2_7-3]
DESCRIPTION
"A cast should not be performed between a pointer to object type and a
different
pointer to object type. Conversions of this type may be invalid if the new
pointer type requires a stricter alignment.
Pointer types can be classified as follows:
- Pointer to object
- Pointer to function
- Pointer to void
- The null pointer constant (the value 0 cast to type void *)"

NOTES
Pointers which are different only const or volatile qualifier are not
checked
by this rule.

BENEFITS
Prevents incorrect pointer alignment.

EXAMPLE
void foo( )
{
unsigned int* ui;
signed char* sc;
/* Examples of incorrect code */
ui = (unsigned int*) sc;
ui = (unsigned int*) &sc;
}

REPAIR

/* Violation */
/* Violation */

typedef unsigned int uint32_t;


void foo( )
{
unsigned int* ui;
uint32_t* ui_t;
/* Examples of correct code */
ui = (unsigned int*) ui_t;
ui = (unsigned int* const) ui_t;

/* OK */
/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
2. Origin: Misra Guidelines rule 45
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-7
4. ISO/DIS 26262
point 8.4.4

An object with integer type or pointer to void type shall not be converted to an object with
pointer type [MISRA2008-5_2_8-3]
DESCRIPTION
"An object with integer type or pointer to void type shall
not be converted to an object with pointer type"

SINCE
v7.2

BENEFITS
In general, converting from an integral type or a pointer to void type
to a pointer to an object leads to unspecified behaviour.

EXAMPLE
struct S
{
int i;
int j;
};
void f ( void * v, int i )
{
S * s1 = reinterpret_cast< S * >( v ); // Violation
S * s2 = reinterpret_cast< S * >( i ); // Violation
}

REPAIR
Do not cast an object with integer type or pointer to void type
to an object with pointer type

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems
Chapter 6, Section 5, Rule 5-2-8

A cast should not convert a pointer type to an integral type [MISRA2008-5_2_9-4]


DESCRIPTION
"The size of integer that is required when a pointer is converted to an
integer
is implementation-defined. Casting between a pointer and an integer type
should
be avoided where possible, but may be unavoidable when addressing memory
mapped
registers or other hardware specific features."

EXCEPTIONS
The rule allows to cast to UINT_PTR or INT_PTR type. These types are
integral
types that scale to the size of a pointer for both 32-bit and 64-bit
Windows.

BENEFITS
Prevents undefined or implementation-defined behaviour.

EXAMPLE
void foo( ) {
int* pi;
int i;
i = (int) pi;
}

// Violation

REPAIR
Do not cast pointers to non-pointers.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 11
2. Misra Guidelines rule 45
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 7
4. http://msdn2.microsoft.com/en-gb/library/aa489560.aspx
5. http://www.codeproject.com/system/64BitOSAndPortingIssues.asp
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
7. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-9
8. ISO/DIS 26262
point 8.4.4

Each operand of the ! operator, the logical && or the logical || operators shall have type bool
[MISRA2008-5_3_1-3]
DESCRIPTION
"The use of operands with types other than bool with these operators is
unlikely to be meaningful (or intended). This rule allows the detection of
such uses, which often occur because the logical operators (&&, || and !)
can be easily confused with the bitwise operators (&, | and ~)."

SINCE
v7.2

NOTES
Rule does not report violations if the operand is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.

BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.

EXAMPLE
/* examples of incorrect code */
void foo(int a, int b, int c, int d, int* ptr)
{
if ( 1 && ( c < d ) ) {}
// Violation
if ( ( a < b ) && ( c + d ) ){} // Violation
if ( a || ( c + d ) ) {}
// Violation
if ( !ptr ) {}
// Violation
}

REPAIR
/* examples of correct code */

void foo(int a, int b, int c, int d)


{
if ( ( a < b ) && ( c < d ) ){}
// OK
if ( ( a == b ) || ( c != d ) ){} // OK
if ( !false ) {}
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-1

The unary minus operator shall not be applied to an expression whose underlying type is
unsigned [MISRA2008-5_3_2-3]
DESCRIPTION
"Applying the unary minus operator to an expression of type unsigned int
or
unsigned long generates a result of type unsigned int or unsigned long
respectively and is not a meaningful operation. Applying unary minus to an
operand of smaller unsigned integer type may generate a meaningful signed
result
due to integral promotion, but this is not good practice."

BENEFITS
Prevents unexpected result due to integral promotion.

EXAMPLE
void foo() {
unsigned char ui1;
signed short si2;
si2 = -ui1;
}

// Violation

REPAIR
void foo() {
unsigned char ui1;
signed short si2;
si2 = -(signed short) ui1;
}

// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12

2. Origin: Misra Guidelines - Rule 39


3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 165
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-2

The unary & operator shall not be overloaded [MISRA2008-5_3_3-3]


DESCRIPTION
"Taking the address of an object of incomplete type where the complete
type
contains a user declared operator & leads to undefined behaviour"

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
class A
{
public:
A * operator & ( );
};

// Violation

REPAIR
Do not overload the unary '&' operator

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-3

Evaluation of the operand to the sizeof operator shall not contain side effects [MISRA20085_3_4-3]
DESCRIPTION
"A possible programming error in C is to apply the sizeof operator to an
expression and expect the expression to be evaluated. However the
expression
is not evaluated: sizeof only acts on the type of the expression. To avoid
this
error, sizeof shall not be used on expressions that contain side effects,
as the side effects will not occur."
"The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."

NOTES
Rule checks only three nested level of function calls.

EXCEPTIONS
An operand of the form sizeof(i) where i is volatile is permitted.

BENEFITS
Prevents error that are caused by believing that operand of sizeof is
evaluated.

EXAMPLE
int glob;
int fun_with_se(){
glob++; // side-effect
return glob;
}
void foo1(int i){

int
j =
l =
m =

j, k, l, m;
sizeof(k = 2);
// Violation - k is not set to 2
sizeof(i++);
// Violation - i is not incremented
sizeof(fun_with_se()); // Violation - glob is not incremented

REPAIR
int fun_without_se(){
// no side-effect
return 1;
}
void foo1(int i){
int j, k, l, m, n, o;
volatile int vol;
k = 2;
j = sizeof(k);
i++;
l = sizeof(i);
// examples of correct code
m = sizeof(fun_without_se());
n = sizeof(int);
o = sizeof(vol);
}

// OK
// OK
// OK
// OK
// OK - volatile objects are permitted

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 166
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-4

The right hand operand of a shift operator shall lie between zero and one less than the width
in bits of the underlying type of the left hand operand [MISRA2008-5_8_1-3]
DESCRIPTION
"If, for example, the left-hand operand of a left-shift or right-shift is
a
16-bit integer, then it is important to ensure that this is shifted only
by a
number between 0 and 15 inclusive.
There are various ways of ensuring this rule is followed. The simplest is
for
the right-hand operand to be a constant (whose value can then be
statically
checked). Use of an unsigned integer type will ensure that the operand is
non-negative, so then only the upper limit needs to be checked
(dynamically at
run-time or by review). Otherwise both limits will need to be checked."
The rule checks right-hand operand of shift operator and reports a
violation
in following cases:
- the operand is a constant with negative value or with value that exceeds
the length (in bits) of the left-hand operand
- the operand is a non-const variable and it's value is not checked by
specific
pattern.
The specific pattern recognized by the rule requires the shift operator
to be wrapped by an 'if' statement which checks the variable's value
using
comparison operators (both "greater then" and "less then" operators must
be used).

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )

uint8_t;
uint16_t;

{
uint8_t u8a;
u8a = (uint8_t) (u8a << 9); /* Violation */
u8a = (uint8_t) (u8a << p); /* Violation */
}

REPAIR
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
{
uint8_t u8a;
uint16_t u16a;

uint8_t;
uint16_t;

u16a = (uint16_t) ((uint16_t) u8a << 9); /* OK */


if (p >= 0 && p <= 8) {
u8a = (uint8_t) (u8a << p); /* OK - p range checked */
}
u8a = (uint8_t) (u8a << 4); /* OK - constant value in range */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-8-1

Assignment operators shall not be used in sub-expressions [MISRA2008-6_2_1-3]


DESCRIPTION
"No assignments are permitted in any expression which is considered to
have a
Boolean value. This precludes the use of both simple and compound
assignment
operators in the operands of a Boolean-valued expression. However, it does
not
preclude assigning a Boolean value to a variable. If assignments are
required
in the operands of a Boolean-valued expression then they must be performed
separately outside of those operands. This helps to avoid getting "=" and
"=="
confused, and assists the static detection of mistakes."

NOTES
An expression is considered to represent a Boolean value either because
it appears in a position where a Boolean value is expected or because it
uses an operator that gives rise to a Boolean value. Boolean values are
expected in the following contexts:
- the controlling expression of an if statement
- the controlling expression of an iteration statement
- the first operand of the conditional operator ?

BENEFITS
Rule prevents getting "=" and "==" confused.

EXAMPLE
void foo()
{
int x;
int y;
int z;
z = !(x = y);
if ((x > y) && (x = 4));

// Violation
// Violation

if (!(x = y));

// Violation

REPAIR
void foo()
{
int x;
int y;
int z;
z = !(x == y);
// OK
if ((x > y) && (x == 4)); // OK
if (!(x == y));
// OK
}

REFERENCES
1. Misra Guidelines - Rule 35
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 160
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-1

Floating-point expressions shall not be directly or indirectly tested for equality or inequality
[MISRA2008-6_2_2-3]
DESCRIPTION
"Floating-point expressions shall not be tested for equality or
inequality.
The recommended method for achieving deterministic floating-point
comparisons is
to write a library that implements the comparison operations. The library
should
take into account the floating-point granularity (FLT_EPSILON) and the
magnitude
of the numbers being compared."

NOTES
Rule does not detect indirect tests of equality and inequality which are
equally
problematic and are also forbidden by Misra standard:
if ( ( x <= y ) && ( x >= y ) )
{
/* ... */
}

BENEFITS
"The inherent nature of floating-point types is such that comparisons of
equality will often not evaluate to true even when they are expected to.
In
addition the behaviour of such a comparison cannot be predicted before
execution, and may well vary from one implementation to another. "

EXAMPLE
void foo() {
float x, y;
if (x == y);
if (x == 0.0f);

// Violation
// Violation

REPAIR
void foo( float epsilon ) {
float x, y;
if (x - epsilon <= y && y <= x + epsilon);
if (-epsilon <= x && x <= epsilon);

// OK
// OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 50
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 202
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-2

Before preprocessing, a null statement shall only occur on a line by itself; it may be followed
by a comment, provided that the first character following the null statement is a white-space
character [MISRA2008-6_2_3-3]
DESCRIPTION
"Null statements should not normally be deliberately included, but where
they
are used they shall appear on a line by themselves.
White-space characters may precede the null statement to preserve
indentation.
If a comment follows the null statement then at least one white-space
character
shall separate the null statement from the comment.
The use of a white-space character to separate the null statement from any
following comment is required on the grounds that it provides an important
visual cue to reviewers."
See also: MISRA-054.

BENEFITS
"Following this rule enables a static checking tool to
warn of null statements appearing on a line with other text,
which would normally indicate a programming error."

EXAMPLE
void foo()
{
/* Violation */ ;
;/* Violation */
}

REPAIR
void goo()
{
/* OK */

;
; /* OK */
;
/* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-3

The statement forming the body of a switch, while, do while or for statement shall be a
compound statement [MISRA2008-6_3_1-3]
DESCRIPTION
" The statement that forms the body of a switch statement or a while,
do ... while or for loop, shall be a compound statement (enclosed within
braces), even if that compound statement contains a single statement."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x ) {
int i;
switch(i)
;

// Violation

for (i=0; i< 10; i++) // Violation


foo( x );
while (1)
// Violation
foo( x );
do
foo( x );
while(1);

// Violation

REPAIR
void foo( int x ) {
int i;
switch(i)
{
}

// OK

for (i=0; i< 10; i++) // OK

{foo( x );}
while (1)
{foo( x );}

// OK

do

// OK

{foo( x );}
while(1);
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 59
3. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-3-1

An if ( condition ) construct shall be followed by a compound statement. The else keyword


shall be followed by either a compound statement, or another if statement [MISRA2008-6_4_13]
DESCRIPTION
"An 'if' (expression) construct shall be followed by a compound statement.
The 'else' keyword shall be followed by either a compound statement,
or another 'if' statement."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int x, int
{
int i, j;
if(x > 0)
//
x = i;
else if(y > 0) //
y = i;
else
y = j;
//
x = j;
}

y )

Violation
Violation

Violation

REPAIR
void foo( int x, int y )
{
int i, j;
if(x > 0)
// OK
{
x = i;
}
else if(y > 0) // OK
{
y = i;

}
else
{
y = j;
x = j;

// OK

}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Misra Guidelines - Rule 59
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-1

All if ... else if constructs shall be terminated with an else clause [MISRA2008-6_4_2-3]
DESCRIPTION
"This rule applies whenever an 'if' statement is followed by one or more
'else-if' statements; the final 'else-if' shall be followed by an 'else'
statement. In the case of a simple 'if' statement then the 'else'
statement
need not be included.
The requirement for a final 'else' statement is defensive programming.
The 'else' statement should either take appropriate action or contain
a suitable comment as to why no action is taken."
See also: CODSTA-23

BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.

EXAMPLE
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
}

// Violation

REPAIR
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}

// OK

else
{
// comment or action
}
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 60
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 192
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-2

A switch statement shall be a well-formed switch statement [MISRA2008-6_4_3_a-3]


DESCRIPTION
"The scope of a case or default label shall be the compound statement,
which is the body of a switch statement.
All case clauses and the default clause shall be at the same scope."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int a, int b ) {
switch(a) {
case 1:
{
case 6:
/* Violation */
;
default:
/* Violation */
break;
}
break;
case 2:
if (b == 1) {
case 3:
/* Violation */
break;
}
break;
}
}

REPAIR
Do not use nested 'case'/'default' statements.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical

systems
Chapter 6, Section 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-4

A switch statement shall be a well-formed switch statement [MISRA2008-6_4_3_b-3]


DESCRIPTION
"An unconditional throw or break statement shall terminate every non-empty
switch-clause. If a developer fails to add a break statement to the end of
a switch-clause, then control flow "falls" into any following switchclause.
Whilst this is sometimes intentional, it is often an error. To ensure that
such errors can be detected, the last statement in every switch-clause
shall
be a break statement, or if the switch-clause is a compound statement,
then the
last statement in the compound statement shall be a break statement. A
special
case exists if the switch-clause is empty, as this allows groups of
clauses
requiring identical statements to be created."

SINCE
v7.2

BENEFITS
Prevents unpredictable program behaviour.

EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
{

// Violation

// Violation

i = 5;
break;
}
case 2 :
{

// Violation
i = 3;

}
default:
i = 8;

// Violation

}
}

REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
throw;
}
}

// OK

// OK

// OK

// OK - empty case
// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3

A switch statement shall be a well-formed switch statement [MISRA2008-6_4_3_c-3]


DESCRIPTION
"The final clause of a switch statement shall be the default-clause.
The requirement for a final default-clause is defensive programming.
This clause shall either take appropriate action, or else contain a
suitable
comment as to why no action is taken."

SINCE
v7.2

EXCEPTIONS
"If the condition of a switch statement is of type enum, and all the
enumerators are listed in case labels, then the default-clause is not
required
as the rules associated with enums are intended to ensure that the enum
cannot
be assigned values outside of its set of enumerators."

BENEFITS
Rule improves readability and maintainability of 'switch' statement.

EXAMPLE
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;

// Violation

}
switch( colour )
{
case RED:
break;
case GREEN:
break;

// Violation

}
}

REPAIR
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
default:
break;
}
switch( colour )
{
case RED:
break;
case BLUE:
break;
case GREEN:
break;
}
}

// OK

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3

A switch statement shall be a well-formed switch statement [MISRA2008-6_4_3_d-3]


DESCRIPTION
Values which are effectively Boolean should not be represented in
'switch' condition.
The rule forbids following operators:
a) equality operators (== and !=)
b) logical operators (!, && and ||)
c) relational operators (<, >, <= and >=)
which produce boolean-by-construct values.

BENEFITS
Rule prevents using values that are effectively Boolean in switch.

EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}

// Violation

REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}

REFERENCES

// OK

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 63
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 195
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-7

A switch statement shall be a well-formed switch statement [MISRA2008-6_4_3_e-3]


DESCRIPTION
Every switch statement shall have at least one case.
See also: OPT-21, OPT-22, CODSTA-54

BENEFITS
Provides maintainability of 'switch' statement.

EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}

/* Violation */

REPAIR
void foo(int i)
{
switch(i)
{
case 1:
{
}
default:
;
}
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 64
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-8

A switch-label shall only be used when the most closely-enclosing compound statement is the
body of a switch statement [MISRA2008-6_4_4-3]
DESCRIPTION
"The scope of a case or default label shall be the compound statement,
which is the body of a switch statement.
All case clauses and the default clause shall be at the same scope."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo( int a, int b ) {
switch(a) {
case 1:
{
case 6:
/* Violation */
;
default:
/* Violation */
break;
}
break;
case 2:
if (b == 1) {
case 3:
/* Violation */
break;
}
break;
}
}

REPAIR
Do not use nested 'case'/'default' statements.

REFERENCES

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-4

An unconditional throw or break statement shall terminate every non-empty switch-clause


[MISRA2008-6_4_5-3]
DESCRIPTION
"An unconditional throw or break statement shall terminate every non-empty
switch-clause. If a developer fails to add a break statement to the end of
a switch-clause, then control flow "falls" into any following switchclause.
Whilst this is sometimes intentional, it is often an error. To ensure that
such errors can be detected, the last statement in every switch-clause
shall
be a break statement, or if the switch-clause is a compound statement,
then the
last statement in the compound statement shall be a break statement. A
special
case exists if the switch-clause is empty, as this allows groups of
clauses
requiring identical statements to be created."

SINCE
v7.2

BENEFITS
Prevents unpredictable program behaviour.

EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)

// Violation

// Violation

{
i = 5;
break;
}
case 2 :
{

// Violation
i = 3;

}
default:
i = 8;

// Violation

}
}

REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
throw;
}
}

// OK

// OK

// OK

// OK - empty case
// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3

The final clause of a switch statement shall be the default-clause [MISRA2008-6_4_6-3]


DESCRIPTION
"The final clause of a switch statement shall be the default-clause.
The requirement for a final default-clause is defensive programming.
This clause shall either take appropriate action, or else contain a
suitable
comment as to why no action is taken."

SINCE
v7.2

EXCEPTIONS
"If the condition of a switch statement is of type enum, and all the
enumerators are listed in case labels, then the default-clause is not
required
as the rules associated with enums are intended to ensure that the enum
cannot
be assigned values outside of its set of enumerators."

BENEFITS
Rule improves readability and maintainability of 'switch' statement.

EXAMPLE
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;

// Violation

}
switch( colour )
{
case RED:
break;
case GREEN:
break;

// Violation

}
}

REPAIR
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
default:
break;
}
switch( colour )
{
case RED:
break;
case BLUE:
break;
case GREEN:
break;
}
}

// OK

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3

The condition of a switch statement shall not have bool type [MISRA2008-6_4_7-3]
DESCRIPTION
Values which are effectively Boolean should not be represented in
'switch' condition.
The rule forbids following operators:
a) equality operators (== and !=)
b) logical operators (!, && and ||)
c) relational operators (<, >, <= and >=)
which produce boolean-by-construct values.

BENEFITS
Rule prevents using values that are effectively Boolean in switch.

EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}

// Violation

REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}

REFERENCES

// OK

1. MISRA-C:2004 Guidelines for the use of the C language in critical


systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 63
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 195
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-7

Every switch statement shall have at least one case-clause [MISRA2008-6_4_8-3]


DESCRIPTION
Every switch statement shall have at least one case.
See also: OPT-21, OPT-22, CODSTA-54

BENEFITS
Provides maintainability of 'switch' statement.

EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}

/* Violation */

REPAIR
void foo(int i)
{
switch(i)
{
case 1:
{
}
default:
;
}
}

/* OK */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems

Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 64
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-8

A for loop shall contain a single loop-counter which shall not have floating type [MISRA20086_5_1-3]
DESCRIPTION
"A for loop without exactly one loop-counter is simply a while loop.
If this is the desired behaviour, then a while loop is more appropriate."

SINCE
v7.2

NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.

BENEFITS
Rule helps to ensure deterministic loop termination.

EXAMPLE
void foo()
{
int x = 0;
int y;
y = 0;
for (x = 0; x < y; x = y++){} // Violation
}

REPAIR
void foo3()
{

int x = 0;
int y;
y = 0;
x = 0;
while(x < y) // OK
{
x = y++;
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-1

If loop-counter is not modified by -- or ++, then, within condition, the loop-counter shall only
be used as an operand to <=, <, > or >= [MISRA2008-6_5_2-3]
DESCRIPTION
"When the loop-counter is modified using an operator other than -- or ++,
then == and != shall not be used, as loop termination may not occur,
which may be inconsistent with developer expectations."

SINCE
v7.2

NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.

BENEFITS
Rule helps to ensure deterministic loop termination.

EXAMPLE
void foo()
{
int i;
for ( i = 1; i != 10; i += 2 ){} // Violation
}

REPAIR
void foo()
{
int i;

for ( i = 1; i <= 10; i += 2 ){} // OK


for ( i = 1; i != 10; ++i ){}
// OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-2

The loop-counter shall not be modified within condition or statement [MISRA2008-6_5_3-3]


DESCRIPTION
"Loop counters shall not be modified in the body of the loop.
However other loop control variables representing logical values
may be modified in the loop, for example a flag to indicate that something
has been completed, which is then tested in the for statement."

NOTES
A
-

loop-counter is a loop-control-variable that is:


Initialized in, or prior to, for-init-statement; and
an operand to a relational operator in condition; and
modified in expression.

BENEFITS
Modification 'for' loop counter within a body of the loop can lead to
errors and confusion.

EXAMPLE
void foo( ) {
int i;
for ( i = 0; i < 5; i++ ) {
i = i + 3;
}
}

/* Violation */

REPAIR
void foo( ) {
int i;
for ( i = 0; i < 5; i = i + 3 ) {} /* OK */
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 67
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 201
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-5-3

The loop-counter shall be modified by one of: --, ++, -=n, or +=n; where n remains constant for
the duration of the loop [MISRA2008-6_5_4-3]
DESCRIPTION
"The loop-counter shall be modified by one of: --, ++, -=n, or +=n;
where n remains constant for the duration of the loop"

SINCE
v7.2

NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.

BENEFITS
Rule helps to ensure deterministic loop termination.

EXAMPLE
void foo()
{
int x;
for ( x = 0; x < 10; x = x + 1 ){} // Violation
}

REPAIR
void foo()
{
int x;
for ( x = 0; x < 10; ++x ){} // OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-4

A loop-control-variable other than the loop-counter shall not be modified within condition or
expression [MISRA2008-6_5_5-3]
DESCRIPTION
"A loop-control-variable other than the loop-counter shall
not be modified within condition or expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
loop-control-variables are either the loop-counter, or flags used for
early
loop termination. The code is easier to understand if these are not
modified
within condition or expression."

SINCE
v7.2

NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.

BENEFITS
Rule improves readability of code.

EXAMPLE
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; flag = test(++x) ) {}
}

// Violation

REPAIR
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; ++x ) // OK
{
flag = test(x);
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-5

A loop-control-variable other than the loop-counter which is modified in statement within a


body of the loop shall have type bool [MISRA2008-6_5_6-3]
DESCRIPTION
"A loop-control-variable other than the loop-counter which is modified
in statement shall have type bool.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
loop-control-variables are typically used to terminate a for loop early.
The code is easier to understand if this is done with the use
of Boolean values"

SINCE
v7.2

NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && ( u8a != 3U ); ++x )
{
u8a = 5;
// Violation
}
}

REPAIR
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && flag; ++x )
{
u8a = 5;
// OK
flag = u8a != 3U;
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-6

Any label referenced by a goto statement shall be declared in the same block, or in a block
enclosing the goto statement [MISRA2008-6_6_1-3]
DESCRIPTION
"Any label referenced by a goto statement shall be declared in the same
block,
or in a block enclosing the goto statement. Unconstrained use of goto can
lead to programs that are extremely difficult to comprehend, analyse and,
for C++, can also lead to the program exhibiting unspecified behaviour.
However, in many cases a total ban on goto requires the introduction of
flags to ensure correct control flow, and it is possible that these flags
may themselves be less transparent than the goto they replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. Jumping in to nested
blocks is
prohibited as it may lead to complex flow graphs."

SINCE
v7.2

BENEFITS
Prevents unspecified behaviour.

EXAMPLE
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
L1: // Violation
j;
}
}

REPAIR
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
}
L1: // OK
j;
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-1

The goto statement shall jump to a label declared later in the same function body [MISRA20086_6_2-3]
DESCRIPTION
"Unconstrained use of goto can lead to programs that are extremely
difficult
to comprehend, analyse and, for C++, can also lead to the program
exhibiting
unspecified behaviour. However, in many cases a total ban on goto requires
the introduction of flags to ensure correct control flow, and it is
possible
that these flags may themselves be less transparent than the goto they
replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. "Back" jumps are
prohibited
as they can be used to create iterations without using the well-defined
iteration statements supplied by the core language."

SINCE
v7.2

BENEFITS
Prevents unspecified behaviour.

EXAMPLE
void foo(int j)
{
L1:
++j;
goto L1; // Violation - jumps backward
++j;
}

REPAIR
void foo(int j)
{
++j;
goto L1; // OK ++j;
L1:
}

jumps forward

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-2

The continue statement shall only be used within a well-formed for loop [MISRA2008-6_6_3-3]
DESCRIPTION
"Over-use of the continue statement can lead to unnecessary complexity
within
the code. This complexity may impede effective testing as extra logic must
be
tested. The required testing may not be achievable due to control flow
dependencies."

SINCE
v7.2

EXCEPTIONS
Rule does not report a violation if the 'continue' is used within 'for'
loop.

BENEFITS
Rule eliminates unnecessary complexity within the code.

EXAMPLE
void foo()
{
int x = 0;
int y;
y = 10;
while(x < y)
{
x++;
/* ... */
continue;
}

// Violation

REPAIR
Do not use 'continue' statement outside 'for' loop.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-3

For any iteration statement there shall be no more than one break or goto statement used for
loop termination [MISRA2008-6_6_4-3]
DESCRIPTION
"For any iteration statement there shall be no more than one break or goto
statement used for loop termination."

SINCE
v7.2

BENEFITS
"Restricting the number of exits from a loop is done in the interests of
good
structured programming. One break or goto statement is acceptable in a
loop
since this allows, for example, for dual outcome loops or optimal coding."

EXAMPLE
void foo( ) {
int a;
for (a = 0; a < 10; a++) { // Violation
if (a == 5) {
break;
}
if (a == 7) {
break;
}
}
}

REPAIR
void foo( ) {
int a;

for (a = 0; a < 10; a++) { // OK


if (a == 5 || a == 7) {
break;
}
}
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-4

A function shall have a single point of exit at the end of the function [MISRA2008-6_6_5-3]
DESCRIPTION
Every function should have a single point of exit.

NOTES
Calls of functions exit, abort, and _Exit from standard library stdlib.h
are detected by rule as exit points.

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
int foo(int i)
{
if (i == 0) {
return 0;
// Violation
} else if (i == 1) {
return 1;
// Violation
} else {
return 2;
// Violation
}
}
int foo2(int a) {
int result;
if (a > 0) {
return result;
}
}

REPAIR
int foo(int i)
{
int result = 0;

// Violation

if (i == 0) {
result = 0;
} else if (i == 1) {
result = 1;
} else {
result = 2;
}
return result;
// OK
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 82
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 113
4. ISO/DIS 26262
point 8.4.4

A variable which is not modified shall be const qualified [MISRA2008-7_1_1-3]


DESCRIPTION
This rule checks if you declared your parameters or local variables as
const.
Immutable values are easier to understand, track, and reason about, so
prefer
constants over variables whenever it is sensible and make const your
default
choice when you define a value.
See also: CODSTA-CPP-43, MISRA2004-16_7

SINCE
v7.0

NOTES
For parameters and variables of pointer type the const qualifier
should be applied to the pointer, not to the pointed object.

BENEFITS
It's safe, it's checked at compile time, and it's integrated
with C++'s type system. It also prevents future revisions
from unintentional changing the caller's data.

EXAMPLE
int foo1(int param1,
int* param2,
const int* param3)

// Violation
// Violation
// Violation - const is applied to the
// pointed object, not to the pointer

{
int var1 = 0;
// Violation
return param1 + *param2 + *param3 + var1;
}
int foo2(int param1,

// OK - param1 is modified

int* param2,
const int* param3)

// OK - param2 is modified
// OK - param3 is modified

{
int var1 = 0;
// OK - var1 is modified
param1++;
param2++;
param3++;
var1 = param1 + *param2 + *param3;
return var1;
}

REPAIR
// Fixed violations - const added
int foo1(const int param1,
int* const param2,
const int* const param3)

// OK
// OK - const is applied to the pointer
// OK - const is applied to the pointed
// object and to the pointer

{
const int var1 = 0;
// OK
return param1 + *param2 + *param3 + var1;
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc., Chapter: "Coding Style", Rule 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A pointer parameter in a function shall be declared as pointer to const if the corresponding


object is not modified [MISRA2008-7_1_2_a-3]
DESCRIPTION
"A pointer parameter in a function prototype should be declared as pointer
to
const if the pointer is not used to modify the addressed object. The const
qualification should be applied to the object pointed to, not to the
pointer,
since it is the object itself that is being protected."
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104

NOTES
There can already be overloaded function with parameter declared as
pointer
to const. Then changing the type of parameter to pointer to const will
make
the code non-compilable.

EXCEPTIONS
Violation is not reported if parameter is unnamed.

BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.

EXAMPLE
int function(int* ptr)
{
return (*ptr) + 1;
}

REPAIR

// Violation

int function(const int* ptr) // OK


{
return (*ptr) + 1;
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2

A reference parameter in a function shall be declared as reference to const if the


corresponding object is not modified [MISRA2008-7_1_2_b-3]
DESCRIPTION
This rule checks if you declared your reference parameters as const
references.
When your function is not going to modify the argument it is referencing,
you
should use const to protect variables from unintended modifications when
the
function returns.
See also: CODSTA-CPP-03, CODSTA-CPP-38, CODSTA-CPP-44,
MISRA-104, MISRA2004-16_7, OPT-21

NOTES
The rule does not report violations on virtual functions.

BENEFITS
Declaring parameters which are not modified as const reference instead of
reference improves legibility. It also prevents future revisions from
unintentional changing the caller's data.

EXAMPLE
struct Foo {
int x;
int y;
};
int Bar( Foo &f ) {
return f.x;
}

// Violation

int FooBar( Foo &f ) { // OK


return f.x++;
}

REPAIR
struct Foo {
int x;
int y;
};
int Bar( const Foo &f ) {
return f.x;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declare a type of parameter as typedef to pointer to const if the pointer is not used to modify
the addressed object [MISRA2008-7_1_2_c-3]
DESCRIPTION
The rule reports a violation if a parameter in a function prototype is
declared
as typedef to pointer to non-const object and the pointer is not used to
modify
the addressed object. Then the type of parameter could be changed to
typedef
to pointer to const object.
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104

NOTES
It is not sufficient to add 'const' identifier before typedef's
name in a function declaration, because it is applied to pointer
not to pointed object.
There can already be overloaded function with parameter declared as
typedef
to pointer to const. Then changing the type of parameter to typedef to
pointer
to const will make the code non-compilable.

BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.

EXAMPLE
typedef int* PINT;
typedef const int* CINT;
int function1(PINT ptr)
{
return (*ptr) + 1;
}

// Violation

int function2(const PINT ptr)

// Violation

{
return (*ptr) + 1;
}

REPAIR
typedef int* PINT;
typedef const int* CINT;
int function1(CINT ptr)
{
return (*ptr) + 1;
}

// OK

int function2(const CINT ptr)


{
return (*ptr) + 1;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2

The global namespace shall only contain main, namespace declarations and extern "C"
declarations [MISRA2008-7_3_1-3]
DESCRIPTION
This rule detects the use of global variables, classes,
and global functions outside of namespaces.

BENEFITS
Prevents the use of global variables, classes, and global functions
outside namespaces. All data and functions in a file should be inside
one or more namespaces.

EXAMPLE
int var = 0;

// Violation

void globalfoo( ) { // Violation


}
class A {
int i;
void foo( );
};

// Violation

REPAIR
namespace name1 {
int var = 0;

// OK

void globalfoo( ) { // OK
}
class A {
int i;
void foo();
};
}

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.11 Namespaces, AV Rule 98
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-3-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
4. ISO/DIS 26262
point 8.4.4

The identifier main shall not be used for a function other than the global function main
[MISRA2008-7_3_2-3]
DESCRIPTION
"main (or its equivalent) is usually the entry point to the program and is
the
only identifier which must be in the global namespace. The use of main for
other functions may not meet developer expectations."

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
namespace
{
int main ( ){} // Violation
}

REPAIR
int main ( ){}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-2

There shall be no unnamed namespaces in header files [MISRA2008-7_3_3-3]


DESCRIPTION
"An unnamed namespace will be unique within each translation unit.
Any declarations appearing in an unnamed namespace in a header will refer
to different entities in each translation unit, which may not be
consistent
with developer expectations."

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
// file.hpp
namespace // Violation
{
extern int x;
}

REPAIR
Do not define unnamed namespaces in header files

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

using-directives shall not be used [MISRA2008-7_3_4-3]


DESCRIPTION
"using-directives add additional scopes to the set of scopes searched
during
name lookup. All identifiers in these scopes become visible, increasing
the
possibility that the identifier found by the compiler does not meet
developer
expectations.
using-declarations or fully qualified names restricts the set of names
considered to only the name explicitly specified, and so are safer
options."

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using namespace NS1; // Violation
void f ()
{
++j1;
}

REPAIR
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using NS1::j1;
// OK
void f ()
{
++j1;
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-4

Multiple declarations for an identifier in the same namespace shall not straddle a usingdeclaration for that identifier [MISRA2008-7_3_5-3]
DESCRIPTION
"The set of identifiers introduced by a using-declaration does not include
any
declarations that may be added by a subsequent declaration in the
namespace.
Any subsequent declarations will not be found through the usingdeclaration,
which may not be consistent with developer expectations."

SINCE
v7.2

BENEFITS
Rule prevents unexpected behaviour.

EXAMPLE
namespace NS
{
void foo( unsigned short );
}
using NS::foo;
namespace NS
{
void foo( unsigned int );
}
void some()
{
foo( 0U );
}

// Violation

REPAIR
namespace NS
{
void foo( unsigned short );
}
namespace NS
{
void foo( unsigned int );
}

// OK

using NS::foo;
void some()
{
foo( 0U );
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-5

All usage of assembler shall be documented [MISRA2008-7_4_1-3]


DESCRIPTION
"All usage of assembler shall be documented. Assembly language code
is implementation-defined and therefore is not portable."

SINCE
v7.2

NOTES
Rule assumes that the usage of assembler is documented if there is
a comment in the same line as 'asm' instruction or in line directly
before 'asm' instruction.

BENEFITS
Rule improves readability of code.

EXAMPLE
// Violation in line with 'asm' instruction
void foo( void )
{
asm ( "NOP" );
}

REPAIR
void foo( void )
{
// OK - comment before 'asm' instruction
asm ( "NOP" );
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-4-1

Assembler instructions shall only be introduced using the asm declaration [MISRA20087_4_2-3]
DESCRIPTION
"The asm declaration is available to all C++ implementations, allowing
a consistent mechanism to be used. However, the parameters to asm are
still implementation-defined."
Rule reports a violation if '#pragma asm', '#pragma endasm' or an
assembler instruction that form is different than "asm" is found.

SINCE
v7.2

BENEFITS
Rule improves consistency of the code.

EXAMPLE
void foo()
{
#pragma asm
"NOP";
#pragma endasm
}

// Violation
// Violation

REPAIR
void foo()
{
asm ( "NOP" ); // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems

Chapter 6, Section 7, Rule 7-4-2

Assembly language shall be encapsulated and isolated [MISRA2008-7_4_3-3]


DESCRIPTION
"Where assembly language instructions are required it is recommended
that they be encapsulated and isolated in either (a) assembler functions,
(b) C functions or (c) macros."

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
/* compilable by cl.exe g++*/
void asmCall( ) {
/* Violation */
int g = 0;
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (
"mov %eax, 0x01\n\t"
"int $0x10"
);
#endif
}

REPAIR
void asmCall( ) {
/* OK */
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (

"mov %eax, 0x01\n\t"


"int $0x10"
);
#endif
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Misra Guidelines - Rule 3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-4-3

A function shall not return a reference or a pointer to an automatic variable (including


parameters), defined within the function [MISRA2008-7_5_1-3]
DESCRIPTION
"A function shall not return a reference or a pointer to an automatic
variable
(including parameters), defined within the function."

SINCE
v7.2

BENEFITS
"Automatic variables are destroyed at the end of the function call.
Returning a reference or pointer to such a variable allows it to be used
after its destruction, leading to undefined behaviour."

EXAMPLE
int* foo( ) {
int i;
return &i; // Violation
}
int& bar( ) {
int i;
return i; // Violation
}

REPAIR
int foo( ) {
int i = 0;
return i; // OK
}
int bar( ) {
int i = 0;

return i;

// OK

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-1

The address of an object with automatic storage shall not be assigned to another object that
may persist after the first object has ceased to exist [MISRA2008-7_5_2-3]
DESCRIPTION
"If the address of an automatic object is assigned to another automatic
object
of larger scope, or to a static object, or returned from a function then
the
object containing the address may exist beyond the time when the original
object
ceases to exist (and its address becomes invalid). For example:
int * foo( void ) {
int local_auto;
return (&local_auto);
}"

BENEFITS
Prevents loss of data

EXAMPLE
int* global;
int* foo() {
int iLocal;
static int* siLocal;
siLocal = &iLocal;
global = &iLocal;
return &iLocal;
}
void goo() {
int* piLocal;
{
int iiLocal;
piLocal = &iiLocal;
}
}

// Violation
// Violation
// Violation

// Violation

REPAIR
Do not assign local address of object to more global,
or static object or return from function.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 106
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 173
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-2

A function shall not return a reference or a pointer to a parameter that is passed by reference
or const reference [MISRA2008-7_5_3-3]
DESCRIPTION
"A function shall not return a reference or a pointer to a parameter that
is
passed by reference or const reference. It is implementation-defined
behaviour
whether the reference parameter is a temporary object or a reference to
the
parameter. If the implementation uses a local copy (temporary object),
this
will be destroyed when the function returns. Any attempt to use such an
object
after its destruction will lead to undefined behaviour."

SINCE
v7.2

BENEFITS
Rule prevents non-deterministic behaviour.

EXAMPLE
int* foo2 ( int& x )
{
return ( &x );
}

// Violation

REPAIR
Do not return a reference or a pointer to a parameter that is passed by
reference or const reference

REFERENCES

MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-3

Functions should not call themselves, either directly or indirectly [MISRA2008-7_5_4-4]


DESCRIPTION
Functions shall not call themselves, either directly or indirectly.

NOTES
This rule checks for direct recursion and simple indirect
recursion (up to three nested function calls).

BENEFITS
Prevents using recursive functions.

EXAMPLE
void foo( int l ) {
int x = l;
if (l > 0) {
foo( x - 1 );
}

/* Violation */

}
void foo3( int );
void foo4( int i ) {
if (i > 0) {
foo3( (int) i / 2 );
}
}

/* Violation */

void foo3( int i ) {


int x = i;
if (i > 0) {
foo4( x - i );
}
}

/* Violation */

REPAIR
void foo1( ) {
/* empty */
}

/* OK */

void foo2( );

/* OK */

void foo3( ) {
foo2( );
}

/* OK */

void foo7( int );


void foo4( int i ) {
foo7( i );
/* OK - cannot check complex indirect recursion */
}
void foo5( int i ) {
foo4( i );
/* OK - cannot check complex indirect recursion */
}
void foo6( int i ) {
foo5( i );
/* OK - cannot check complex indirect recursion */
}
void foo7( int i ) {
if (i > 0) {
foo6( i - 5 );
}
}

/* OK - cannot check complex indirect recursion */

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 70
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 119

4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-4
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1
6. HIS Source Code Metriken, version 1.3.1
Metrik "ap_cg_cycle"
7. ISO/DIS 26262
point 8.4.4

An init-declarator-list or a member-declarator-list shall consist of a single init-declarator or


member-declarator respectively [MISRA2008-8_0_1-3]
DESCRIPTION
"Each variable is to be declared in a separate declaration statement."
Determining the types of variables becomes confusing when pointers and
access
specifiers are used for multiple declarations in the same statement.
See also: FORMAT-29

BENEFITS
Rule prevents confusion and makes source code more readable.

EXAMPLE
void foo( )
{
int* a, b;
}

// Violation

REPAIR
void foo( )
{
int* a;
int b;
}

// OK
// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 39, 6 Style - 6.5 Pointers and References Rec. 26
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-0-1

Parameters in an overriding virtual function shall either use the same default arguments as
the function they override, or else shall not specify any default arguments [MISRA2008-8_3_13]
DESCRIPTION
"Virtual functions are dynamically bound, but default parameters are
statically
bound. That means that you may end up invoking a virtual function defined
in a derived class but using a default parameter value from a base class"
This rule detects cases when you redefine an inherited virtual function
with a different default parameter value.

NOTES
Rule does not check:
- functions with template parameters
- non-constant default parameter values
- default parameter values with complex expressions

BENEFITS
This rule prevents misinterpretation which value is passed as default.

EXAMPLE
class Base
{
public:
virtual void func(int i = 1);
};
class Derived: public Base
{
public:
virtual void func(int i = 0);
};

REPAIR

// Violation

class Base
{
public:
virtual void func1(int i = 1);
virtual void func2(int i = 1);
};
class Derived: public Base
{
public:
virtual void func1(int i);
virtual void func2(int i = 1);
};

// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 37
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Inheritance and ObjectOriented Design", Item 38
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 95
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Functions shall not be defined using the ellipsis notation [MISRA2008-8_4_1-3]


DESCRIPTION
Functions with variable numbers of arguments shall not be used.

BENEFITS
Prevents from a lot of potential problems with this feature.

EXAMPLE
void foo(int x, ...)
{
}

// Violation

REPAIR
Do not use functions with variable numbers of arguments.

REFERENCES
1. Misra Guidelines - Rule 69
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.1 Function Arguments - Rule 31
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 98
4. Scott Meyers and Martin Klaus, "Examining C++ Program Analyzers",
Dr. Dobbs' Journal, the February 1997,
Chapter: "Implementation", Item 23
http://www.aristeia.com/ddjpaper1_frames.html
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 108

6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-1

The identifiers used for the parameters in a re-declaration of a function shall be identical to
those in the declaration [MISRA2008-8_4_2-3]
DESCRIPTION
If identifiers are given for any of the parameters, then the identifiers
used
in the declaration and definition shall be identical.

BENEFITS
Rule improves readability and clarity of code.

EXAMPLE
void foo(int a, int b);
void foo(int x, int y ) {}

/* Violation */

REPAIR
void foo(int a, int b);
void foo(int a, int b) {}

/* OK */

/* Examples of correct code */


void foo1();
/* OK */
void foo2(int , int
); /* OK */
void foo2(int x, int y ) {}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 74
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-2

All exit paths from a function with non-void return type shall have an explicit return statement
with an expression [MISRA2008-8_4_3-3]
DESCRIPTION
"All exit paths from a function with non-void return type
shall have an explicit return statement with an expression.
This expression gives the value that the function returns.
The absence of a return with an expression leads to undefined
behaviour (and the compiler may not give an error)."

NOTES
"goto" statement is considered as exit point.
The rule does not track the flow. It assumes that each path could
be reachable independently from conditions in conditional statements.

BENEFITS
Rules prevents unpredictable function behaviour.

DRAWBACKS
Rule skips "while", "for", and "catch" sections.

EXAMPLE
int foo1(int x){ // Violation
// in second 'if' statement, 'return' statement is missing
if (x==0) {
if (x==0) {
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // Violation

// in 'switch' statement, 'default' statement is missing


switch(x){
case 0: return 1;
case 1: return 1;
case 2: return 1;
}
}
int foo3(int x){ // Violation
}
int foo4(int x){ // Violation - rule does not track the flow
if (x > 10) {
return 0;
}
if (x <= 10) {
return 1;
}
// unreachable path
}

REPAIR
int foo1(int x){ // OK
if (x==0) {
if (x==0) {
return 0;
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // OK
switch(x){
case 0: return 1;
case 1: return 1;
case 2: return 1;
default: return 1;
}
}

int foo3(int x){ // OK


return 0;
}
int foo4(int x){ // OK
if (x > 10) {
return 0;
} else {
return 1;
}
// unreachable path
}

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-3

All variables shall have a defined value before they are used [MISRA2008-8_5_1-3]
DESCRIPTION
"The intent of this rule is that all variables shall have been written to
before
they are read. This does not necessarily require initialisation at
declaration.
Ideally a static check should be performed for any automatic variables
which
might be used without having first been assigned a value"
See also: INIT-06, INIT-10, INIT-14, BD-PB-NOTINIT

NOTES
The rule assumes that local variable might be initialized
by passing its non-const pointer to an external function.

BENEFITS
Prevents reading from uninitialized variables.

EXAMPLE
void foo( ) {
int b;
b++;
}

// Violation

REPAIR
void foo( ) {
int b = 0;
b++;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve

Your Programs and Design", Third Edition, Addison-Wesley,


(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. Misra Guidelines - Rule 30
3. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9, rule 9.1
4. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 40
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 142
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-1

Braces shall be used to indicate and match the structure in the non-zero initialization of arrays
and structures [MISRA2008-8_5_2-3]
DESCRIPTION
"ISO C requires initializer lists for arrays, structures and union types
to be
enclosed in a single pair of braces (though the behaviour if this is not
done
is undefined). The rule given here goes further in requiring the use
of additional braces to indicate nested structures.
The zero initialization of arrays or structures shall only be applied
at the top level. The non-zero initialization of arrays or structures
requires an explicit initializer for each element."

NOTES
Rule checks only up to three-level nested bracket initialization.

EXCEPTIONS
"All the elements of arrays or structures can be initialized (to zero or
NULL)
by giving an explicit initializer for the first element only. If this
method
of initialization is chosen then the first element should be initialized
to zero (or NULL), and nested braces need not be used."

BENEFITS
"This forces the programmer to explicitly consider and demonstrate the
order
in which elements of complex data types are initialized"

EXAMPLE
int y[3][2] = { 1, 2, 3, 4, 5, 6 }; // Violation
struct S {
int i;

struct T {
int j;
}t;
} s = {1, 2}; // Violation

REPAIR
int y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // OK
struct S {
int i;
struct T {
int j;
}t;
} s = {1, { 2 }}; // OK

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Misra Guidelines - Rule 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 144
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-2

In an enumerator list, the = construct shall not be used to explicitly initialize members other
than the first, unless all items are explicitly initialized [MISRA2008-8_5_3-3]
DESCRIPTION
"In enumerator list, the '=' construct shall not be used
to explicitly initialize members other than the first,
unless all items are explicitly initialized."

BENEFITS
Helps avoid errors and confusion.

EXAMPLE
enum TEST { /* Violation */
X = 1,
Y,
Z = 3,
};
enum TEST2 { /* Violation */
X2,
Y2 = 2,
Z2,
};
enum TEST3 { /* Violation */
X3,
Y3,
Z3 = 3,
};

REPAIR
enum TEST { /* OK */
X,
Y,
Z,
};

enum TEST2 { /* OK */
X2 = 1,
Y2,
Z2,
};
enum TEST3 { /* OK */
X3 = 1,
Y3 = 2,
Z3 = 3,
};

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Origin: Misra Guidelines - Rule 32
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-3

const member functions shall not return non-const pointers or references to class-data
[MISRA2008-9_3_1-3]
DESCRIPTION
"When an object is declared with const class type, only const member
functions
can be invoked on that object. The common expectation of const member
functions
is that the state of the object may not be modified when invoking the
functions. However, returning a non-const pointer or reference to classdata
from a const function allows a modification to the conceptual state of an
object."
See also: CODSTA-CPP-06, OOP-12, OOP-36

NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.

BENEFITS
Rule prevents exposing internal state of the object to clients, so they
won't
uncontrollably modify the state of the object. Enforces data encapsulation
that
is a cornerstone of Object Oriented programming. Improves code
maintainability.
Helps const functions act const.

EXAMPLE
class Test
{
public:
Test(int & p) : _i(p)

{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1() const
{
return &_i; // Violation
}
protected:
int& GetI2() const
{
return _i; // Violation
}
int * GetI3() const
{
return _k; // Violation
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
GetI2() = 0; // Modification of possibly-const object
*(GetI3()) = 0; // Modification of possibly-const object
}
private:
int z;
};
void bar()
{
const Child c;
*(c.GetI1()) = 0; // Modification of possibly-const object
}

REPAIR
class Test

{
public:
Test(int & p) : _i(p)
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1() const
{
return &_i; // OK
}
protected:
const int& GetI2() const
{
return _i; // OK
}
const int * GetI3() const
{
return _k; // OK
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
// GetI2() = 0; // Not compilable - can't modify const object
// *(GetI3()) = 0; // Not compilable - can't modify const
object
}
private:
int z;
};
void bar()
{
const Child c;
// *(c.GetI1()) = 0; // Not compilable - can't modify const object
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 9-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Protected member functions shall not return non-const handles to class-data [MISRA20089_3_2_a-3]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a protected member function returns nonconst
reference or pointer to private class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-36

NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.

BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.

EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
int* GetI1()
{

return &_i; // Violation


}
int& GetI2()
{
return _i; // Violation
}
int * GetI3()
{
return _k; // Violation
}
private:
int _i;
int * _k;
};
class Child: public Test
{
public:
void foo()
{
*(GetI1()) = 0; // Encapsulation broken - possible to change
private class data
GetI2() = 0; // Encapsulation broken - possible to change
private class data
*(GetI3()) = 0; // Encapsulation broken - possible to change
private class data
}
};

REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()

{
return _i; // OK
}
const int * GetI3()
{
return _k; // OK
}
private:
int _i;
int * _k;
};
class Child: public Test
{
public:
void foo()
{
// *(GetI1()) = 0; // Not compilable - not possible to change
private class data
// GetI2() = 0; // Not compilable - not possible to change
private class data
// *(GetI3()) = 0; // Not compilable - not possible to change
private class data
}
};

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,

(C) 2005 Pearson Education, Inc.


Chapter: "Class Design and Inheritance", Rule 42
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 9, Rule 9-3-2
6. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Public member functions shall not return non-const handles to class-data [MISRA20089_3_2_b-3]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a public member function returns non-const
reference or pointer to private/protected class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-12

NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.

BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.

EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1()
{
return &_i; // Violation

}
int& GetI2()
{
return _i; // Violation
}
int * GetI3()
{
return _k; // Violation
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
*(t.GetI1()) = 0; // Encapsulation broken - possible to change private
class data
t.GetI2() = 0; // Encapsulation broken - possible to change private
class data
*(t.GetI3()) = 0; // Encapsulation broken - possible to change private
class data
}

REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()
{
return _i; // OK
}
const int * GetI3()
{

return _k; // OK
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
// *(t.GetI1()) = 0; // Not compilable - not possible to change private
class data
// t.GetI2() = 0; // Not compilable - not possible to change private
class data
// *(t.GetI3()) = 0; // Not compilable - not possible to change private
class data
}

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.8 Member Function Return Types - Rule 29
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 9, Rule 9-3-2

If a member function can be made static then it shall be made static, otherwise if it can be
made const then it shall be made const [MISRA2008-9_3_3-3]
DESCRIPTION
"Declaring a member function static or const limits its access
to the non-static data members."
See also: CODSTA-CPP-54

SINCE
v7.2

BENEFITS
Rule prevents unintentional modification of the data.

EXAMPLE
class A
{
public:
int foo1 ()
{
return m_s;
}
int foo2 ()
{
return m_i;
}
private:
int m_i;
static int m_s;
};

REPAIR
class A
{

// Violation - can be static

// Violation - can be const

public:
static int foo1 ()
{
return m_s;
}
int foo2 () const
{
return m_i;
}

// OK

// OK

private:
int m_i;
static int m_s;
};

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Unions shall not be used [MISRA2008-9_5_1-3]


DESCRIPTION
"Even when memory is being reused for related purposes,
there is still a risk that the data may be misinterpreted.
Therefore, this rule prohibits the use of unions for any purpose."

Note:
Rule reports a violation message on each union's declaration.

BENEFITS
Rule prevents undefined behaviour and erroneous code.

EXAMPLE
union U {
/* Violation */
int _i;
char _buf[ sizeof( int ) ];
};

REPAIR
Do not use union.

REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 97
3. Origin: Misra Guidelines - Rule 109

4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.20 Unions and Bit Fields, AV Rule 153
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 9, Rule 9-5-1

Bit-fields shall be either bool type or an explicitly unsigned or signed integral type
[MISRA2008-9_6_2-3]
DESCRIPTION
"Bit-fields shall be either bool type or an explicitly unsigned or signed
integral type Using int is implementation-defined because bit-fields of
type
int can be either signed or unsigned. The use of wchar_t as a bit-field
type
is prohibited as ISO/IEC 14882:2003 does not explicitly define the
underlying
representation as signed or unsigned."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
/* Examples of incorrect code */
struct S
{
char c : 2;
// Violation
short f : 3;
// Violation
int : 0;
// Violation
};

REPAIR
/* Examples of correct code */
struct S
{
unsigned char c : 2;
// OK
signed short f : 3;
// OK
unsigned int : 0;
// OK

bool b : 4

// OK

};

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-2

Bit-fields shall not have enum type [MISRA2008-9_6_3-3]


DESCRIPTION
"The use of enum as a bit-field type is prohibited as ISO/IEC 14882:2003
does
not explicitly define the underlying representation as signed or unsigned.
It is therefore not possible to determine the exact number of bits
required
to represent all values in the enumeration."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
enum Color{RED, BLUE, BLACK};
struct S
{
Color n : 2;
/* ... */
};

// Violation

REPAIR
struct S
{
unsigned int n: 2 // OK
/* ... */
};

REFERENCES

MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-3

Named bit-fields with signed integer type shall have a length of more than one bit
[MISRA2008-9_6_4-3]
DESCRIPTION
"Named bit-fields with signed integer type shall have a length of more
than one
bit. The values which may be represented by a bit-field of length one may
not
meet developer expectations. Anonymous signed bit-fields of any length are
allowed."

SINCE
v7.2

NOTES
Rule reports violations only for explicitly signed types

BENEFITS
Rule prevents the potential pitfalls and erroneous code.

EXAMPLE
struct MyStruct
{
signed int si01 : 1;
signed int si02 : 1;
};

// Violation
// Violation

REPAIR
struct MyStruct
{
signed int si01 : 2;
signed int : 1;
};

// OK
// OK

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-4

MRM
Memory and Resource Management
RULES
Do not allocate resources in function argument list because the order of
evaluation of a function's parameters is undefined [MRM-01-1]
Do not allocate more than one resource in a single statement [MRM-02-3]
All classes should contain the assignment operator or appropriate comment
[MRM-04-3]
All classes should contain the copy constructor or appropriate comment
[MRM-05-3]
Use the same form in corresponding calls to new/malloc and delete/free
[MRM-06-1]
Don't memcpy or memcmp non-PODs [MRM-07-3]
Do not invoke malloc/realloc for objects having constructors [MRM-08-1]
Always assign a new value to an expression that points to deallocated
memory [MRM-09-3]
Always assign a new value to global or member variable that points to
deallocated memory [MRM-10-3]
Always assign a new value to parameter or local variable that points to
deallocated memory [MRM-11-3]
Adhere to convention when writing new and delete [MRM-12-3]
Adhere to convention when writing new [MRM-13-3]
If a class defines any overload of operator new, it should provide
overloads of all three of plain, in-place, and non-throwing operator new
[MRM-14-3]
If a class defines any overload of operator new[], it should provide
overloads of all three of plain, in-place, and non-throwing operator new[]
[MRM-15-3]
If a class defines any overload of operator delete, it should provide
overloads of all three of plain, in-place, and non-throwing operator
delete [MRM-16-3]
If a class defines any overload of operator delete[], it should provide
overloads of all three of plain, in-place, and non-throwing operator
delete[] [MRM-17-3]
Do not allocate memory and expect that someone else will deallocate it
later [MRM-18-3]
Do not allocate memory and expect that someone else will deallocate it
later [MRM-19-3]
Do not allocate memory and expect that someone else will deallocate it
later [MRM-20-3]
Use objects to manage resources [MRM-21-3]
Use objects to manage resources [MRM-22-3]
Never return a dereferenced local pointer initialized by new in this
function scope [MRM-23-2]

Never return a reference to a local object [MRM-24-1]


Store newed objects in smart pointers in standalone statements [MRM-25-3]
Write operator delete if you write operator new [MRM-26-3]
Write operator delete[] if you write operator new[] [MRM-27-3]
Always provide new and delete together [MRM-28-3]
Always provide new[] and delete[] together [MRM-29-3]
Use allocation by declaration rather than by new or malloc [MRM-30-3]
Freed memory shouldn't be accessed under any circumstances. Destructor
should not be called manually [MRM-31-3]
Avoid hiding the global new [MRM-32-1]
Call delete on pointer members in destructors [MRM-33-2]
Check the return value of new [MRM-34-3]
Never provide brackets ([]) for delete when deallocating non-arrays [MRM35-3]
Always provide empty brackets ([]) for delete when deallocating arrays
[MRM-36-3]
Declare an assignment operator for classes with dynamically allocated
memory [MRM-37-1]
Declare a copy constructor for classes with dynamically allocated memory
[MRM-38-1]
Provide error handling for file opening errors right next to the call to
fopen [MRM-39-2]
Copy and destroy consistently [MRM-40-3]
A copy constructor shall copy all data members and bases [MRM-41-2]
Call fclose() on pointer member in destructor if the pointer was used to
open a file [MRM-42-2]
The assignment operator must assign all members, including those in base
classes [MRM-43-2]
Avoid passing address of auto variable into caller space [MRM-44-2]
Do not use sizeof operator on pointer type to specify the size of the
memory to be allocated via 'malloc', 'calloc' or 'realloc' function [MRM45-3]
Do not use calloc, malloc, realloc and free functions [MRM-46-3]
Classes containing at least one non-static member variable should declare
the assignment operator or contain appropriate comment [MRM-47-3]
Classes containing at least one non-static member variable should declare
the copy constructor or contain appropriate comment [MRM-48-3]

Do not allocate resources in function argument list because the order of evaluation of a
function's parameters is undefined [MRM-01-1]
DESCRIPTION
"Make sure that all resources are owned by objects. Perform every explicit
resource allocation (e.g., new) in its own statement that immediately
gives
the allocated resource to a manager object (e.g., shared_ptr); otherwise,
you
can leak resources because the order of evaluation of a function's
parameters
is undefined."
Rule disallows resource allocation in argument list of function.
See also: MRM-02

SINCE
v7.0

BENEFITS
"Such code is unsafe. The C++ standard gives compilers great leeway to
reorder
the two expressions building the function's two arguments. In particular,
the
compiler can interleave execution of the two expressions: Memory
allocation
(by calling operator new) could be done first for both object, followed by
attempts to call the two constructors. That very nicely sets things up for
a leak because if one of the constructor calls throws an exception, then
the
other object's memory will never be released."

EXAMPLE
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;

void Fun2( shared_ptr<int> p1, shared_ptr<int> p2 );


void goo( ) {
Fun2( shared_ptr<int>( new int ), shared_ptr<int>( new int ) ); //
Violation
}

REPAIR
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
void Fun2( shared_ptr<int> p1, shared_ptr<int> p2 );
void goo( ) {
shared_ptr<int> p1( new int );
shared_ptr<int> p2( new int );
Fun2( p1, p2 );
// OK
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 13
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not allocate more than one resource in a single statement [MRM-02-3]


DESCRIPTION
"Make sure that all resources are owned by objects. Perform every explicit
resource allocation (e.g., new) in its own statement that immediately
gives
the allocated resource to a manager object (e.g., shared_ptr).
Follow the advice to perform every explicit resource allocation (e.g.,
new)
in its own code statement that immediately gives the resource to an owning
object (e.g., shared_ptr)."
Rule disallows allocating more than one resource in a single statement.
See also: MRM-01

SINCE
v7.0

BENEFITS
"Memory allocation (by calling operator new) could be done first for both
objects, followed by attempts to call the two constructors. That very
nicely
sets things up for a leak because if one of the constructor calls throws
an
exception, then the other object's memory will never be released."

EXAMPLE
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
class Sport{};
void smartPointer( ) {
shared_ptr<Sport> sport1( new Sport ), sport2( new Sport );
Violation

//

REPAIR
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
class Sport{};
void smartPointer( ) {
shared_ptr<Sport> sport1( new Sport );
shared_ptr<Sport> sport2( new Sport );
}

// OK
// OK

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 13

All classes should contain the assignment operator or appropriate comment [MRM-04-3]
DESCRIPTION
"Ensure that your class provides sensible copying, or none at all.
The choices are:
- If copying doesn't make sense for your type, disable copy assignment by
declaring assignment operator as private unimplemented function
- If copy assignment is warranted, but correct copying behaviour differs
from
what the compiler-generated version will do, then write the function
yourself
and make it non-private
- If copying make sense and the default behaviour is correct, use the
compiler
generated version with an explicit comment, so that readers of your code
will know that you didn't miss one of the other two options by accident"
Comment should contain string "assignment operator" which is checked
insensitive.
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-05, MRM-37,
MRM-40,
MRM-47, OOP-27, OOP-30, OOP-34

BENEFITS
Prevents using compiler-generated assignment operator by accident.

EXAMPLE
class A
{
};

// Violation

class B
{
};

// Violation

class C : public B
{
};
class D

// Violation

// Violation

{
};

REPAIR
class A
// OK
{
public:
A& operator=(const A& a)
{
/* ... */
return *this;
}
};
class B
// OK
{
private:
// copying disabled
B& operator=(const B& b);
};
class C : public B
// OK
{
// copying disabled
// private assignment operator in a base class
};
class D
// OK
{
// class uses compiler-generated assignment operator
};

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53

All classes should contain the copy constructor or appropriate comment [MRM-05-3]
DESCRIPTION
"Ensure that your class provides sensible copying, or none at all.
The choices are:
- If copying doesn't make sense for your type, disable copy construction
by
declaring copy constructor as private unimplemented function
- If copy construction is warranted, but correct copying behaviour differs
from
what the compiler-generated version will do, then write the function
yourself
and make it non-private
- If copying make sense and the default behaviour is correct, use the
compiler
generated version with an explicit comment, so that readers of your code
will know that you didn't miss one of the other two options by accident"
Comment should contain string "copy constructor" which is checked
insensitive.
See also: CODSTA-CPP-19, MRM-04, MRM-38, MRM-40, MRM-48, OOP-27, OOP-30,
OOP-34

BENEFITS
Prevents using compiler-generated copy constructor by accident.

EXAMPLE
class A
{
};

// Violation

class B
{
};

// Violation

class C : public B
{
};
class D

// Violation

// Violation

{
};

REPAIR
class A
{
public:
A(const A& a){}
};

// OK

class B
{
private:
// copying disabled
B(const B& b);
};

// OK

class C : public B
// OK
{
// copying disabled
// private copy constructor in a base class
};
class D
// OK
{
// class uses compiler-generated copy constructor
};

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53

Use the same form in corresponding calls to new/malloc and delete/free [MRM-06-1]
DESCRIPTION
Use the same form in corresponding calls to new/malloc and delete/free.
This rule checks calls to new, delete, malloc, and free to make sure that
they
use the same form; it reports a violation if you call new and free( ).
If you do not use the same form in corresponding calls to to new, delete,
malloc, and free, an incorrect number of destructors may be called.
See also: MRM-08, MRM-09, MRM-10, MRM-11, MRM-30

SINCE
v7.0

NOTES
Rule will trigger if the same variable is allocated memory in two
different
incompatible ways in the same function.

BENEFITS
Prevents using different kinds of 'new/malloc' and 'delete/free' calls.

EXAMPLE
#include <stdlib.h>
void foo( ) {
char* ptr1 = (char*) malloc( 19 );
char* ptr2 = new char[ 10 ];
delete ptr1;
// Violation
free( ptr2 );
// Violation
}

REPAIR
#include <stdlib.h>

void foo( ) {
char* ptr1 = (char*) malloc( 19 );
char* ptr2 = new char[ 10 ];
free( ptr1 );
// OK
delete[] ptr2;
// OK
}

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Don't memcpy or memcmp non-PODs [MRM-07-3]


DESCRIPTION
"Don't use memcpy or memcmp to copy or compare anything more structured
than raw
memory. Memcpy and memcmp violate the type system. Using memcpy is a
serious
violation of information hiding, and often leads to memory and resource
leaks,
crashes, or undefined behavior."

BENEFITS
Rule improves safety and reliability of code.

EXAMPLE
#include <memory.h>
class A {
int *p;
};
class B {
int *p;
};
void foo( ) {
A p1;
B p2;
memcpy( &p1, &p2, sizeof( p1 ) );
}

// Violation

REPAIR
Memcpy and memcmp should not be used.

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-

Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 96
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not invoke malloc/realloc for objects having constructors [MRM-08-1]


DESCRIPTION
Do not invoke malloc/realloc for objects having constructors.
See also: MRM-06, MRM-09, MRM-10, MRM-11, MRM-30

SINCE
v7.0

BENEFITS
Rule ensures that all member variables are initialized.

EXAMPLE
#include <stdlib.h>
class A {
public:
A( );
};
void foo( ) {
A* a = (A*) malloc( sizeof( A ) );
a
= (A*) malloc( sizeof( A ) );
}

REPAIR
#include <stdlib.h>
class A {
public:
A( );
};
void foo( ) {
A* a = new A( );
a
= new A( );
}

// OK
// OK

// Violation
// Violation

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Always assign a new value to an expression that points to deallocated memory [MRM-09-3]
DESCRIPTION
All pointers should be set to either 0 or to a valid address immediately
after delete statement.
The rule reports a violation if directly after delete used on an
expression
there is no assignment to this expression.
The rule does not report violation only if in assignment is used exactly
the same expression as in delete statement.
See also: MRM-10, MRM-11, MRM-31

NOTES
The rule checks only complex expressions. Simple parameters and variables
are checked by rules MRM-10 and MRM-11.

EXCEPTIONS
The rule does not report violation if an expression that contains
non-static member variables and does not contain global variables
is used as operand of delete in destructor.

BENEFITS
Rule prevents accessing a pointer or a reference to a deleted object.

EXAMPLE
struct S {
int* p;
int* q;
};
void foo(S* s){
s->p = new int;
s->q = new int(5);
//....
delete s->p;// Violation - set deleted pointer in next expression

delete
s->p =
s->q =
//...
delete

s->q;// Violation - set deleted pointer in next expression


0;
new int(10);
s->q;// Violation - set deleted pointer in next expression

struct S {
int* p;
int* q;
};
void foo(S* s){
s->p = new int;
s->q = new int(5);
//....
delete s->p;// OK
s->p = 0;
delete s->q;// OK
s->q = new int(10);
//...
delete s->q;// OK
s->q = 0;
}

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 59

Always assign a new value to global or member variable that points to deallocated memory
[MRM-10-3]
DESCRIPTION
All pointers should be set to either 0 or to a valid address immediately
after delete statement.
The rule reports a violation if directly after delete used on a global
or member variable there is no assignment to this variable.
See also: MRM-09, MRM-11, MRM-31

NOTES
Violation is not reported if delete is used on a non-static member
variable in destructor.
Some violations can be not reported on MSVC compiler
if an assignment is used before delete statement inside macro.

BENEFITS
Rule prevents accessing a pointer or a reference to a deleted object.

EXAMPLE
int* p;
int* q;
void foo(){
p = new int;
q = new int(5);
//....
delete p;// Violation - set deleted pointer in next expression
delete q;// Violation - set deleted pointer in next expression
p = 0;
q = new int(10);
//...
delete q;
// Violation - set deleted pointer to 0
}
class A {
public:
A();

~A();
void clear();
int* ptr;
};
A::A(){
ptr = new int(10);
}
void A::clear(){
delete ptr;
}

// Violation - set deleted pointer to 0

REPAIR
int* p;
int* q;
void foo(){
p = new int;
q = new int(5);
//....
delete p;// OK
p = 0;
delete q;// OK
q = new int(10);
//...
delete q;// OK
q = 0;
}
class A {
public:
A();
~A();
void clear();
int* ptr;
};
A::A(){
ptr = new int(10);
}
A::~A(){

delete ptr;

// OK - exception

}
void A::clear(){
delete ptr;
ptr = 0;
}

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 59

Always assign a new value to parameter or local variable that points to deallocated memory
[MRM-11-3]
DESCRIPTION
All pointers should be set to either 0 or to a valid address immediately
after delete statement.
The rule reports a violation if directly after delete used on
local variable there is no assignment to this variable.
See also: MRM-09, MRM-10, MRM-31

NOTES
Violation is not reported if delete is a last statement in function
(ignoring other delete and return statements).
Some violations can be not reported on MSVC compiler
if an assignment is used before delete statement inside macro.

BENEFITS
Rule prevents accessing a pointer or a reference to a deleted object.

EXAMPLE
void foo(int* p){
p = new int;
int* q = new int(5);
//....
delete p;// Violation - set deleted pointer in next expression
delete q;// Violation - set deleted pointer in next expression
p = 0;
q = new int(10);
//...
return;
}

REPAIR
void foo(int* p){
p = new int;

int* q = new int(5);


//....
delete p;// OK
p = 0;
delete q;// OK
q = new int(10);
//...
delete q;// OK
return;
}

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 59

Adhere to convention when writing new and delete [MRM-12-3]


DESCRIPTION
"For operator delete, things are simpler. About all you need to remember
is
that C++ guarantees it's always safe to delete the null pointer, so you
need
to honor that guarantee.
The member version of this function is simple, too, except you've got to
be
sure to check the size of what's being deleted. Assuming your classspecific
operator new forwards requests of the "wrong" size to ::operator new,
you've
got to forward "wrongly sized" deletion requests to ::operator delete."
See also: MRM-13

SINCE
v7.0

BENEFITS
Insures your 'delete' function(s) behavior that is consistent with the
default operator delete.

EXAMPLE
#include <iostream>
#include <cstddef>
class Base {
public:
static void* operator new( size_t size ) throw( std::bad_alloc );
static void operator delete( void* rawMemory, size_t size ) throw( );
};
void Base::operator delete( void* rawMemory, size_t size ) throw( ) {
Violation
if (rawMemory == 0) return;

//

// deallocate the memory pointed to by rawMemory;


return;
}
void operator delete( void* rawMemory ) throw( ) {
Violation
// deallocate the memory pointed to by rawMemory;
}

//

REPAIR
#include <iostream>
#include <cstddef>
class Base {
public:
static void* operator new( size_t size ) throw( std::bad_alloc );
static void operator delete( void* rawMemory, size_t size ) throw( );
};

void Base::operator delete( void* rawMemory, size_t size ) throw( ) {


OK
if (rawMemory == 0) return;
if (size != sizeof( Base )) {
::operator delete( rawMemory );
return;
}
// deallocate the memory pointed to by rawMemory;
return;
}

//

void operator delete( void* rawMemory ) throw( ) {


OK
if (rawMemory == 0) return;

//

// deallocate the memory pointed to by rawMemory;


}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve

Your Programs and Design", Third Edition, Addison-Wesley,


(C) 2005 Pearson Education, Inc., Chapter 8, Item 51
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Adhere to convention when writing new [MRM-13-3]


DESCRIPTION
When you write operator new, this rule checks to make sure that you are
consistent with the default new. "In practical terms, this means having
the
right return value, calling an error-handling function when insufficient
memory is available, and being prepared to cope with requests for no
memory.
Curiously, C++ requires that operator new return a legitimate pointer even
when zero bytes are requested. That being the case, pseudocode for a
non-member operator new looks like this:
void * operator new(std::size_t size) throw(std::bad_alloc)
{ // your operator new might
using namespace std; // take additional params
if (size == 0) { // handle 0-byte requests
size = 1;
// by treating them as
}
// 1-byte requests
/* ... */
}
(...) given an operator new for a class X, the behavior of that function
is
typically tuned for objects of size sizeof(X)nothing larger and nothing
smaller. Because of inheritance, however, it is possible that the operator
new
in a base class will be called to allocate memory for an object of a
derived
class:
class Base {
public:
static void * operator new(std::size_t size) throw(std::bad_alloc);
...
};
class Derived: public Base // Derived doesn't declare
{ ... }; // operator new

Derived *p = new Derived; // calls Base::operator new!


If Base's class-specific operator new wasn't designed to cope with this
and
chances are that it wasn't the best way for it to handle the situation
is to
slough off calls requesting the "wrong" amount of memory to the standard
operator new, like this:
void * Base::operator new(std::size_t size) throw(std::bad_alloc)
{
if (size != sizeof(Base))
// if size is "wrong,"
return ::operator new(size); // have standard operator
// new handle the request
...
}
See also: MRM-12

BENEFITS
If you do not adhere to convention when you write new, you may cause
confusing inconsistencies for users of your new and delete operators.

EXAMPLE
#include <stdio.h>
class A {
public:
A( );
void* operator new(size_t size) {
// Violation
// missing ifs checking proper memory allocation
return (int *)(new int);
};
};

REPAIR
#include <stdio.h>
class A {
public:
A( );

void* operator new(size_t size) {


if (size !=sizeof(A) ) {
return ::operator new(size);
}

// OK

if (size==0) {
size=1;
}
return (int *)(new int);
};
};

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 8, Item 51
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 8
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

If a class defines any overload of operator new, it should provide overloads of all three of
plain, in-place, and non-throwing operator new [MRM-14-3]
DESCRIPTION
"If a class defines any overload of operator new, it should provide
overloads of all three of plain, in-place, and non-throwing operator new.
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-17, MRM-16, MRM-15, MRM-32

BENEFITS
This rule prevents hiding other overloaded new operators.

EXAMPLE
#include <new>
class MyClass
// Violation - in-place new only
{
public:
static void * operator new( size_t count, void * object );
};

REPAIR
#include <new>
class MyClass
// OK - all three operators overloaded
{
public:
static void * operator new( size_t count );
static void * operator new( size_t count, std::nothrow_t nt ) throw( );
static void * operator new( size_t count, void * object );
};

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,

(C) 2005 Pearson Education, Inc.


Chapter: "Class Design and Inheritance", Rule 46

If a class defines any overload of operator new[], it should provide overloads of all three of
plain, in-place, and non-throwing operator new[] [MRM-15-3]
DESCRIPTION
"If a class defines any overload of operator new[], it should provide
overloads of all three of plain, in-place, and non-throwing operator
new[].
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-17, MRM-16, MRM-14

BENEFITS
This rule prevents hiding other overloaded new[] operators.

EXAMPLE
#include <new>
class MyClass
// Violation - in-place new only
{
public:
static void * operator new[]( size_t count, void * object );
};

REPAIR
#include <new>
class MyClass
// OK - all three operators overloaded
{
public:
static void * operator new[]( size_t count );
static void * operator new[]( size_t count, std::nothrow_t nt ) throw(
);
static void * operator new[]( size_t count, void * object );
};

REFERENCES

Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,


(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 46

If a class defines any overload of operator delete, it should provide overloads of all three of
plain, in-place, and non-throwing operator delete [MRM-16-3]
DESCRIPTION
"If a class defines any overload of operator delete,
it should provide overloads of all three of plain, in-place,
and non-throwing operator delete.
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-17, MRM-15, MRM-14

BENEFITS
This rule prevents hiding other overloaded delete operators.

EXAMPLE
#include <new>
class MyClass
// Violation
{
public:
static void operator delete(void* _Ptr) throw( );
};

REPAIR
#include <new>
class MyClass1
// OK
{
public:
static void operator delete(void* _Ptr) throw( );
static void operator delete(void* _Ptr, const std::nothrow_t&) throw( );
static void operator delete(void*, void*) throw( );
};

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 46

If a class defines any overload of operator delete[], it should provide overloads of all three of
plain, in-place, and non-throwing operator delete[] [MRM-17-3]
DESCRIPTION
"If a class defines any overload of operator delete[],
it should provide overloads of all three of plain, in-place,
and non-throwing operator delete[].
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-16, MRM-15, MRM-14

BENEFITS
This rule prevents hiding other overloaded delete[] operators.

EXAMPLE
#include <new>
class MyClass
// Violation
{
public:
static void operator delete[](void* _Ptr) throw( );
};

REPAIR
#include <new>
class MyClass1
// OK
{
public:
static void operator delete[](void* _Ptr) throw( );
static void operator delete[](void* _Ptr, const std::nothrow_t&) throw( );
static void operator delete[](void*, void*) throw( );
};

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 46

Do not allocate memory and expect that someone else will deallocate it later [MRM-18-3]
DESCRIPTION
If local memory in global function is allocated via new it
should be deleted in this function.
See also: MRM-20, MRM-19

BENEFITS
This rule helps to ensure that all allocated memory
is being cleaned up properly.

EXAMPLE
void foo( ) {
int *var = new int( );
}

// Violation

REPAIR
void foo( ) {
int *var = new int( );
delete var;
}

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 58

Do not allocate memory and expect that someone else will deallocate it later [MRM-19-3]
DESCRIPTION
If local memory in class is allocated via new it should be deallocated
in destructor via delete.
See also: MRM-20, MRM-18

BENEFITS
This rule helps to ensure that all allocated memory is being cleaned
up properly.

EXAMPLE
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
~A( ) {}
};

// Violation

REPAIR
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
~A( ) {
delete var;
}
};

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 58

Do not allocate memory and expect that someone else will deallocate it later [MRM-20-3]
DESCRIPTION
If local memory in class is allocated via new a destructor
should be defined as well.
See also: MRM-19, MRM-18

BENEFITS
This rule helps to ensure that all allocated memory is being cleaned
up properly.

EXAMPLE
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
};

// Violation

REPAIR
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
~A( ) {
delete var;
}
};

REFERENCES

// OK

Ellemtel Coding Standards


http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 58

Use objects to manage resources [MRM-21-3]


DESCRIPTION
"Both auto_ptr and TR1::shared_ptr use delete in their destructors,
not delete []. That means that using auto_ptr or tr1::shared_ptr with
dynamically allocated arrays is a bad idea (...). If you still think it
would
be nice to have auto_ptr- and tr1::shared_ptr-like classes for arrays,
look
to Boost. There you'll be pleased to find the boost::scoped_array
and boost::shared_array classes that offer the behavior you're looking
for.
This Item's guidance to use objects to manage resources suggests that if
you're
releasing resources manually (e.g., using delete other than in a
resource-managing class), you're doing something wrong."
See also: MRM-22

SINCE
v7.0

BENEFITS
Rule prevents resource leaks by encouraging usage of RAII objects that
acquire
resources in their constructors and release them in their destructors.

EXAMPLE
#include <boost/scoped_array.hpp>
#include <memory>
void myFunction () {
std::auto_ptr<int> pInv(new int[100]);
}

REPAIR

// Violation

#include <boost/scoped_array.hpp>
#include <memory>
void myFunction()
{
boost::scoped_array<int> pFeatureButtons( new int[22] );
}

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 13

// OK

Use objects to manage resources [MRM-22-3]


DESCRIPTION
"To make sure that the resource returned by function is always released,
we
need to put that resource inside an object whose destructor will
automatically
release the resource when control leaves scope. In fact, that's half the
idea
behind this Item: by putting resources inside objects, we can rely on
C++'s
automatic destructor invocation to make sure that the resources are
released.
In fact, the idea of using objects to manage resources is often called
Resource Acquisition Is Initialization (RAII), because it's so common to
acquire a resource and initialize a resource-managing object in the same
statement. Sometimes acquired resources are assigned to resource-managing
objects instead of initializing them, but either way, every resource is
immediately turned over to a resource-managing object at the time the
resource
is acquired. i.e: auto_ptr, shared_ptr."
See also: MRM-21

SINCE
v7.0

BENEFITS
Rule prevents resources leaks.

EXAMPLE
#include <boost/tr1/memory.hpp>
using namespace std;
using namespace tr1;
class Investment {};
Investment* createInvestment()

{
Investment * ptr = new Investment();
return ptr;
};
void myFunction()
{
Investment *pInv = createInvestment();
}

// Violation

REPAIR
#include <boost/tr1/memory.hpp>
using namespace std;
using namespace tr1;
class Investment {};
Investment* createInvestment()
{
Investment * ptr = new Investment();
return ptr;
};
void myFunction()
{
std::auto_ptr<Investment> pInv(createInvestment()); // OK
shared_ptr<Investment> pInv2(createInvestment());
// OK
}

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 13

Never return a dereferenced local pointer initialized by new in this function scope [MRM-23-2]
DESCRIPTION
Never return a reference to a local object or a dereferenced pointer
initialized by new within the function. This rule detects when you
return a reference to a local object or dereferenced pointer.
See also: MRM-24

BENEFITS
Returning a reference to a local object or a dereferenced pointer
initialized
by new within the function may cause a memory leak.

EXAMPLE
class A {
public:
A(int xval, int yval) : _x(xval), _y(yval) {}
friend A& operator+(const A& p1, const A& p2);
private:
int _x, _y;
};
A& operator+(const A& p1, const A& p2) {
A *result = new A(p1._x + p2._x, p1._y + p2._y);
return *result;
// Violation
}

REPAIR
class A {
public:
A(int xval, int yval) : _x(xval), _y(yval) {}
friend A operator+(const A& p1, const A& p2);
private:
int _x, _y;
};
A operator+(const A& p1, const A& p2) {

A result = A(p1._x + p2._x, p1._y + p2._y);


return result;

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 31
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 112
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Never return a reference to a local object [MRM-24-1]


DESCRIPTION
"A function must never return a pointer or reference to a local variable.
If a function returns a reference or a pointer to a local variable, the
memory
to which it refers will already have been deallocated, when this reference
or
pointer is used. The compiler may or may not give a warning for this."
See also: MRM-23, PB-40, MISRA2004-17_6

BENEFITS
Returning a reference to a local object or a dereferenced pointer
initialized
by new within the function may cause a memory leak.

EXAMPLE
int* foo(
int i;
return
}
int& bar(
int i;
return
}

) {
&i; // Violation
) {
i;

// Violation

REPAIR
int foo( ) {
int i = 0;
return i; // OK
}
int bar( ) {
int i = 0;
return i; // OK
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#9.4
From: 9 Functions - 9.4 Return Types and Values - Rule 34
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Implementation", Item 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 111
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Store newed objects in smart pointers in standalone statements [MRM-25-3]


DESCRIPTION
"Store newed objects in smart pointers in standalone statements."

SINCE
v7.0

BENEFITS
Prevention from subtle resource leaks when exceptions are thrown.

EXAMPLE
#include <boost/shared_ptr.hpp>
#include <boost/tr1/memory.hpp>
class Widget {
public:
Widget( ){}
~Widget( ){}
void f( void );
int priority( void );
void processWidget( std::tr1::shared_ptr<Widget>pw, int priority );
};
void Widget::f( void ) {
processWidget(
std::tr1::shared_ptr<Widget>( new Widget ), priority( ) ); //
Violation
}

REPAIR
#include <boost/shared_ptr.hpp>
#include <boost/tr1/memory.hpp>
class Widget {

public:
Widget( ){}
~Widget( ){}
void f( void );
int priority( void );
void processWidget( std::tr1::shared_ptr<Widget>pw, int priority );
};
void Widget::f( void ) {
std::tr1::shared_ptr <Widget> pw( new Widget );
processWidget( pw,priority( ) );
}

// OK

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 17

Write operator delete if you write operator new [MRM-26-3]


DESCRIPTION
This rule makes sure that if you write your own version of operator new,
you also write a corresponding operator delete. If you write delete when
you write new, you ensure that new and delete share the same assumptions.
See also: MRM-27

BENEFITS
Writing operator delete and operator new in concert helps
prevent memory corruption and memory leaks.

EXAMPLE
#include <stdio.h>
class A {
// Violation
public:
A( ) {}
void* operator new(size_t size);
};

REPAIR
#include <stdio.h>
class A {
// OK
public:
A( ) {}
void* operator new(size_t size);
void operator delete( void* );
};

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 10
2. General Principles of Software Validation;

Final Guidance for Industry and FDA Staff


Document issued on: January 11, 2002

Write operator delete[] if you write operator new[] [MRM-27-3]


DESCRIPTION
This rule makes sure that if you write your own version of operator new[
],
you also write a corresponding operator delete[ ]. If you write delete
when
you write new, you ensure that new and delete share the same assumptions.
See also: MRM-26

BENEFITS
Writing operator delete and operator new in concert helps
prevent memory corruption and memory leaks.

EXAMPLE
#include <stdio.h>
class A {
// Violation
public:
A( ) {}
void* operator new[](size_t size);
};

REPAIR
#include <stdio.h>
class A {
// OK
public:
A( ) {}
void* operator new[](size_t size);
void operator delete[]( void* );
};

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 10

2. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Always provide new and delete together [MRM-28-3]


DESCRIPTION
Every class-specific overload 'operator new' must be accompanied
by a matching overload 'operator delete'.
The same goes for the array forms new[] and delete[].
A declaration of a deallocation function matches the declaration
of the allocation function if it has the same number of parameters and all
parameter types except the first are identical.
The reason is that if new-expression allocates memory but later
initialization of the created object terminates by throwing an exception
and a suitable deallocation function can be found, the deallocation
function
is called to free the memory in which the object was being constructed.
If the suitable deallocation function does not exists it is likely to
result in a memory leak.
See also: MRM-26, MRM-29

NOTES
Rule described in Rule 45 of Herb Sutter & Andrei Alexandrescu
"C++ Coding Standards" has been modified to match C++ standard.

EXCEPTIONS
A declaration of a non-placement deallocation function with exactly
two parameters, the second of which has type std::size_t matches
a non-placement allocation function with one parameter.

BENEFITS
Prevents spurious memory leaks in cases when overloaded new operator
fails.
Ensures that corresponding new and delete operators share the same
assumptions.

EXAMPLE
#include <new>
class MemoryPool;
class A {
public:
void * operator new(std::size_t);
// Violation
void * operator new(std::size_t, MemoryPool&);
// Violation
void * operator new(std::size_t, float*);
// Violation
void operator delete(void*, std::size_t, float*);
};

REPAIR
#include <new>
class MemoryPool;
class A {
public:
void * operator new(std::size_t);
// OK
void * operator new(std::size_t, MemoryPool&); // OK
void * operator new(std::size_t, float*);
// OK
void operator delete(void*);
void operator delete(void*, MemoryPool&);
void operator delete(void*, float*);
};
class B {
public:
// non-placement allocation function
void * operator new(std::size_t);
// non-placement deallocation function
void operator delete(void*, std::size_t);
};

// OK

REFERENCES
ISO/IEC 14882:2003(E) C++ standard
Sections 5.3.4, 3.7.3
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 45

Always provide new[] and delete[] together [MRM-29-3]


DESCRIPTION
Every class-specific overload 'operator new' must be accompanied
by a matching overload 'operator delete'.
The same goes for the array forms new[] and delete[].
A declaration of a deallocation function matches the declaration
of the allocation function if it has the same number of parameters and all
parameter types except the first are identical.
The reason is that if new-expression allocates memory but later
initialization of the created object terminates by throwing an exception
and a suitable deallocation function can be found, the deallocation
function
is called to free the memory in which the object was being constructed.
If the suitable deallocation function does not exists it is likely to
result in a memory leak.
See also: MRM-26, MRM-29

NOTES
Rule described in Rule 45 of Herb Sutter & Andrei Alexandrescu
"C++ Coding Standards" has been modified to match C++ standard.

EXCEPTIONS
A declaration of a non-placement deallocation function with exactly
two parameters, the second of which has type std::size_t matches
a non-placement allocation function with one parameter.

BENEFITS
Prevents spurious memory leaks in cases when overloaded new operator
fails.
Ensures that corresponding new and delete operators share the same
assumptions.

EXAMPLE
#include <new>
class MemoryPool;
class A {
public:
void * operator new[](std::size_t);
// Violation
void * operator new[](std::size_t, MemoryPool&);
// Violation
void * operator new[](std::size_t, float*);
// Violation
void operator delete[](void*, std::size_t, float*);
};

REPAIR
#include <new>
class MemoryPool;
class A {
public:
void * operator new[](std::size_t);
// OK
void * operator new[](std::size_t, MemoryPool&); // OK
void * operator new[](std::size_t, float*);
// OK
void operator delete[](void*);
void operator delete[](void*, MemoryPool&);
void operator delete[](void*, float*);
};
class B {
public:
// non-placement allocation function
void * operator new[](std::size_t);
// non-placement deallocation function
void operator delete[](void*, std::size_t);
};

// OK

REFERENCES
ISO/IEC 14882:2003(E) C++ standard
Sections 5.3.4, 3.7.3
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 45

Use allocation by declaration rather than by new or malloc [MRM-30-3]


DESCRIPTION
If new/delete is used on a pointer in the same function, use allocation
by declaration instead.
See also: MRM-06, MRM-08, MRM-09, MRM-10, MRM-11

SINCE
v7.0

NOTES
The user need to be aware, because the rule may promote security flaws
and may be not a best practice on stack short devices.
In small systems stack size is critical. It should not be defined arrays
on the stack in case of critical importance to the system.
The change of code may cause that it will be more vulnerable to a buffer
overflow attack.

BENEFITS
Rule improves efficiency of code and prevents memory leaks.

EXAMPLE
#include <string>
using std::string;
void foo( ) {
string* pStr = new string();
// some operation on pStr
delete pStr;
}

REPAIR

// Violation

#include <string>
using std::string;
void foo( ) {
string pStr = "something";
// some operation on pStr
}

REFERENCES
Recommended by ParaSoft

// OK

Freed memory shouldn't be accessed under any circumstances. Destructor should not be
called manually [MRM-31-3]
DESCRIPTION
"There are three major kinds of invalid objects:
- Destroyed objects: Typical examples are automatic objects that have gone
out
of scope and deleted heap-based objects.
- Semantically invalidated objects: Typical examples include dangling
pointers
to deleted objects (e.g., a pointer p after a delete p;) and invalidated
iterators. It is generally undefined and unsafe to do anything except
assign
another valid value to an invalidated object.
- Objects that were never valid.
Be aware of object lifetimes and validity. Never dereference an invalid
iterator
or pointer. Don't make assumptions about what delete does and doesn't do;
freed memory is freed, and shouldn't be subsequently accessed under
any circumstances. Don't try to play with object lifetime by calling
the destructor manually (e.g. obj.~T())."
The rule reports violations on the use of pointers to deleted objects
and on explicit calls of destructors.

NOTES
The rule checks only simple cases (use of variables, parameters,
a[b], a.b, a->b, or *a expressions after they were deleted).
The rule does not check a flow. It assumes that pointer to deleted object
is used if between 'delete' and an use of that pointer there is no
'case', 'default', 'break', 'return', 'throw', 'goto', exit(), abort().

BENEFITS
Rule prevents writing unsafe and error prone code.

EXAMPLE
class A {

public:
A();
~A();
};
void foo1( ) {
A obj;
obj.~A( );
}

// Violation

char* foo2( ) {
char * a = new char;
delete a;
return a;
// Violation
};
char* foo3(char * ptr){
char * a = new char;
if(a > ptr){
delete a;
(*a)++;
// Violation
} else {
(*a)++;
// OK
}
a = ptr + 1;
return a;
// OK
}

REPAIR
Don't use invalid objects.

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 99
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 70.1

3. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid hiding the global new [MRM-32-1]


DESCRIPTION
This rule detects when the global new is hidden by an operator new.
By declaring a function called "operator new" inside the class,
you inadvertently block access to the "normal" form of new
See also: MRM-14

BENEFITS
If you hide the global new, normal new operator functionality
will be unavailable to maintainers of your code.

EXAMPLE
#include <stdlib.h>
void ErrorHandler() {};
class A {
// Violation
public:
void* operator new(size_t size, void (*pehf)()) {
return new int[size];
}
void operator delete(void *A) {
delete A;
}
};
template<class T> class D {
// Violation
public:
void* operator new(size_t size, T (*pehf)()) {
return new int[size];
}
void operator delete(void *d) {
delete d;
}
};
void foo() {
D<void> *a = new (ErrorHandler) D<void>;
}

REPAIR
#include <stdlib.h>
void ErrorHandler() {};
class B {
// OK
public:
void* operator new(size_t size, void (*pehf)()) {
return new int[size];
}
void* operator new(size_t size) {
return new int[size];
}
void operator delete(void *A) {
delete A;
}
};
class C {
// OK
public:
void* operator new(size_t size, void (*pehf)()) {
return new int[size];
}
void* operator new(size_t size, int aa=0) {
return new int[size];
}
void operator delete(void *A) {
delete A;
}
};
template<class T> class E {// OK
public:
void* operator new(size_t size, T (*pehf)()) {
return new int[size];
}
void* operator new(size_t size) {
return new int[size];
}
void operator delete(void *e) {
delete e;
}

};
template<class T> class F {// OK
public:
void* operator new(size_t size, T (*pehf)()) {
return new int[size];
}
void* operator new(size_t size, int aa=0) {
return new int[size];
}
void operator delete(void *f) {
delete f;
}
};
void foo() {
E<void> *a = new (ErrorHandler) E<void>;
}

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 9
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Call delete on pointer members in destructors [MRM-33-2]


DESCRIPTION
"Classes performing dynamic memory allocation will use 'new'
in the constructor(s) to allocate the memory and will later
use 'delete' in the destructor to free up the memory.
Failing to delete the pointer in the destructor often exhibits no obvious
external symptoms. Instead, it manifests itself as a subtle memory leak"
This rule reports a violation if it finds a pointer member allocated by
'new'
by any member function, that has no corresponding 'delete' in the
destructor.
See also: MRM-42

NOTES
Pointer member can be deleted inside function called from destructor.
The rule checks two nested levels of function's calls.

BENEFITS
Rule prevents memory leaks now and as the code evolves in the future.

EXAMPLE
class A
{
public:
A( );
~A( );
void init();
private:
int* ptr1; //
int* ptr2; //
int* ptr3; //
int* ptr4; //
};

Violation
Violation
Violation
OK - null pointer

A::A() : ptr1(new int), ptr4(0){


ptr3 = new int;

init();
}
void A::init(){
ptr2 = new int;
}
A::~A(){
// any delete
}

REPAIR
class A
{
public:
A( );
~A( );
void init();
void freeMem();
private:
int* ptr1; // OK
int* ptr2; // OK
int* ptr3; // OK
int* ptr4; // OK - null pointer
};
A::A() : ptr1(new int), ptr4(0){
ptr3 = new int;
init();
}
void A::init(){
ptr2 = new int;
}
void A::freeMem(){
delete ptr1;
delete ptr2;
}
A::~A(){
freeMem();

delete ptr3;
delete ptr4; // not necessary
}

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Check the return value of new [MRM-34-3]


DESCRIPTION
This rule warns you if you do not check
"Until 1993, C++ required that operator
to
allocate the requested memory. Operator
a bad_alloc exception, but a lot of C++

the return value of new.


new return null when it was unable
new is now specified to throw
was written before compilers began

supporting the revised specification. The C++ standardization committee


didn't
want to abandon the test-for-null code base, so they provided alternative
forms
of operator new that offer the traditional failure-yields-null behavior.
These
forms are called "nothrow" forms, in part because they employ nothrow
objects
(defined in the header <new>) at the point where new is used."

NOTES
Rule does not report a violation if result of 'new' is passed directly
to function call or 'return' statement.

BENEFITS
Prevents access to null pointer when memory is not allocated.

EXAMPLE
#include <new>
void foo()
{
char *pc;
pc = new char[10*10*10];
pc[0] = 'x';
delete[] pc;
int *p;
if(p){
/*code here*/

// Violation

}
p = new int;

// Violation

REPAIR
#include <new>
void foo()
{
char *pc;
try{
pc = new char[10*10*10];
}catch(std::bad_alloc&){}
pc[0] = 'x';
delete[] pc;
int *p = new int;
if(p){
/*code here*/
}
}

// OK

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 8, Item 49
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 7
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Never provide brackets ([]) for delete when deallocating non-arrays [MRM-35-3]
DESCRIPTION
Use the same form in corresponding calls to new and delete.
This rule checks calls to new and delete to make sure that
they use the same form; it reports a violation if you call
new and you [] when calling delete. If you do not use the
same form in corresponding calls to new and delete,
an incorrect number of destructors may be called.
See also: MRM-36

BENEFITS
Prevents using different kinds of 'new' and 'delete' calls.

EXAMPLE
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A;
delete[] a;
}

// Violation

REPAIR
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A;
delete a;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 5
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Always provide empty brackets ([]) for delete when deallocating arrays [MRM-36-3]
DESCRIPTION
Use the same form in corresponding calls to new and delete.
This rule checks calls to new and delete to make sure that
they use the same form; it reports a violation if you call
new[] but forget to use [] when calling delete. If you do
not use the same form in corresponding calls to new and delete,
an incorrect number of destructors may be called.
See also: MRM-35

BENEFITS
Prevents using different kinds of 'new' and 'delete' calls.

EXAMPLE
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A[100];
delete a;
}

// Violation

REPAIR
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A[100];
delete[] a;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 5
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rule 51
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declare an assignment operator for classes with dynamically allocated memory [MRM-37-1]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or
'delete' to deallocate its data member, has an explicitly defined
canonical
assignment operator. A canonical assignment operator returns a class
reference
type and takes a const reference of the type.
"An assignment is not inherited like other operators. If an assignment
operator
is not explicitly defined, then one is automatically defined instead.
If you perform an assignment 'b = a;' (where 'a' and 'b' are pointers)
there is
no client-defined operator= to call, so C++ generates and calls the
default
assignment operator instead.
This default assignment operator performs memberwise assignment from the
members of 'a' to the members of 'b', which for pointers is just a bitwise
copy.
There are at least two problems with this state of affairs.
First, the memory that 'b' used to point to was never deleted;
it is lost forever. This is a classic example of how a memory leak can
arise.
Second, both 'a' and 'b' now contain pointers to the same character
string.
When one of them goes out of scope, its destructor will delete the memory
still pointed to by the other."
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-38,
MRM-40, MRM-47, OOP-27, OOP-30, OOP-34

EXCEPTIONS
Rule does not report violation if there's an assignment operator in a base
class which prevents implicitly declared assignment operator in this class
from being used.

BENEFITS
"Bit-wise copying is only performed for member data having primitive

types.
One consequence of this is that bit-wise copying is performed for member
data
having pointer types. If an object manages the allocation of the instance
of
an object pointed to by a pointer member, this will probably lead to
problems:
either by invoking the destructor for the managed object more than once or
by
attempting to use the deallocated object."

EXAMPLE
class MyClass { // Violation
public:
MyClass( );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}

REPAIR
class MyClass { // OK
public:
MyClass( );
MyClass& operator=( const MyClass& );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 AssignmentOperators - Rule 27
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declare a copy constructor for classes with dynamically allocated memory [MRM-38-1]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or 'delete' to deallocate its data member, has an explicitly defined copy
constructor.
See also: CODSTA-CPP-19, MRM-05, MRM-37, MRM-40, MRM-48, OOP-27, OOP-30,
OOP-34

EXCEPTIONS
Rule does not report violation if there's an copy constructor in a base
class which prevents implicitly declared copy constructor in this class
from being used.

BENEFITS
"A copy constructor is recommended to
is initialized using an object of the
the allocation and deallocation of an
object has a pointer to the object to
constructor),
only the value of the pointer will be
invocations
of the destructor for the same object
in a run-time error."

EXAMPLE
class MyClass{ // Violation
public:
MyClass();
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}

avoid surprises when an object


same type. If an object manages
object on the heap (the managing
be created by the class'
copied. This can lead to two
(on the heap), probably resulting

REPAIR
class MyClass{ // OK
public:
MyClass();
MyClass(MyClass&);
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 25
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Constructors,
Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Provide error handling for file opening errors right next to the call to fopen [MRM-39-2]
DESCRIPTION
Provide error handling for file opening errors right next to the call to
fopen.

BENEFITS
Rule prevents accessing a FILE pointer in case
of IO error which will lead to a program crash.

EXAMPLE
#include <stdio.h>
int foo(int c)
{
FILE* data = fopen("data.txt", "r"); // Violation
do {
c = getc(data);
/* ... */
} while (c != EOF);
FILE* data2;
data2 = fopen("data2.txt", "r");
do {
c = getc(data2);
/* ... */
} while (c != EOF);
if (!data2)
{
/* ... */
return 0;
}
return 1;
}

// Violation

REPAIR
#include <stdio.h>
int foo(int c)
{
FILE* data = fopen("data.txt", "r");

// OK

if (data) {
do {
c = getc(data);
/* ... */
} while (c != EOF);
} else {
printf( "File opening error" );
return 0;
}
FILE* data2;
data2 = fopen("data2.txt", "r");
if (!data2) {
printf( "File opening error" );
return 0;
} else {
do {
c = getc(data2);
/* ... */
} while (c != EOF);
}
return 1;

// OK

REFERENCES
1. http://cwe.mitre.org/data/definitions/391.html
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Copy and destroy consistently [MRM-40-3]


DESCRIPTION
"If you define any of the copy constructor, copy assignment operator,
or destructor, you might need to define one or both of the others."
See also: CODSTA-CPP-02, CODSTA-CPP-19, CODSTA-CPP-21, CODSTA-CPP-24, MRM04,
MRM-05, MRM-37, MRM-38, MRM-47, MRM-48, OOP-27, OOP-30, OOP-34

EXCEPTIONS
"When any of the special functions are declared only to make
them private or virtual, but without special semantics, it doesn't
imply that the others are needed."

BENEFITS
Rule prevents from memory management problems.

EXAMPLE
class A {
public:
A( ) {}

// Violation - copy constructor is missing

A& operator=( const A& f ) {


return *this;
}
~A( ) {}
};
class B {
public:
B( ) {}
B( B& ) {}
~B( ) {}
};

// Violation - assignment operator is missing

class C {
public:
C( ) {}

// Violation - destructor is missing

C( C& ) {}
C& operator=( const C& f ) {
return *this;
}
};

REPAIR
class A {
destructor
public:
A( ) {}

// OK - copy constructor, assignment operator and

A( A& ) {}
A& operator=( const A& f ) {
return *this;
}
~A( ) {}
};
class B { // OK no defined copy constructor, assignment operator and
destructor
};
class C { // OK - copy constructor, assignment operator and destructor
public:
C( ) {}
C( C& ) {}
C& operator=( const C& f ) {
return *this;
}
~C( ) {}

};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 52
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A copy constructor shall copy all data members and bases [MRM-41-2]
DESCRIPTION
"A class may contain many data members as well as exist within an
inheritance
hierarchy. Hence the copy constructor must copy all members, including
those
in base classes."

SINCE
v7.1

NOTES
The rule does not report violations on variables of class/struct type.
If a copy constructor of base class is called then the rule assumes
that all variables from a base class are copied.

BENEFITS
"Ensure data members and bases are properly handled when an object is
copied."

EXAMPLE
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:

Derived (int x, int y, int z) : Base (x),


derived_member_1 (y),
derived_member_2 (z) { }
Derived(const Derived& rhs)
{
}

// Violation

private:
int derived_member_1;
int derived_member_2;
};

REPAIR
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:
Derived (int x, int y, int z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) { }
Derived(const Derived& rhs) : Base(rhs),
derived_member_1 (rhs.derived_member_1),
derived_member_2 (rhs.derived_member_2)
{
}
private:
int derived_member_1;
int derived_member_2;
};

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Call fclose() on pointer member in destructor if the pointer was used to open a file [MRM-42-2]
DESCRIPTION
This rule reports a violation message when pointer member was used to open
a file in constructor and the file is not closed in destructor.
See also: MRM-33

SINCE
v7.1

BENEFITS
Prevention of resource leaks, especially in error cases.
Releasing resources in a destructor provides a convenient means of
resource
management, especially in regards to exceptional cases. Moreover, if it is
possible that a resource could be leaked, then that resource should be
wrapped
in a class whose destructor automatically cleans up the resource.

EXAMPLE
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}

~File_ptr ()
{
}
private:

// Violation

FILE *p;
};

REPAIR
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}

~File_ptr ()
{
if (p)
{
fclose(p);
}
}

// OK

private:
FILE *p;
};

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 79
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The assignment operator must assign all members, including those in base classes [MRM-432]
DESCRIPTION
A class may contain many data members as well as exist within
an inheritance hierarchy. Hence the assignment operator must
assign all members, including those in base classes.
Rule reports a violation message if base class assignment
operator is not called or not all base classes' member variables
are assigned within derived class assignment operator.
See also: INIT-11

SINCE
v7.1

BENEFITS
Assign to all member variables in operator= function
in order to prevent data corruption.

EXAMPLE
typedef unsigned int int32;
class Base
{
public:
Base (int32 x) : base_member (x) {}
Base &operator=(const Base& rhs)
{
if (this != &rhs)
{
base_member = rhs.base_member;
}
else
{
}
return *this;
}

private:
int32 base_member;
};

class Derived : public Base


{
public:
Derived (int32 x, int32 y, int32 z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) {}
Derived& operator=(const Derived& rhs)
// Violation
{
if (this != &rhs)
{
derived_member_1 = rhs.derived_member_1;
derived_member_2 = rhs.derived_member_2;
}
else
{
}
return *this;
}
private:
int32 derived_member_1;
int32 derived_member_2;
};

REPAIR
typedef unsigned int int32;
class Base
{
public:
Base (int32 x) : base_member (x) {}
Base &operator=(const Base& rhs)
{
if (this != &rhs)
{
base_member = rhs.base_member;
}
else

{
}
return *this;
}
private:
int32 base_member;
};

class Derived : public Base


{
public:
Derived (int32 x, int32 y, int32 z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) {}
Derived& operator=(const Derived& rhs)
{
if (this != &rhs) // Check for self-assignment
{
Base::operator=(rhs);
derived_member_1 = rhs.derived_member_1;
derived_member_2 = rhs.derived_member_2;
}
else
{
}
return *this;
}
private:
int32 derived_member_1;
int32 derived_member_2;
};

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 83
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

// OK

Avoid passing address of auto variable into caller space [MRM-44-2]


DESCRIPTION
Rule reports a violation if the address of an auto variable is passed via
assignment into a location specified by the caller to the function.
For example:
void foo( int *a[] )
{
int r;
a[1] = &r;
}
In above example the address of a local variable 'r' is being passed into
the second element of the array passed to the function 'foo'.
Such situation may cause that upon return the array will contain a pointer
to a variable which lifetime is over.
See also: MISRA2004-17_6, OOP-12, OOP-36, MRM-24

SINCE
v7.2

BENEFITS
Rule prevents possibility of erroneous code.

EXAMPLE
void foo(int *a[])
{
int n;
a[1] = &n;
// Violation
}

REPAIR
Do not pass address of an auto variable into caller space.

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not use sizeof operator on pointer type to specify the size of the memory to be allocated
via 'malloc', 'calloc' or 'realloc' function [MRM-45-3]
DESCRIPTION
Rule reports a violation message if any of the following functions:
'malloc', 'calloc', or 'realloc' is used to allocate memory and the size
of required memory is calculated using a sizeof operator with the pointer
to the type instead of actual type. Using a pointer to the type instead of
actual type as sizeof argument makes the sizeof operator return the size
of pointer (which is 4 in a 32-bit platform).
See also: PB-32

SINCE
v7.2

BENEFITS
Rule prevents incorrect memory allocation.

EXAMPLE
#include <stdlib.h>
typedef struct Str
{
int m1;
int m2;
}*pS;
void foo(int n)
{
pS var = (pS) malloc(n * sizeof(pS));
free(var);
}

REPAIR
#include <stdlib.h>

// Violation

typedef struct Str


{
int m1;
int m2;
}*pS;
void foo(int n)
{
pS var = (pS) malloc(n * sizeof(Str));
free(var);
}

// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
2. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131
http://cwe.mitre.org/top25/#CWE-131

Do not use calloc, malloc, realloc and free functions [MRM-46-3]


DESCRIPTION
"In C malloc, realloc and free are used to allocate memory dynamically on
the
heap. This may lead to conflicts with the use of the new and delete
operators
in C++."
The rule disallow using calloc, malloc, realloc and free functions in C++.

SINCE
v7.2

BENEFITS
The rule prevents or decreases the danger of:
"- invoking delete for a pointer obtained via malloc/realloc,
- invoking malloc/realloc for objects having constructors,
- invoking free for anything allocated using new."

EXAMPLE
#include <malloc.h>
void foo( ) {
char* string;
char* string2;
string = (char *) malloc( 10 );
string2 = (char*) realloc( string, 12 );
free( string );
free( string2 );

/*
/*
/*
/*

Violation
Violation
Violation
Violation

REPAIR
Do not use calloc, malloc, realloc and free functions.

*/
*/
*/
*/

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rule 50
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Shifting from C to C++",
Item 3

Classes containing at least one non-static member variable should declare the assignment
operator or contain appropriate comment [MRM-47-3]
DESCRIPTION
Classes which have at least one non-static member variable should contain
the assignment operator. When behavior of the compiler-generated version
of operator is correct it should be commented. Comment should contain
string "assignment operator" which is checked insensitive.
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37,
MRM-40, MRM-48, OOP-27, OOP-30, OOP-34

SINCE
v7.3

BENEFITS
Prevents using compiler-generated assignment operator by accident.

EXAMPLE
class A
// Violation
{
private:
int* ptr;
};
class B
// Violation
{
private:
int var;
};

REPAIR
class A
// OK
{
public:
A& operator=(const A&);

private:
int* ptr;
};
class B
// OK
{
// Assignment operator is compiler generated
private:
int var;
};

REFERENCES
Recommended by ParaSoft

Classes containing at least one non-static member variable should declare the copy
constructor or contain appropriate comment [MRM-48-3]
DESCRIPTION
Classes which have at least one non-static member variable should declare
the copy constructor. When behavior of the compiler-generated version
of copy constructor is correct it should be commented. Comment should
contain
string "copy constructor" which is checked insensitive.
See also: CODSTA-CPP-19, MRM-05, MRM-38, MRM-40, MRM-47, OOP-27, OOP-30,
OOP-34

SINCE
v7.3

BENEFITS
Prevents using compiler-generated copy constructor by accident.

EXAMPLE
class A
// Violation
{
public:
A();
private:
int* ptr;
};
class B
// Violation
{
private:
int var;
};

REPAIR
class A

// OK

{
public:
A();
A(const A&);
private:
int* ptr;
};
class B
// OK
{
// Copy constructor is compiler generated
private:
int var;
};

REFERENCES
Recommended by ParaSoft

NAMING
Naming Conventions
RULES
All "#define" constants shall be in uppercase [NAMING-01-3]
In an enumerated list, list members (elements) shall be in uppercase and
names or tags for the list shall be in lowercase [NAMING-02-3]
Use lowercase for file names [NAMING-03-3]
Global prefixes should only be used for global variables [NAMING-04-3]
Begin local variable names with a lowercase letters [NAMING-05-3]
Begin global variable names with a lowercase letters [NAMING-06-3]
Begin member variable names with a lowercase letters [NAMING-07-3]
Begin all boolean type variables with 'b' [NAMING-08-3]
Begin class, struct, union, enum, and typedef names with an uppercase
letter [NAMING-09-3]
The names of abstract data types, structures, typedefs, and enumerated
types are to begin with an uppercase letter [NAMING-10-3]
The name of enumeration type shall begin with an uppercase letter and
contain a suffix '_t' at the end [NAMING-11-3]
The names of structures shall begin with an uppercase letter and contain a
suffix '_t' at the end [NAMING-12-3]
Begin constant variables with 'c' [NAMING-13-3]
Begin class data member names with 'its' [NAMING-14-3]
Begin all double type variable with 'd' [NAMING-15-3]
Begin all float type variables with 'f' [NAMING-16-3]
Begin all function names with uppercase letter [NAMING-17-3]
Begin global variable names with 'the' [NAMING-18-3]
Begin all integer type variable with 'i' [NAMING-19-3]
Functions that begin with 'is' should return boolean values [NAMING-20-3]
Begin all long integer variables with 'li' [NAMING-21-3]
Prefix a variable type 'pointer' with a 'p' character [NAMING-22-3]
Begin all short integer variables with 'si' [NAMING-23-3]
Begin all signed character variables with 'c' [NAMING-24-3]
Begin all terminated characters string variables with 'sz' [NAMING-25-3]
Begin all unsigned character type variables with 'uc' [NAMING-26-3]
Begin all unsigned integer type variables with 'ui' [NAMING-27-3]
Use lowercase letters for structure and union member names [NAMING-28-3]
Append names of non-scalar typedefs with "_t" [NAMING-29-3]
Implementation files in C always have the file name extension ".c"
[NAMING-30-3]
Do not use typenames that differ only by the use of uppercase and
lowercase letters [NAMING-31-3]
An include file for a class should have a file name of the form <class
name> + extension [NAMING-32-3]

Do not use identifiers which begin with one or two underscores (`_' or
`__') [NAMING-33-3]
Global function names should start with lowercase [NAMING-34-3]
Member function names should start with lowercase [NAMING-35-3]
Names of parameters in declaration and definition should be identical
[NAMING-36-3]
Include files in C++ always have the file name extension '.hh' [NAMING-373]
Implementation files in C++ always have the file name extension ".cc"
[NAMING-38-3]
Inline definition files always have the file name extension ".icc"
[NAMING-39-3]
Only the first word of the name of a class, structure, namespace,
enumeration, or typedef will begin with an uppercase letter [NAMING-40-3]
Header files will always have a file name extension of '.h' [NAMING-41-3]
Identifiers for constant and enumerator values shall be lowercase [NAMING42-2]
Implementation files will always have a file name extension of ".cpp"
[NAMING-43-3]
All letters contained in function and variable names will be composed
entirely of lowercase letters [NAMING-44-3]
Identifiers will not differ by mixture of case, the underscore character,
interchange of the similarly looking letters and numbers [NAMING-45-3]
The ', ", /* or // characters shall not occur in a header file name
[NAMING-46-3]
Different identifiers shall be typographically unambiguous [NAMING-47-3]
The \ character should not occur in a header file name [NAMING-48-3]

NAMING-HN
Hungarian Notation
RULES
Hungarian notation for array variables and parameters [NAMING-HN-01-3]
Hungarian notation for bool types [NAMING-HN-02-3]
Hungarian notation for bool pointer, array, or reference types [NAMING-HN03-3]
Hungarian notation for byte types [NAMING-HN-04-3]
Hungarian notation for byte pointer, array, or reference types [NAMING-HN05-3]
Hungarian notation for char types [NAMING-HN-06-3]
Hungarian notation for array of char types [NAMING-HN-07-3]
Hungarian notation for pointer, array, or reference to array of char types
[NAMING-HN-08-3]
Hungarian notation for char pointer, array, or reference types [NAMING-HN09-3]
Hungarian notation for char pointer or reference types [NAMING-HN-10-3]
Hungarian notation for constant parameters [NAMING-HN-11-3]
Hungarian notation for double-precision floating point types [NAMING-HN12-3]
Hungarian notation for double-precision floating point pointer, array, or
reference types [NAMING-HN-13-3]
Hungarian notation for dword types [NAMING-HN-14-3]
Hungarian notation for dword pointer, array, or reference types [NAMINGHN-15-3]
Hungarian notation for dynamically allocated array [NAMING-HN-16-3]
Hungarian notation for floating point types [NAMING-HN-17-3]
Hungarian notation for floating point pointer, array, or reference types
[NAMING-HN-18-3]
Hungarian notation for class declaration [NAMING-HN-19-3]
Hungarian notation for structs declaration [NAMING-HN-20-3]
Hungarian notation for ifstream type variables and parameters [NAMING-HN21-3]
Hungarian notation for int types [NAMING-HN-22-3]
Hungarian notation for int pointer, array, or reference types [NAMING-HN23-3]
Hungarian notation for istream type parameters and variables [NAMING-HN24-3]
Hungarian notation for long int types [NAMING-HN-25-3]
Hungarian notation for long double-precision floating point types [NAMINGHN-26-3]
Hungarian notation for long double-precision floating point pointer,
array, or reference types [NAMING-HN-27-3]

Hungarian notation
[NAMING-HN-28-3]
Hungarian notation
Hungarian notation
Hungarian notation
31-3]
Hungarian notation
32-3]
Hungarian notation
33-3]
Hungarian notation
Hungarian notation
Hungarian notation
Hungarian notation
[NAMING-HN-37-3]
Hungarian notation
Hungarian notation
Hungarian notation
HN-40-3]
Hungarian notation
Hungarian notation
Hungarian notation
Hungarian notation
44-3]

for long int pointer, array, or reference types


for member variables [NAMING-HN-29-3]
for int types [NAMING-HN-30-3]
for int pointer, array, or reference types [NAMING-HNfor ofstream type parameters and variables [NAMING-HNfor ostream type parameters and variables [NAMING-HNfor
for
for
for

pointer [NAMING-HN-34-3]
reference parameters [NAMING-HN-35-3]
short int types [NAMING-HN-36-3]
short int pointer, array, or reference types

for static variables [NAMING-HN-38-3]


for string types [NAMING-HN-39-3]
for string pointer, array, or reference types [NAMINGfor
for
for
for

unsigned types [NAMING-HN-41-3]


void pointer types [NAMING-HN-42-3]
word types [NAMING-HN-43-3]
word pointer, array, or reference types [NAMING-HN-

Hungarian notation for array variables and parameters [NAMING-HN-01-3]


DESCRIPTION
For array (stands for range) variables and parameters use "rg" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
const int kiMAX=10;
float fTmp[kiMAX];
void foo()
{
int iTab[10];
int iTab2[kiMAX];
}

// Violation

// Violation
// Violation

REPAIR
const int kiMAX=10;
float rgfTmp[kiMAX];
void foo()
{
int rgiTab[10];
int rgiTab2[kiMAX];
}

// OK

// OK
// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for bool types [NAMING-HN-02-3]


DESCRIPTION
For bool variables and parameters use "b" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
bool g_bmyVar;
bool g_MyVariable;
static const bool g_skMyVariable = true;
class A {
bool m_MyVariable;
static const bool m_skMyVariable = true;
void foo( bool MyParam ) {
bool MyVariable;
static const bool skMyVariable = true;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
bool g_bMyVar;
bool g_bMyVariable;
static const bool g_skbMyVariable = true;
class A {
bool m_bMyVariable;
static const bool m_skbMyVariable = true;
void foo( bool bMyParam ) {
bool bMyVariable;
static const bool skbMyVariable = true;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for bool pointer, array, or reference types [NAMING-HN-03-3]


DESCRIPTION
For bool pointer, array, or reference variables and parameters use "b"
prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
bool* g_pbmyVar;
bool* g_pMyVariable;
static const bool* g_spkMyVariable;
class A {
bool* m_pMyVariable;
static const bool* m_spkMyVariable;
void foo( bool* pMyParam ) {
bool* pMyVariable;
static const bool* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
bool* g_pbMyVar;
bool* g_pbMyVariable;
static const bool* g_spkbMyVariable;
class A {
bool* m_pbMyVariable;
static const bool* m_spkbMyVariable;
void foo( bool* pbMyParam ) {
bool* pbMyVariable;
static const bool* spkbMyVariable;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for byte types [NAMING-HN-04-3]


DESCRIPTION
For unsigned char variables and parameters use "by" or "y" prefix.
For char or signed char variables and parameters use "c" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
char g_cmyVar;
char g_MyVariable;
static const char g_skMyVariable = 'a';
class A {
char m_MyVariable;
static const char m_skMyVariable = 'a';
void foo( char MyParam ) {
char MyVariable;
static const char skMyVariable = 'a';
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

unsigned char g_bymyVar2;


unsigned char g_MyVariable2;
static const unsigned char g_skMyVariable2 = 0;
class B {
unsigned char m_MyVariable;
static const unsigned char m_skMyVariable = 0;
void foo( unsigned char MyParam ) {
unsigned char MyVariable;
static const unsigned char skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
char g_cMyVar;
char g_cMyVariable;
static const char g_skcMyVariable = 'a';
class A {
char m_cMyVariable;
static const char m_skcMyVariable = 'a';
void foo( char cMyParam ) {
char cMyVariable;
static const char skcMyVariable = 'a';
}
};

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

unsigned char g_byMyVar2;


unsigned char g_byMyVariable2;
static const unsigned char g_skbyMyVariable2 = 0;
class B {
unsigned char m_byMyVariable;
static const unsigned char m_skbyMyVariable = 0;
void foo( unsigned char byMyParam ) {
unsigned char byMyVariable;
static const unsigned char skbyMyVariable = 0;
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

Hungarian notation for byte pointer, array, or reference types [NAMING-HN-05-3]


DESCRIPTION
For unsigned char pointer, array, or reference variables and parameters
use
"by" or "y" prefix. For char or signed char pointer, array, or reference
variables and parameters use "c" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
char* g_pcmyVar;
char* g_pMyVariable;
static const char* g_spkMyVariable;
class A {
char* m_pMyVariable;
static const char* m_spkMyVariable;
void foo( char* pMyParam ) {
char* pMyVariable;
static const char* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

unsigned char* g_pbymyVar2;


unsigned char* g_pMyVariable2;
static const unsigned char* g_spkMyVariable2;
class B {
unsigned char* m_pMyVariable;
static const unsigned char* m_spkMyVariable;
void foo( unsigned char* pMyParam ) {
unsigned char* pMyVariable;
static const unsigned char* spkMyVariable;
}

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

};

REPAIR
char* g_pcMyVar;
char* g_pcMyVariable;
static const char* g_spkcMyVariable;
class A {
char* m_pcMyVariable;
static const char* m_spkcMyVariable;
void foo( char* pcMyParam ) {
char* pcMyVariable;
static const char* spkcMyVariable;
}
};

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

unsigned char* g_pbyMyVar2;


unsigned char* g_pbyMyVariable2;
static const unsigned char* g_spkbyMyVariable2;
class B {
unsigned char* m_pbyMyVariable;
static const unsigned char* m_spkbyMyVariable;
void foo( unsigned char* pbyMyParam ) {
unsigned char* pbyMyVariable;
static const unsigned char* spkbyMyVariable;
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

Hungarian notation for char types [NAMING-HN-06-3]


DESCRIPTION
For char variables and parameters use "c" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
char g_cmyVar;
char g_MyVariable;
static const char g_skMyVariable = 'a';
class A {
char m_MyVariable;
static const char m_skMyVariable = 'a';
void foo( char MyParam ) {
char MyVariable;
static const char skMyVariable = 'a';
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
char g_cMyVar;
char g_cMyVariable;
static const char g_skcMyVariable = 'a';
class A {
char m_cMyVariable;
static const char m_skcMyVariable = 'a';
void foo( char cMyParam ) {
char cMyVariable;
static const char skcMyVariable = 'a';
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for array of char types [NAMING-HN-07-3]


DESCRIPTION
For old-style null terminated string variables and parameters use "sz"
prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
char g_szmyVar[1];
char g_MyVariable[1];
static const char g_skMyVariable[1] = {0};
class B {
char m_MyVariable[1];
static const char m_skMyVariable[1];
void foo( char MyParam[1] ) {
char MyVariable[1];
static const char skMyVariable[1] = {0};
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
char g_szMyVar[1];
char g_szMyVariable[1];
static const char g_skszMyVariable[1] = {0};
class A {
char m_szMyVariable[1];
static const char m_skszMyVariable[1];
void foo( char szMyParam[1] ) {
char szMyVariable[1];
static const char skszMyVariable[1] = {0};

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for pointer, array, or reference to array of char types [NAMING-HN-08-3]
DESCRIPTION
For pointer, array, or reference to old-style null terminated
string variables and parameters use "sz" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
char (*g_pszmyVar)[1];
char (*g_pMyVariable)[1];
static const char (*g_spkMyVariable)[1];
class B {
char (*m_pMyVariable)[1];
static const char (*m_spkMyVariable)[1];
void foo( char (*pMyParam)[1] ) {
char (*pMyVariable)[1];
static const char (*spkMyVariable)[1];
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
char (*g_pszMyVar)[1];
char (*g_pszMyVariable)[1];
static const char (*g_spkszMyVariable)[1];
class A {
char (*m_pszMyVariable)[1];
static const char (*m_spkszMyVariable)[1];
void foo( char (*pszMyParam)[1] ) {
char (*pszMyVariable)[1];
static const char (*spkszMyVariable)[1];

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for char pointer, array, or reference types [NAMING-HN-09-3]


DESCRIPTION
For char pointer, array, or reference variables and parameters use "c"
prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
char* g_pcmyVar;
char* g_pMyVariable;
static const char* g_spkMyVariable;
class B {
char* m_pMyVariable;
static const char* m_spkMyVariable;
void foo( char* pMyParam ) {
char* pMyVariable;
static const char* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
char* g_pcMyVar;
char* g_pcMyVariable;
static const char* g_spkcMyVariable;
class A {
char* m_pcMyVariable;
static const char* m_spkcMyVariable;
void foo( char* pcMyParam ) {
char* pcMyVariable;
static const char* spkcMyVariable;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for char pointer or reference types [NAMING-HN-10-3]


DESCRIPTION
For char pointer or reference variables and parameters use "c" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
char* g_cmyVar;
char* g_MyVariable;
static const char* g_skMyVariable;
class A {
char* m_MyVariable;
static const char* m_skMyVariable;
void foo( char* MyParam ) {
char* MyVariable;
static const char* skMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
char* g_cMyVar;
char* g_cMyVariable;
static const char* g_skcMyVariable;
class A {
char* m_cMyVariable;
static const char* m_skcMyVariable;
void foo( char* cMyParam ) {
char* cMyVariable;
static const char* skcMyVariable;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for constant parameters [NAMING-HN-11-3]


DESCRIPTION
For constant parameters use "k" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
void foo( const unsigned char ucLabel )
{
}

// Violation

REPAIR
void foo( const unsigned char kucLabel )
{
}

REFERENCES

// OK

http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for double-precision floating point types [NAMING-HN-12-3]


DESCRIPTION
For double-precision floating point variables and parameters use "d"
prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
double g_dmyVar;
double g_MyVariable;
static const double g_skMyVariable = 0.0;
class B {
double m_MyVariable;
static const double m_skMyVariable;
void foo( double MyParam ) {
double MyVariable;
static const double skMyVariable = 0.0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
double g_dMyVar;
double g_dMyVariable;
static const double g_skdMyVariable = 0.0;
class A {
double m_dMyVariable;
static const double m_skdMyVariable;
void foo( double dMyParam ) {
double dMyVariable;
static const double skdMyVariable = 0.0;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for double-precision floating point pointer, array, or reference types
[NAMING-HN-13-3]
DESCRIPTION
For double-precision floating point pointer, array,
or reference variables and parameters use "d" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
double* g_pdmyVar;
double* g_pMyVariable;
static const double* g_spkMyVariable;
class B {
double* m_pMyVariable;
static const double* m_spkMyVariable;
void foo( double* pMyParam ) {
double* pMyVariable;
static const double* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
double* g_pdMyVar;
double* g_pdMyVariable;
static const double* g_spkdMyVariable;
class A {
double* m_pdMyVariable;
static const double* m_spkdMyVariable;
void foo( double* pdMyParam ) {
double* pdMyVariable;

// OK
// OK
// OK
//
//
//
//

OK
OK
OK
OK

static const double* spkdMyVariable;


}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

// OK

Hungarian notation for dword types [NAMING-HN-14-3]


DESCRIPTION
For unsigned long int variables and parameters use "dw" prefix.
For signed long int or long int variables and parameters use "li" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
long g_limyVar;
long g_MyVariable;
static const long g_skMyVariable = 0;
class A {
long m_MyVariable;
static const long m_skMyVariable;
void foo( long MyParam ) {
long MyVariable;
static const long skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

unsigned long g_dwmyVar2;


unsigned long g_MyVariable2;
static const unsigned long g_skMyVariable2 = 0;
class B {
unsigned long m_MyVariable;
static const unsigned long m_skMyVariable;
void foo( unsigned long MyParam ) {
unsigned long MyVariable;
static const unsigned long skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
long g_liMyVar;
long g_liMyVariable;
static const long g_skliMyVariable = 0;
class A {
long m_liMyVariable;
static const long m_skliMyVariable;
void foo( long liMyParam ) {
long liMyVariable;
static const long skliMyVariable = 0;
}
};

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

unsigned long g_dwMyVar2;


unsigned long g_dwMyVariable2;
static const unsigned long g_skdwMyVariable2 = 0;
class B {
unsigned long m_dwMyVariable;
static const unsigned long m_skdwMyVariable;
void foo( unsigned long dwMyParam ) {
unsigned long dwMyVariable;
static const unsigned long skdwMyVariable = 0;
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

Hungarian notation for dword pointer, array, or reference types [NAMING-HN-15-3]


DESCRIPTION
For unsigned long int pointer, array, or reference variables and
parameters use
"dw" prefix. For signed long int or long int pointer, array, or reference
variables and parameters use "li" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
long* g_plimyVar;
long* g_pMyVariable;
static const long* g_spkMyVariable;
class A {
long* m_pMyVariable;
static const long* m_spkMyVariable;
void foo( long* pMyParam ) {
long* pMyVariable;
static const long* spkMyVariable;
}
};
unsigned long* g_pdwmyVar2;
unsigned long* g_pMyVariable2;
static const unsigned long* g_spkMyVariable2;
class B {
unsigned long* m_pMyVariable;
static const unsigned long* m_spkMyVariable;
void foo( unsigned long* pMyParam ) {
unsigned long* pMyVariable;
static const unsigned long* spkMyVariable;
}

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

};

REPAIR
long* g_pliMyVar;
long* g_pliMyVariable;
static const long* g_spkliMyVariable;
class A {
long* m_pliMyVariable;
static const long* m_spkliMyVariable;
void foo( long* pliMyParam ) {
long* pliMyVariable;
static const long* spkliMyVariable;
}
};
unsigned long* g_pdwMyVar2;
unsigned long* g_pdwMyVariable2;
static const unsigned long* g_spkdwMyVariable2;
class B {
unsigned long* m_pdwMyVariable;
static const unsigned long* m_spkdwMyVariable;
void foo( unsigned long* pdwMyParam ) {
unsigned long* pdwMyVariable;
static const unsigned long* spkdwMyVariable;
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

Hungarian notation for dynamically allocated array [NAMING-HN-16-3]


DESCRIPTION
For dynamically allocated array use "prg" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
const int kiMAX=10;
int *iGrade = new int [kiMAX];
void foo()
{
int *p=new int;
int *iNote = new int[kiMAX];
int *iMark;
iMark = new int[10];
}

// Violation

// Violation
// Violation

REPAIR
const int kiMAX=10;
int *prgiGrade = new int [kiMAX];
void foo()
{
int *p=new int;
int *prgiNote = new int[kiMAX];
int *prgiMark;
prgiMark = new int[10];

// OK

// OK
// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for floating point types [NAMING-HN-17-3]


DESCRIPTION
For floating point variables and parameters use "f" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
float g_fmyVar;
float g_MyVariable;
static const float g_skMyVariable = 0.0;
class B {
float m_MyVariable;
static const float m_skMyVariable;
void foo( float MyParam ) {
float MyVariable;
static const float skMyVariable = 0.0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
float g_fMyVar;
float g_fMyVariable;
static const float g_skfMyVariable = 0.0;
class A {
float m_fMyVariable;
static const float m_skfMyVariable;
void foo( float fMyParam ) {
float fMyVariable;
static const float skfMyVariable = 0.0;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for floating point pointer, array, or reference types [NAMING-HN-18-3]
DESCRIPTION
For floating point pointer, array, or reference
variables and parameters use "f" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
float* g_pfmyVar;
float* g_pMyVariable;
static const float* g_spkMyVariable;
class B {
float* m_pMyVariable;
static const float* m_spkMyVariable;
void foo( float* pMyParam ) {
float* pMyVariable;
static const float* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
float* g_pfMyVar;
float* g_pfMyVariable;
static const float* g_spkfMyVariable;
class A {
float* m_pfMyVariable;
static const float* m_spkfMyVariable;
void foo( float* pfMyParam ) {
float* pfMyVariable;
static const float* spkfMyVariable;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for class declaration [NAMING-HN-19-3]


DESCRIPTION
For class declaration use "C" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
class Figure
{
};

// Violation

REPAIR
class CFigure
{
};

// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for structs declaration [NAMING-HN-20-3]


DESCRIPTION
For structs declaration use "S" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
struct Figure
{
};

// Violation

REPAIR
struct SFigure
{
};

// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for ifstream type variables and parameters [NAMING-HN-21-3]


DESCRIPTION
For ifstream type variables and parameters use "if" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
#include <fstream>
using namespace std;
ifstream NameFile;
void foo( ) {
ifstream Filename;
ifstream *pFilename;
}

// Violation

// Violation
// Violation

REPAIR
#include <fstream>
using namespace std;
ifstream ifNameFile;
void foo( ) {
ifstream ifFilename;
ifstream *pifFilename;
}

// OK

// OK
// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for int types [NAMING-HN-22-3]


DESCRIPTION
For int variables and parameters use "i" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
int g_imyVar;
int g_MyVariable;
static const int g_skMyVariable = 0;
class A {
int m_MyVariable;
static const int m_skMyVariable;
void foo( int MyParam ) {
int MyVariable;
static const int skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
int g_iMyVar;
int g_iMyVariable;
static const int g_skiMyVariable = 0;
class A {
int m_iMyVariable;
static const int m_skiMyVariable;
void foo( int iMyParam ) {
int iMyVariable;
static const int skiMyVariable = 0;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for int pointer, array, or reference types [NAMING-HN-23-3]


DESCRIPTION
For int pointer, array, or reference variables and parameters use "i"
prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
int* g_pimyVar;
int* g_pMyVariable;
static const int* g_spkMyVariable;
class A {
int* m_pMyVariable;
static const int* m_spkMyVariable;
void foo( int* pMyParam ) {
int* pMyVariable;
static const int* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
int* g_piMyVar;
int* g_piMyVariable;
static const int* g_spkiMyVariable;
class A {
int* m_piMyVariable;
static const int* m_spkiMyVariable;
void foo( int* piMyParam ) {
int* piMyVariable;
static const int* spkiMyVariable;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for istream type parameters and variables [NAMING-HN-24-3]


DESCRIPTION
For istream type parameters and variables use "is" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
#include <istream>
using namespace std;
void foo( istream &rIn )
{
}

// Violation

REPAIR
#include <istream>
using namespace std;
void foo( istream &risIn )
{
}

// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for long int types [NAMING-HN-25-3]


DESCRIPTION
For long int variables and parameters use "li" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
long int g_limyVar;
long int g_MyVariable;
static const long int g_skMyVariable = 0;
class B {
long int m_MyVariable;
static const long int m_skMyVariable;
void foo( long int MyParam ) {
long int MyVariable;
static const long int skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
long int g_liMyVar;
long int g_liMyVariable;
static const long int g_skliMyVariable = 0;
class A {
long int m_liMyVariable;
static const long int m_skliMyVariable;
void foo( long int liMyParam ) {
long int liMyVariable;
static const long int skliMyVariable = 0;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for long double-precision floating point types [NAMING-HN-26-3]


DESCRIPTION
For long double-precision floating point
variables and parameters use "ld" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
long double g_ldmyVar;
long double g_MyVariable;
static const long double g_skMyVariable = 0.0;
class B {
long double m_MyVariable;
static const long double m_skMyVariable;
void foo( long double MyParam ) {
long double MyVariable;
static const long double skMyVariable = 0.0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
long double g_ldMyVar;
long double g_ldMyVariable;
static const long double g_skldMyVariable = 0.0;
class A {
long double m_ldMyVariable;
static const long double m_skldMyVariable;
void foo( long double ldMyParam ) {
long double ldMyVariable;
static const long double skldMyVariable = 0.0;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for long double-precision floating point pointer, array, or reference types
[NAMING-HN-27-3]
DESCRIPTION
For long double-precision floating point pointer, array,
or reference variables and parameters use "ld" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
long double* g_pldmyVar;
long double* g_pMyVariable;
static const long double* g_spkMyVariable;
class B {
long double* m_pMyVariable;
static const long double* m_spkMyVariable;
void foo( long double* pMyParam ) {
long double* pMyVariable;
static const long double* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
long double* g_pldMyVar;
long double* g_pldMyVariable;
static const long double* g_spkldMyVariable;
class A {
long double* m_pldMyVariable;
static const long double* m_spkldMyVariable;
void foo( long double* pldMyParam ) {
long double* pldMyVariable;

// OK
// OK
// OK
//
//
//
//

OK
OK
OK
OK

static const long double* spkldMyVariable;


}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

// OK

Hungarian notation for long int pointer, array, or reference types [NAMING-HN-28-3]
DESCRIPTION
For long int pointer, array, or reference
variables and parameters use "li" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
long int* g_plimyVar;
long int* g_pMyVariable;
static const long int* g_spkMyVariable;
class B {
long int* m_pMyVariable;
static const long int* m_spkMyVariable;
void foo( long int* pMyParam ) {
long int* pMyVariable;
static const long int* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
long int* g_pliMyVar;
long int* g_pliMyVariable;
static const long int* g_spkliMyVariable;
class A {
long int* m_pliMyVariable;
static const long int* m_spkliMyVariable;
void foo( long int* pliMyParam ) {
long int* pliMyVariable;
static const long int* spkliMyVariable;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for member variables [NAMING-HN-29-3]


DESCRIPTION
For member variables use "m_" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
class CSample
{
int iSize;
};

// Violation

REPAIR
class CSample
{
int m_iSize;
};

// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for int types [NAMING-HN-30-3]


DESCRIPTION
For int variables and parameters use "n" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
int g_nmyVar;
int g_MyVariable;
static const int g_skMyVariable = 0;
class A {
int m_MyVariable;
static const int m_skMyVariable;
void foo( int MyParam ) {
int MyVariable;
static const int skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
int g_nMyVar;
int g_nMyVariable;
static const int g_sknMyVariable = 0;
class A {
int m_nMyVariable;
static const int m_sknMyVariable;
void foo( int nMyParam ) {
int nMyVariable;
static const int sknMyVariable = 0;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for int pointer, array, or reference types [NAMING-HN-31-3]


DESCRIPTION
For int pointer, array, or reference variables and parameters use "n"
prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
int* g_pnmyVar;
int* g_pMyVariable;
static const int* g_spkMyVariable;
class A {
int* m_pMyVariable;
static const int* m_spkMyVariable;
void foo( int* pMyParam ) {
int* pMyVariable;
static const int* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
int* g_pnMyVar;
int* g_pnMyVariable;
static const int* g_spknMyVariable;
class A {
int* m_pnMyVariable;
static const int* m_spknMyVariable;
void foo( int* pnMyParam ) {
int* pnMyVariable;
static const int* spknMyVariable;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for ofstream type parameters and variables [NAMING-HN-32-3]


DESCRIPTION
For ofstream type parameters and variables use "of" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
#include <fstream>
using namespace std;
ofstream NameFile;

// Violation

void foo( ofstream &rIn ) { // Violation


ofstream Filename;
// Violation
ofstream *pFilename;
// Violation
}

REPAIR
#include <fstream>
using namespace std;
ofstream ofNameFile;

// OK

void foo( ofstream &rofIn ) { // OK


ofstream ofFilename;
// OK
ofstream *pofFilename; // OK
}

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for ostream type parameters and variables [NAMING-HN-33-3]


DESCRIPTION
For ostream type parameters and variables use "os" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
#include <fstream>
using namespace std;
void foo(ostream &rOut)
{
}

// Violation

REPAIR
#include <fstream>
using namespace std;
void foo(ostream &rosOut)
{
}

// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for pointer [NAMING-HN-34-3]


DESCRIPTION
For pointers use "p" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
const int kiMAX=10;
int *iGrade;
void foo()
{
int *iMark;
char * cLetter = 0;
}

// Violation

// Violation
// Violation

REPAIR
const int kiMAX=10;
int *piGrade;
void foo()
{
int *piMark;
char * pcLetter = 0;
}

// OK

// OK
// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for reference parameters [NAMING-HN-35-3]


DESCRIPTION
For reference parameters use "r" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
void foo(const unsigned char &kucLabel)
{
}

// Violation

REPAIR
void foo(const unsigned char &rkucLabel)
{
}

// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for short int types [NAMING-HN-36-3]


DESCRIPTION
For short int variables and parameters use "si" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
short int g_simyVar;
short int g_MyVariable;
static const short int g_skMyVariable = 0;
class B {
short int m_MyVariable;
static const short int m_skMyVariable;
void foo( short int MyParam ) {
short int MyVariable;
static const short int skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
short int g_siMyVar;
short int g_siMyVariable;
static const short int g_sksiMyVariable = 0;
class A {
short int m_siMyVariable;
static const short int m_sksiMyVariable;
void foo( short int siMyParam ) {
short int siMyVariable;
static const short int sksiMyVariable = 0;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for short int pointer, array, or reference types [NAMING-HN-37-3]
DESCRIPTION
For short int pointer, array, or reference
variables and parameters use "si" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
short int* g_psimyVar;
short int* g_pMyVariable;
static const short int* g_spkMyVariable;
class B {
short int* m_pMyVariable;
static const short int* m_spkMyVariable;
void foo( short int* pMyParam ) {
short int* pMyVariable;
static const short int* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
short int* g_psiMyVar;
short int* g_psiMyVariable;
static const short int* g_spksiMyVariable;
class A {
short int* m_psiMyVariable;
static const short int* m_spksiMyVariable;
void foo( short int* psiMyParam ) {
short int* psiMyVariable;
static const short int* spksiMyVariable;

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for static variables [NAMING-HN-38-3]


DESCRIPTION
For static variables use "s" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
static int g_iMark;

// Violation

REPAIR
static int g_siMark;

// OK

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for string types [NAMING-HN-39-3]


DESCRIPTION
For string variables and parameters use "str" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
#include <string>
using namespace std;
string g_strmyVar;
string g_MyVariable;
static const string g_skMyVariable;
class A {
string m_MyVariable;
static const string m_skMyVariable;
void foo( string MyParam ) {
string MyVariable;
static const string skMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
#include <string>
using namespace std;
string g_strMyVar;
string g_strMyVariable;
static const string g_skstrMyVariable;
class A {

// OK
// OK
// OK

string m_strMyVariable;
static const string m_skstrMyVariable;
void foo( string strMyParam ) {
string strMyVariable;
static const string skstrMyVariable;
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

//
//
//
//
//

OK
OK
OK
OK
OK

Hungarian notation for string pointer, array, or reference types [NAMING-HN-40-3]


DESCRIPTION
For string pointer, array, or reference
variables and parameters use "str" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
#include <string>
using namespace std;
string* g_pstrmyVar;
string* g_pMyVariable;
static const string* g_spkMyVariable;
class A {
string* m_pMyVariable;
static const string* m_spkMyVariable;
void foo( string* pMyParam ) {
string* pMyVariable;
static const string* spkMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
#include <string>
using namespace std;
string* g_pstrMyVar;
string* g_pstrMyVariable;
static const string* g_spkstrMyVariable;

// OK
// OK
// OK

class A {
string* m_pstrMyVariable;
static const string* m_spkstrMyVariable;
void foo( string* pstrMyParam ) {
string* pstrMyVariable;
static const string* spkstrMyVariable;
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

//
//
//
//
//

OK
OK
OK
OK
OK

Hungarian notation for unsigned types [NAMING-HN-41-3]


DESCRIPTION
For unsigned types use "u" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
unsigned int g_iSize;

// Violation

void foo(unsigned char cLabel)


{
unsigned short siStudents;
}

// Violation

class CSample
{
unsigned int m_iStudent;
};

// Violation

// Violation

REPAIR
unsigned int g_uiSize;

// OK

void foo(unsigned char ucLabel) // OK


{
unsigned short usiStudents; // OK
}
class CSample
{
unsigned int m_uiStudent;

// OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for void pointer types [NAMING-HN-42-3]


DESCRIPTION
For void pointer variables and parameters use "v" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
void* g_pvmy;
void* g_pMyVariable;
static const void* g_skpMyVariable;
class A {
void* m_pMyVariable;
static const void* m_skpMyVariable;
void foo( void* pMyParam ) {
void* pMyVariable;
static const void* skpMyVariable;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
void* g_pvMyV;
void* g_pvMyVariable;
static const void* g_skpvMyVariable;
class A {
void* m_pvMyVariable;
static const void* m_skpvMyVariable;
void foo( void* pvMyParam ) {
void* pvMyVariable;
static const void* skpvMyVariable;
}

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

Hungarian notation for word types [NAMING-HN-43-3]


DESCRIPTION
For unsigned int variables and parameters use "w" prefix.
For signed int or int variables and parameters use "i" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
int g_imyVar;
int g_MyVariable;
static const int g_skMyVariable = 0;
class A {
int m_MyVariable;
static const int m_skMyVariable;
void foo( int MyParam ) {
int MyVariable;
static const int skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

unsigned int g_wmyVar2;


unsigned int g_MyVariable2;
static const unsigned int g_skMyVariable2 = 0;
class B {
unsigned int m_MyVariable;
static const unsigned int m_skMyVariable;
void foo( unsigned int MyParam ) {
unsigned int MyVariable;
static const unsigned int skMyVariable = 0;
}
};

// Violation
// Violation
// Violation
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
int g_iMyVar;
int g_iMyVariable;
static const int g_skiMyVariable = 0;
class A {
int m_iMyVariable;
static const int m_skiMyVariable;
void foo( int iMyParam ) {
int iMyVariable;
static const int skiMyVariable = 0;
}
};

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

unsigned int g_wMyVar2;


unsigned int g_wMyVariable2;
static const unsigned int g_skwMyVariable2 = 0;
class B {
unsigned int m_wMyVariable;
static const unsigned int m_skwMyVariable;
void foo( unsigned int wMyParam ) {
unsigned int wMyVariable;
static const unsigned int skwMyVariable = 0;
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

// OK
// OK
// OK
//
//
//
//
//

OK
OK
OK
OK
OK

Hungarian notation for word pointer, array, or reference types [NAMING-HN-44-3]


DESCRIPTION
For unsigned int pointer, array, or reference variables and parameters use
"w" prefix. For signed int or int pointer, array, or reference variables
and parameters use "i" prefix.

SINCE
v7.0

BENEFITS
Improves readability and maintainability.

EXAMPLE
int* g_pimyVar;
int* g_pMyVariable;
static const int* g_spkMyVariable;
class A {
int* m_pMyVariable;
static const int* m_spkMyVariable;
void foo( int* pMyParam ) {
int* pMyVariable;
static const int* spkMyVariable;
}
};

// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation

unsigned int* g_pwmyVar2;


unsigned int* g_pMyVariable2;
static const unsigned int* g_spkMyVariable2;
class B {
unsigned int* m_pMyVariable;
static const unsigned int* m_spkMyVariable;
void foo( unsigned int* pMyParam ) {
unsigned int* pMyVariable;
static const unsigned int* spkMyVariable;
}
};

// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation

REPAIR
int* g_piMyVar;
// OK
int* g_piMyVariable;
// OK
static const int* g_spkiMyVariable;
// OK
class A {
int* m_piMyVariable;
// OK
static const int* m_spkiMyVariable;
// OK
void foo( int* piMyParam ) {
// OK
int* piMyVariable;
// OK
static const int* spkiMyVariable;
// OK
}
};
unsigned int* g_pwMyVar2;
// OK
unsigned int* g_pwMyVariable2;
// OK
static const unsigned int* g_spkwMyVariable2;
// OK
class B {
unsigned int* m_pwMyVariable;
// OK
static const unsigned int* m_spkwMyVariable;
// OK
void foo( unsigned int* pwMyParam ) {
// OK
unsigned int* pwMyVariable;
// OK
static const unsigned int* spkwMyVariable;
// OK
}
};

REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html

All "#define" constants shall be in uppercase [NAMING-01-3]


DESCRIPTION
This rule checks that all "#define" constants are in uppercase.

BENEFITS
This convention will make the recognition of constants easier
and support future maintenance efforts.

EXAMPLE
#define max_value 255 // Violation

REPAIR
#define MAX_VALUE 255 // OK

REFERENCES
Recommended by ParaSoft

In an enumerated list, list members (elements) shall be in uppercase and names or tags for the
list shall be in lowercase [NAMING-02-3]
DESCRIPTION
In an enumerated list, list members (elements) shall be in uppercase.
The name or tag for the list shall be in lowercase. The members of a list
are equivalent to a defined constant, only the compiler is doing the
definition.

BENEFITS
Because members of enum are equivalent to a defined constant,
allows to keep naming convention of constants.

EXAMPLE
enum Color {
red,
blue,
green
};

// Violation
// Violation
// Violation
// Violation

REPAIR
enum color {
RED,
BLUE,
GREEN
};

// OK
// OK
// OK
// OK

REFERENCES
Motorola Coding Standards R-18

Use lowercase for file names [NAMING-03-3]


DESCRIPTION
The file name should be lowercase. It is preferred that the file name
be in lowercase and that this rule be consistently applied throughout
a development organization.

BENEFITS
Rule determine standard file names.

EXAMPLE
// filename: Test.c

// Violation

REPAIR
// filename: test.c

// OK

REFERENCES
Motorola Coding Standards G-2

Global prefixes should only be used for global variables [NAMING-04-3]


DESCRIPTION
The legibility of code is hindered by using a global prefix to a local
variable.

BENEFITS
Makes code more legible.

EXAMPLE
void foo()
{
int theVar = 0; // Violation
}

REPAIR
int theVar = 0; // OK

REFERENCES
Recommended by ParaSoft

Begin local variable names with a lowercase letters [NAMING-05-3]


DESCRIPTION
Local variable names shall be in proper lowercase.
By standardizing the appearance of variables,
the programmer will be able to more easily differentiate
user-defined variables from constants.
See also: NAMING-06, NAMING-07, NAMING-34, NAMING-35

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo() {
int Count;
};

// Violation

REPAIR
void foo() {
int count;
};

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13
2. Motorola Coding Standards R-20

Begin global variable names with a lowercase letters [NAMING-06-3]


DESCRIPTION
Global variable names shall be in proper lowercase.
By standardizing the appearance of variables,
the programmer will be able to more easily differentiate
user-defined variables from constants.
See also: NAMING-05, NAMING-07, NAMING-34, NAMING-35

BENEFITS
Rule improves readability of code.

EXAMPLE
int Count;

// Violation

REPAIR
int count;

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13

Begin member variable names with a lowercase letters [NAMING-07-3]


DESCRIPTION
Member variable names shall be in proper lowercase.
By standardizing the appearance of variables,
the programmer will be able to more easily differentiate
user-defined variables from constants.
See also: NAMING-05, NAMING-06, NAMING-34, NAMING-35

BENEFITS
Rule improves readability of code.

EXAMPLE
class A {
int Count;
};

// Violation

REPAIR
class A {
int count;
};

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13

Begin all boolean type variables with 'b' [NAMING-08-3]


DESCRIPTION
Begin all boolean type variables with 'b'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
bool Var; // Violation
}

REPAIR
void foo()
{
bool bVar; // OK
}

REFERENCES
Recommended by ParaSoft

Begin class, struct, union, enum, and typedef names with an uppercase letter [NAMING-09-3]
DESCRIPTION
Begin class, struct, union, enum, and typedef names
with an uppercase letter.
See also: NAMING-10, NAMING-11, NAMING-12

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class myClass{}; // Violation
struct myStruct{}; // Violation
union myUnion{}; // Violation
enum myEnum{ val1, val2 }; // Violation
typedef int myInt; // Violation

REPAIR
class MyClass{}; // OK
struct MyStruct{}; // OK
union MyUnion{}; // OK
enum MyEnum{ val1, val2 }; // OK
typedef int MyInt; // OK

REFERENCES
Recommended by ParaSoft

The names of abstract data types, structures, typedefs, and enumerated types are to begin
with an uppercase letter [NAMING-10-3]
DESCRIPTION
"The names of abstract data types, structures, typedefs, and enumerated
types
are to begin with an uppercase letter. A class/struct/union is said to be
an abstract data type if it does not have any public or protected member
data."
See also: NAMING-09, NAMING-11, NAMING-12

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class
struct
union
enum
typedef

myClass
myStruct
myUnion
myEnum
int

{};
{};
{};
{ val1, val2 };
myInt;

//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

MyClass
MyStruct
MyUnion
MyEnum
int

{};
{};
{};
{ val1, val2 };
MyInt;

//
//
//
//
//

OK
OK
OK
OK
OK

REPAIR
class
struct
union
enum
typedef

class myClass{
public:
void foo();
};

// OK - no abstract data type

enum {
E1, E2
};

// OK - unnamed type

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 14

The name of enumeration type shall begin with an uppercase letter and contain a suffix '_t' at
the end [NAMING-11-3]
DESCRIPTION
The rule reports a violation if the name of enumeration type does not
begin
with an uppercase letter or is not followed by a suffix '_t'.
See also: NAMING-09, NAMING-10, NAMING-12

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
enum possibleColors1_t { RED, BLUE, GREEN };
// Violation
enum PossibleColors2
{ YELLOW, BLACK, WHITE }; // Violation

REPAIR
enum PossibleColors1_t { RED, BLUE, GREEN };
// OK
enum PossibleColors2_t { YELLOW, BLACK, WHITE }; // OK

REFERENCES
Recommended by ParaSoft

The names of structures shall begin with an uppercase letter and contain a suffix '_t' at the
end [NAMING-12-3]
DESCRIPTION
The rule reports a violation if the name of struct does not begin
with an uppercase letter or is not followed by a suffix '_t'.
See also: NAMING-09, NAMING-10, NAMING-11

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
struct Str1
{
int i;
};
struct str2_t
{
int i;
};

// Violation

// Violation

REPAIR
struct Str1_t
{
int i;
};
struct Str2_t
{
int i;
};

// OK

// OK

REFERENCES
Recommended by ParaSoft

Begin constant variables with 'c' [NAMING-13-3]


DESCRIPTION
Constant variables should begin with 'c'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
const int Foo = 0;// Violation

REPAIR
const int cFoo = 0;// OK

REFERENCES
Recommended by ParaSoft

Begin class data member names with 'its' [NAMING-14-3]


DESCRIPTION
Class data member names should begin with 'its'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class Foo {
private:
int bar;// Violation
};

REPAIR
class Foo {
private:
int itsBar;// OK
};

REFERENCES
Recommended by ParaSoft

Begin all double type variable with 'd' [NAMING-15-3]


DESCRIPTION
All double type variable should begin with 'd'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
double Var;
}

// Violation

REPAIR
void foo()
{
double dVar;
}

// OK

REFERENCES
Recommended by ParaSoft

Begin all float type variables with 'f' [NAMING-16-3]


DESCRIPTION
All float type variables should begin with 'f'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
float Var;// Violation
}

REPAIR
void foo()
{
float fVar;// OK
}

REFERENCES
Recommended by ParaSoft

Begin all function names with uppercase letter [NAMING-17-3]


DESCRIPTION
All function names should begin with uppercase letter.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo();// Violation

REPAIR
void Foo();// OK

REFERENCES
Recommended by ParaSoft

Begin global variable names with 'the' [NAMING-18-3]


DESCRIPTION
All global variable names should begin with 'the'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
int global_var;

// Violation

REPAIR
int theWindows; // OK

REFERENCES
Recommended by ParaSoft

Begin all integer type variable with 'i' [NAMING-19-3]


DESCRIPTION
All integer type variable should begin with 'i'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
int Var;
}

// Violation

REPAIR
void foo()
{
int iVar;
}

// OK

REFERENCES
Recommended by ParaSoft

Functions that begin with 'is' should return boolean values [NAMING-20-3]
DESCRIPTION
Rule checks if a function that begins with 'is_' or 'is[A-Z]' return a
boolean
value.

NOTES
As boolean types are recognized typedefs which have names
begin with 'bool' (ignoring case)

BENEFITS
Improvement of legibility and clarifies what the return value means.

EXAMPLE
int
{

isPositive(int x) // Violation
return x > 0;

REPAIR
bool isPositive(int x)
{
return x > 0;
}

REFERENCES
Recommended by ParaSoft

// OK

Begin all long integer variables with 'li' [NAMING-21-3]


DESCRIPTION
All long integer variables should begin with 'li'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
long int Var;// Violation
}

REPAIR
void foo()
{
long int liVar;// OK
}

REFERENCES
Recommended by ParaSoft

Prefix a variable type 'pointer' with a 'p' character [NAMING-22-3]


DESCRIPTION
A variable type 'pointer' should be prefixed with a 'p' character.
The legibility of code is better and bug can be avoided by adding
a prefix of a type to a variable.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
int *Foo;// Violation

REPAIR
int *pFoo;// OK

REFERENCES
Recommended by ParaSoft

Begin all short integer variables with 'si' [NAMING-23-3]


DESCRIPTION
All short integer variables should begin with 'si'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
short int Var;
}

// Violation

REPAIR
void foo()
{
short int siVar;
}

// OK

REFERENCES
Recommended by ParaSoft

Begin all signed character variables with 'c' [NAMING-24-3]


DESCRIPTION
All signed character variables should begin with 'c'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
signed char Var;// Violation
}

REPAIR
void foo()
{
signed char cVar;// OK
}

REFERENCES
Recommended by ParaSoft

Begin all terminated characters string variables with 'sz' [NAMING-25-3]


DESCRIPTION
All terminated characters string variables should begin with 'sz'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
char Var[] = "\n"; // Violation
}

REPAIR
void foo()
{
char szVar[] = "\n";
}

REFERENCES

// OK

Recommended by ParaSoft

Begin all unsigned character type variables with 'uc' [NAMING-26-3]


DESCRIPTION
All unsigned character type variables should begin with 'uc'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
unsigned char Var;// Violation
}

REPAIR
void foo()
{
unsigned char ucVar;// OK
}

REFERENCES
Recommended by ParaSoft

Begin all unsigned integer type variables with 'ui' [NAMING-27-3]


DESCRIPTION
All unsigned integer type variables should begin with 'ui'.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo()
{
unsigned int Var;
}

// Violation

REPAIR
void foo()
{
unsigned int uiVar;
}

// OK

REFERENCES
Recommended by ParaSoft

Use lowercase letters for structure and union member names [NAMING-28-3]
DESCRIPTION
All structure and union members shall be lowercase proper. This convention
will
make the recognition of structure/union members easier.

BENEFITS
Makes code more readable

EXAMPLE
struct
int
int
int
};

date_foo2 {
datemonth;
DateDay;
// Violation
Dateyear;
// Violation

REPAIR
struct
int
int
int
};

date_foo1 {
dateMonth;
dateDay;
// OK
dateYear;
// OK

REFERENCES
Motorola Coding Standards R-19

Append names of non-scalar typedefs with "_t" [NAMING-29-3]


DESCRIPTION
All non-scalar typedefs shall be appended with an underscore followed
by a lowercase 't'. This convention will make the recognition of user
defined data types easier and support future maintenance efforts.

BENEFITS
Makes code more readable.

EXAMPLE
class MyClass {
int count;
};
typedef MyClass My;// Violation

REPAIR
class MyClass {
int count;
};
typedef MyClass My_t;// OK

REFERENCES
Motorola Coding Standards R-17

Implementation files in C always have the file name extension ".c" [NAMING-30-3]
DESCRIPTION
The rule reports violations on implementation files which are used in C
language and does not have '.c' extension.
See also: NAMING-38, NAMING-41

NOTES
An implementation file is defined as any file that is not included via
#include.

BENEFITS
Rule makes source code more readable.

EXAMPLE
// file.c90
// Violation
void foo( ) {}

REPAIR
// file.c
// OK
void foo( ) {}

REFERENCES
Motorola Coding Standards R-12

Do not use typenames that differ only by the use of uppercase and lowercase letters
[NAMING-31-3]
DESCRIPTION
"Do not use typenames that differ only by the use
of uppercase and lowercase letters."

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
typedef int MyInt; // Violation
typedef int myInt; // Violation

REPAIR
typedef int MyInt; // OK
typedef int myInt2; // OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rec. 14

An include file for a class should have a file name of the form <class name> + extension
[NAMING-32-3]
DESCRIPTION
"An include file for a class should have a file name of the form
<class name> + extension. Use uppercase and lowercase letters in the same
way
as in the source code. Since class names must generally be unique within
a large context, it is appropriate to utilize this characteristic when
naming
its include file."
The rule reports a violation if in a header file is declared more than one
class
or a name of header file (ignoring extension) is not the same as a name of
class
inside.
See also: PFO-03

NOTES
A header file is defined as any file that is included via #include.

BENEFITS
Makes easy to locate a class definition using a file-based tool.

EXAMPLE
// file.cpp
#include "MyClass1.hh"
#include "MyClass2.hh"
// MyClass1.hh
class MyClass{
int i;
};
// MyClass2.hh
class MyClass1{
int i;

// Violation

// Violation

};
class MyClass2{
int i;
};

REPAIR
// file.cpp
#include "MyClass1.hh"
// MyClass1.hh
class MyClass1{
int i;
};

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.2 Naming Files - Rec. 7

Do not use identifiers which begin with one or two underscores (`_' or `__') [NAMING-33-3]
DESCRIPTION
"Do not use identifiers which begin with one or two underscores (`_' or
`__')."
See also: CODSTA-92, CODSTA-93

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
void _foo( );

// Violation

REPAIR
void foo( );

// OK

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 47

Global function names should start with lowercase [NAMING-34-3]


DESCRIPTION
Global function names should start with lowercase.
See also: NAMING-05, NAMING-06, NAMING-07, NAMING-35

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void Foo( ) {}

// Violation

REPAIR
void foo( ) {}

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13

Member function names should start with lowercase [NAMING-35-3]


DESCRIPTION
Member function names should start with lowercase.
See also: NAMING-05, NAMING-06, NAMING-07, NAMING-34

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class A {
void Foo( ) {}
};

// Violation

REPAIR
class A {
void foo( ) {}
};

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13

Names of parameters in declaration and definition should be identical [NAMING-36-3]


DESCRIPTION
"If identifiers are given for any of the parameters, then the identifiers
used
in declaration and definition should be identical."

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
void foo1( int a, int b );
void foo1( int x, int y ) {}

// Violation

REPAIR
void foo1( int a, int b );
void foo1( int a, int b ) {}
void foo2( int, int );
void foo2( int x, int y ) {}

// OK

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.3 Formal Arguments - Rule 32

Include files in C++ always have the file name extension '.hh' [NAMING-37-3]
DESCRIPTION
The rule reports violations on header files which are used in C++ language
and does not have '.hh' extension.
See also: NAMING-38, NAMING-41

NOTES
A header file is defined as any file that is included via #include.

BENEFITS
Rule makes source code more readable.

EXAMPLE
// file.cpp
#include "file.hpp"
// file.hpp
extern int i;

// Violation

REPAIR
// file.cpp
#include "file.hh"
// file.hh
extern int i;

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rule 1

Implementation files in C++ always have the file name extension ".cc" [NAMING-38-3]
DESCRIPTION
The rule reports violations on implementation files which are used in C++
language and does not have '.cc' extension.
See also: NAMING-37, NAMING-41

NOTES
An implementation file is defined as any file that is not included via
#include.

BENEFITS
Rule makes source code more readable.

EXAMPLE
// file.cpp
// Violation
void foo( ) {}

REPAIR
// file.cc
void foo( ) {}

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rule 2

Inline definition files always have the file name extension ".icc" [NAMING-39-3]
DESCRIPTION
"Inline definition files - files which contain definitions of inline
functions should always have the file extension ".icc"."

BENEFITS
Rule makes source code more readable.

EXAMPLE
// file.cpp
inline int sum( int a, int b ) {
return a + b;
}

// Violation

REPAIR
// file.icc
inline int sum( int a, int b ) {
return a + b;
}

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rule 3

Only the first word of the name of a class, structure, namespace, enumeration, or typedef will
begin with an uppercase letter [NAMING-40-3]
DESCRIPTION
The first word of the name of a class, structure, namespace, enumeration,
or type created with typedef will begin with an uppercase letter.
All others letters will be lowercase.

SINCE
v7.1

NOTES
If one wants to eliminate some abbreviations from checking it can be done
by
adding abbreviation string to array abb_table in rule's python method
checkNamingConvention() e.g. abb_table = ["RGB", "IBM"]

EXCEPTIONS
The first letter of a typedef name may be in lowercase if the typedef is a
class member or
when it is used as a replacement for primitive types.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class sample_Class
{
// ...
};

// Violation

REPAIR
class Sample_class
{
// ...
};

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 50

Header files will always have a file name extension of '.h' [NAMING-41-3]
DESCRIPTION
The rule reports violations on header files which does not have '.h'
extension.
See also: PREPROC-08, NAMING-37, NAMING-38

SINCE
v7.1

NOTES
A header file is defined as any file that is included via #include.

BENEFITS
Rule makes source code more readable.

EXAMPLE
// file.cpp
#include "file.hpp"
// file.hpp
extern int i;

// Violation

REPAIR
// file.cpp
#include "file.h"
// file.h
extern int i;

REFERENCES

// OK

JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.9 Style, AV Rule 53

Identifiers for constant and enumerator values shall be lowercase [NAMING-42-2]


DESCRIPTION
Identifiers for constant and enumerator values shall be lowercase.

SINCE
v7.1

BENEFITS
Although it is an accepted convention to use uppercase letters for
constants and enumerators, it is possible for third party libraries
to replace constant/enumerator names as part of the macro substitution
process (macros are also typically represented with uppercase letters).

EXAMPLE
const int Max_pressure = 100;
// Violation
enum Switch_position {Up, down}; // Violation

REPAIR
const int max_pressure = 100;
enum Switch_position {up, down};

// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 52

Implementation files will always have a file name extension of ".cpp" [NAMING-43-3]
DESCRIPTION
If a file name extension is not ".h" (reserved for header file) than
it should be ".cpp" (implementation file).
Rule detects file name extensions different than ".cpp" and ".h".
".cpp" extension should be used for implementation files whereas
".h" are reserved for headers (rule NAMING-41).
See also: NAMING-41

SINCE
v7.1

NOTES
Rule is enabled for C++ only.

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
//file.cc

// Violation

REPAIR
//file.cpp

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 54

All letters contained in function and variable names will be composed entirely of lowercase
letters [NAMING-44-3]
DESCRIPTION
All letters contained in function and variable names will be composed
entirely of lowercase letters.

SINCE
v7.1

EXCEPTIONS
Constructors and destructors.

BENEFITS
Rule improves readability and maintainability.

EXAMPLE
class Sample_class
{
public:
int Some_function();
private:
int Some_variable;
};

// Violation
// Violation

REPAIR
class Sample_class
{
public:
int some_function();
private:
int some_variable;
};

// OK
// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 51

Identifiers will not differ by mixture of case, the underscore character, interchange of the
similarly looking letters and numbers [NAMING-45-3]
DESCRIPTION
Identifiers will not differ by:
- Only a mixture of case
- The presence/absence of the underscore character
- The interchange of the letter 'O', with the number '0' or the letter 'D'
- The interchange of the letter 'I', with the number '1' or the letter 'l'
- The interchange of the letter 'S' with the number '5'
- The interchange of the letter 'Z' with the number '2'
- The interchange of the letter 'n' with the letter 'h'.

SINCE
v7.1

BENEFITS
Rule improves readability of code.

EXAMPLE
void foo(int paramS, int param5);

// Violation

REPAIR
void foo(int param1, int param2);

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 48

The ', ", /* or // characters shall not occur in a header file name [NAMING-46-3]
DESCRIPTION
"It is undefined behaviour if the ', ", /* or // characters are used
between < and > delimiters or the ', /* or // characters are used
between the " delimiters in a header name preprocessing token."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include "fi'le.h" // Violation

REPAIR
#include "file.h"

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-4

Different identifiers shall be typographically unambiguous [NAMING-47-3]


DESCRIPTION
"Depending on the font used to display the character set, it is possible
for
certain glyphs to appear the same, even though the characters are
different.
This may lead to the developer confusing an identifier with another one.
To help reduce the chance of this, identifiers shall not differ by any
combination of:
- Only a mixture of case;
- The presence or absence of the underscore character;
- The interchange of the letter 'O', and the number '0';
- The interchange of the letter 'I', and the number '1';
- The interchange of the letter 'i', and the number '1';
- The interchange of the letter 'i', and the number 'l';
- The interchange of the letter 'I', and the letter 'l' (el);
- The interchange of the letter 'l' (el), and the number '1';
- The interchange of the letter 'S' and the number '5';
- The interchange of the letter 'Z' and the number '2';
- The interchange of the letter 'n' and the letter 'h';
- The interchange of the letter 'B' and the number '8';
- The interchange of the letter sequence 'rn' ('r' followed by 'n')
with the letter 'm'."
See also: NAMING-45.

SINCE
v7.2

BENEFITS
Rule improves readability of code.

EXAMPLE
typedef int id1_uint32; // Violation - interchange Z and 2
short id1_uint3Z;
// Violation - interchange Z and 2
void id2_foo(

// Violation - absence underscore

int id4_paramS, // Violation - interchange S and 5


int id4_param5
// Violation - interchange S and 5
){
int id3_abc; // Violation - mixed case
int id3_ABC; // Violation - mixed case
}
int id6_modern;

// Violation - interchange rn and m

void id2_foo_(){
// Violation - presence underscore
int id5_BO;
// Violation - interchange B and 8, O and 0
int id5_80;
// Violation - interchange B and 8, O and 0
int id6_modem; // Violation - interchange rn and m
}

REPAIR
typedef int id1_uint32_t; // OK
int id1_uint32_v;
// OK
void id2_foo_1(
// OK
int id4_param1, // OK
int id4_param2
// OK
){
int id3_abc_1; // OK
int id3_ABC_2; // OK
}
int id6_modern;

// OK

void id2_foo_2(){ // OK
int id5_BO_1; // OK
int id5_80_2; // OK
int foo_2_id6_modem; // OK
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-10-1

The \ character should not occur in a header file name [NAMING-48-3]


DESCRIPTION
"It is undefined behaviour if the \ character is used between < and >
delimiters or between the " delimiters in a header name preprocessing
token.
Note that this rule is only advisory, since some environments use \ as a
file
name delimiter. Compilers for these environments often support the use
of / in #include directives."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include "fi\\le.h" // Violation

REPAIR
#include "file.h"

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-5

OOP
Object Oriented
RULES
Base class copy constructor should be protected or public with smart
pointer as parameter [OOP-01-3]
Avoid slicing. Consider Clone instead of copying in base classes [OOP-023]
Class cannot inherit other class more than once unless it is virtual
inheritance [OOP-03-1]
Do not derive functions with the same name from more than one base class
[OOP-04-3]
Do not use multiple inheritance [OOP-05-2]
For multiple inheritance use virtual common base class [OOP-06-3]
Be wary about using multiple inheritance of classes that are not abstract
interfaces [OOP-07-1]
Do not directly access global data from a constructor [OOP-08-1]
Avoid the use of global objects in destructors [OOP-09-3]
Avoid using global data in member functions [OOP-10-2]
Avoid using the friend mechanism [OOP-11-3]
Protected member function shall not return non-const handles to private
class-data [OOP-12-3]
Do not redefine an inherited virtual function with a different default
parameter value [OOP-13-3]
Consider use composition instead of private inheritance [OOP-14-3]
Don't change default arguments of virtual functions [OOP-15-1]
Avoid calling virtual functions from constructors and destructors [OOP-161]
Write a using declaration to redeclare overloaded functions [OOP-17-4]
Avoid "public" data members [OOP-18-2]
Avoid 'protected' data members [OOP-19-2]
Avoid explicit cast from derived to a base class [OOP-20-3]
Use the virtual keyword if a subclass implements a virtual function [OOP21-3]
Define a virtual destructor in classes used as base classes which have
virtual functions [OOP-22-1]
If a class has virtual functions it shall have a virtual destructor [OOP23-2]
Make destructors virtual in base classes [OOP-24-1]
Avoid declaring virtual functions inline [OOP-25-3]
Never convert pointers to objects of a derived class to pointers to
objects of a virtual base class [OOP-26-3]
Declare copy assignment operator for class with reference or const members
[OOP-27-3]

A pointer to a class may not be converted to a pointer of a second class


unless the first class inherits from the second [OOP-28-4]
A pointer to an abstract class shall not be converted to a pointer of a
class that inherits from that abstract class [OOP-29-1]
Declare the copy constructor and copy assignment operator private not in
class itself, but in a specifically designed base class [OOP-30-3]
Make base class destructors public and virtual, or protected and
nonvirtual [OOP-31-1]
Never redefine an inherited nonvirtual function [OOP-32-3]
Do not redefine an inherited nonvirtual function with template parameter
[OOP-33-3]
Check for assignment to self in operator= [OOP-34-4]
Avoid casts down the inheritance hierarchy [OOP-35-5]
Public member functions shall not return non-const handles to
private/protected class-data [OOP-36-3]
Prefer composition when don't need inheritance [OOP-37-5]
If a class destructor is called and the class has virtual functions it
shall have a virtual destructor [OOP-38-1]
A stateful virtual base shall be explicitly declared in each derived class
that accesses it [OOP-39-2]
Hierarchies should be based on abstract classes [OOP-40-4]
A base class shall not be both virtual and non-virtual in the same
hierarchy [OOP-41-2]
The copy assignment operator shall be declared protected or private in an
abstract class [OOP-42-3]
A virtual function shall only be overridden by a pure virtual function if
it is itself declared as pure virtual [OOP-43-4]
There shall be no more than one definition of each virtual function on
each path through the inheritance hierarchy [OOP-44-3]
All constructors that are callable with a single argument of fundamental
type shall be declared explicit [OOP-45-3]
A copy constructor shall only initialize its base classes and the nonstatic members of the class of which it is a member [OOP-46-3]
Classes should not be derived from virtual bases [OOP-47-3]
Member data in non-POD class types shall be private [OOP-48-3]
Casts from a base class to a derived class should not be performed on
polymorphic types [OOP-49-1]
A pointer to a virtual base class shall only be cast to a pointer to a
derived class by means of dynamic_cast [OOP-50-3]
Use namespace instead of class or structure containing only static
functions [OOP-51-5]

Base class copy constructor should be protected or public with smart pointer as parameter
[OOP-01-3]
DESCRIPTION
"Sliced objects aren't good. (...)
There is a better way that portably achieves the goal of preventing
slicing
and delivers more value to boot. The more general idiomatic solution is to
make the copy constructor for base classes protected"
See also: OOP-02

EXCEPTIONS
"Some designs might require that the copy constructor of base classes
are left public. In that case, prefer passing by (smart) pointer to
passing
by reference. Passing by pointer is much less vulnerable to slicing and
unwanted temporary construction."

BENEFITS
Rule prevents using of sliced objects.
"Object slicing is automatic, invisible, and likely to bring wonderful
polymorphic designs to a screeching halt"

EXAMPLE
class A
{
public:
A(A&);

// Violation - copy constructor in public section


//
without smart pointer as parameter

};
class B
{
private:
B(B &); // Violation
};

- copy constructor in private section

REPAIR
#include <memory>
using namespace std;
class C
{
public:
C(auto_ptr<C>); // OK
};
class D
{
protected:
D(D&);
};

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 54
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid slicing. Consider Clone instead of copying in base classes [OOP-02-3]


DESCRIPTION
Sliced objects are not a good practice.
"Object slicing is automatic and invisible. In base classes, disabling
the copy constructor and copy assignment operator should be considered.
Instead should be supplied a virtual Clone member function if clients
need to make polymorphic (complete, deep) copies."
Base class with copy constructor should look like below:
class A
{
public:
A* Clone() const
{
A* p = DoClone();
assert(typeid(p) == typeid(this));
return p;
}
protected:
A(A&);
virtual A* DoClone() const = 0;
};
This rule checks:
I) if there is protected copy constructor
II) if 'DoClone' function:
- is protected
- is const
- is pure virtual
- returns pointer to the base class
III) if 'Clone' function:
- is public
- is const
- returns pointer to the base class
- has local variable initialized by 'DoClone' method
- contains assert as above
See also: OOP-01

BENEFITS

Prevents using of sliced objects.

EXAMPLE
#include <assert.h>
#include <typeinfo>
#include <memory>
using namespace std;
class A
{

// Violation - function Clone defined incorrectly

public:
A* Clone() const
{
A* p = 0;
return p;
}
protected:
A(A&);
virtual A* DoClone() const = 0;
};
class B
{

// Violation - no DoClone function

protected:
B(B&);
};

REPAIR
#include <assert.h>
#include <typeinfo>
#include <memory>
using namespace std;
class C
{
public:

// OK

C* Clone() const
{
C* p = DoClone();
assert(typeid(p) == typeid(this));
return p;
}
protected:
C(C&);
virtual C* DoClone() const = 0;
};

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 54

Class cannot inherit other class more than once unless it is virtual inheritance [OOP-03-1]
DESCRIPTION
"Multiple inheritance is more complex than single inheritance. It can lead
to
new ambiguity issues and to the need for virtual inheritance. Any time you
have an inheritance hierarchy with more than one path between a base class
and a derived class , you must confront the question of whether you want
the
data members in the base class to be replicated for each of the paths."
See also: OOP-07, OOP-06, OOP-05, OOP-04

SINCE
v7.0

BENEFITS
"Multiple inheritance just means inheriting from more than one base class,
but
it is not uncommon for MI to be found in hierarchies that have higherlevel
base classes, too. That can lead to what is sometimes known as the "deadly
MI
diamond". (..) "

EXAMPLE
class
class
class
class
class

PreBase {};
Base: public PreBase {};
Empty {};
Intermediate: public Base, public Empty
NonEmpty: public PreBase {};

{};

class MyClass:public Intermediate, public NonEmpty, public Empty{}; //


Violation
class MyClass2:public Intermediate, protected Empty {};
//
Violation

REPAIR
class
class
class
class
class

PreBase {};
Base: public virtual PreBase {};
Empty {};
Intermediate: public virtual Base, public virtual Empty
NonEmpty: public virtual PreBase {};

{};

class MyClass: public Intermediate, public NonEmpty, public Empty {};


OK
class MyClass2: public Intermediate, protected Empty {};
OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 40
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

//
//

Do not derive functions with the same name from more than one base class [OOP-04-3]
DESCRIPTION
"One of the first things to recognize is that when MI enters the
designscape,
it becomes possible to inherit the same name (e.g., function, typedef,
etc.)
from more than one base class."
Rule checks if in parent classes exist fields or methods with the same
names
that are not redefined in child class.
See also: OOP-07, OOP-06, OOP-05, OOP-03

SINCE
v7.0

BENEFITS
Rule checks possibility of ambiguity in code.

EXAMPLE
class BaseOne {
public:
int field;
};
class BaseTwo {
public:
int field;
void foo( );
};
class BaseThree {
public:
void foo( );
};
class MyClassOne: public BaseOne, public BaseTwo {};

// Violation

class MyClassTwo: public BaseTwo, public BaseThree {};

// Violation

class MyClassThree: public virtual BaseOne, public virtual BaseThree {};//


OK

REPAIR
class BaseOne {
public:
int field;
};
class BaseTwo {
public:
int field;
void foo();
};
class BaseThree {
public:
void foo();
};
class MyClassOne: public virtual BaseOne, public virtual BaseTwo {};
OK

//

class MyClassTwo: public virtual BaseTwo, public virtual BaseThree {};


OK

//

class MyClassThree: public virtual BaseOne, public virtual BaseThree {};//


OK

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 40

Do not use multiple inheritance [OOP-05-2]


DESCRIPTION
Using multiple inheritances can result in strange class hierarchies and
less
flexible code. Because in C++ there may be an arbitrary number of
instances
of a given type, it could be that direct inheritance from a class may only
be used once (see the example below). This rule detects if you use
multiple
inheritances.
See also: OOP-07, OOP-06, OOP-04, OOP-03

BENEFITS
Clarity, maintainability. Following this rule prevents ambiguity when
classes
derive from one object through multiple objects as in the "diamond of
death".

EXAMPLE
class A {};
class B {};
class C : public A, public B {}; // Violation

REPAIR
class B {};
class A : public B {}; // OK
class C : public B {}; // OK

REFERENCES
Scott Meyers,
"More Effective C++: 35 New Ways to Improve Your Programs and Designs"
Chapter: Efficiency, Item 24

For multiple inheritance use virtual common base class [OOP-06-3]


DESCRIPTION
"Multiple inheritance often leads to the need for virtual base classes.
Without
virtual base classes, if a derived class has more than one inheritance
path to
a base class, the data members of that base class are replicated within
each
derived class object, one copy for each path between the derived class and
the
base class. Such replication is almost never what programmers want, and
making
base classes virtual eliminates the replication. Virtual base classes may
incur
a cost of their own, however, because implementations of virtual base
classes
often use pointers to virtual base class parts as the means for avoiding
the
replication, and one or more of those pointers may be stored inside your
objects."
See also: OOP-07, OOP-05, OOP-04, OOP-03

SINCE
v7.0

BENEFITS
Protect from no virtual multiple inheritance.

EXAMPLE
class
class
class
class

A
B
C
D

{};
: public A {};
: public A {};
: public B, public C {};

// Violation

REPAIR
class
class
class
class

A
B
C
D

{};
: virtual public A {};
: virtual public A {};
: public B, public C {};

// OK

REFERENCES
Scott Meyers,
"More Effective C++: 35 New Ways to Improve Your Programs and Designs"
Chapter: Efficiency, Item 24

Be wary about using multiple inheritance of classes that are not abstract interfaces [OOP-071]
DESCRIPTION
"Be wary about using multiple inheritance of classes that are not abstract
interfaces. Designs that use multiple inheritance can be very expressive,
but are harder to get right and easier to get wrong. In particular,
state management is particularly hard in designs using multiple
inheritance."
See also: OOP-06, OOP-05, OOP-04, OOP-03

NOTES
Rule allows for only one direct not interface parent class.
By interface class is meant class which has no member variables
and all member functions (except for destructor) are pure virtual.

BENEFITS
"Avoiding state in abstract interfaces simplifies the entire hierarchy
design."

EXAMPLE
class A {
public:
void foo1( );
};
class B {
public:
void foo2( );
};
class C: public A, public B {
};

// Violation

REPAIR
class A {
public:
void foo1( );
};
class B {
public:
virtual void foo2( ) = 0;
};
class C: public A, public B {
};

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 36
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not directly access global data from a constructor [OOP-08-1]


DESCRIPTION
Directly accessing global data from a constructor is risky because the
global
object may not yet exist when the "other" static object is initialized.
This rule detects if you directly access global data from a constructor.
See also: OOP-09, OOP-10

EXCEPTIONS
Global constants can be used in a constructor.

BENEFITS
The order of initialization of static objects defined in different
compilation
units is not defined in the C++ language definition. Therefore, accessing
global
data from a constructor may result in reading from uninitialized objects.

EXAMPLE
int globalVar;
class A {
public:
A( ) {
b = globalVar;
}
private:
int b;
};

// Violation

REPAIR
Do not use global variables in constructors.

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 7 Classes - 7.5 Constructors and Destructors - Rec. 33

Avoid the use of global objects in destructors [OOP-09-3]


DESCRIPTION
Avoid the use of global objects in destructors.
Using global variable represents a violation of one of the basic
principles
of object-oriented programming, namely, encapsulation of data.
See also: OOP-08, OOP-10

BENEFITS
Rule prevents using global objects in destructors.

EXAMPLE
int globalVar = 0;
class A {
public:
~A( ) {
globalVar--;
}
};

// Violation

REPAIR
Do not use global objects in destructors.

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 7 Classes - 7.5 Constructors and Destructors - Rec. 33

Avoid using global data in member functions [OOP-10-2]


DESCRIPTION
Avoid using global data in member functions.
"Global references tend to break encapsulation and inhibit reuse. While
global
references may be difficult to eliminate entirely, they should be used as
sparingly as possible."
This rule applies only to the C++ programming language.
See also: OOP-08, OOP-09

BENEFITS
Prevents using global references.

EXAMPLE
int globalVar = 1;
class A {
public:
void foo( ) {
// Violation
memberVar = globalVar;
}
private:
int memberVar;
};

REPAIR
Do not use global variables in member functions.

REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, Novemeber/December, 1999, pg. 33.

Avoid using the friend mechanism [OOP-11-3]


DESCRIPTION
Using friend functions is usually a sign of an inadequate interface.
Fixing the interface, rather than granting friendship, is the best
approach.
Using the friend mechanism undermines data-hiding and encapsulation.
See also: CODSTA-CPP-52

BENEFITS
This rule detects if you use the friend mechanism.

EXAMPLE
int foo( );
class A {
friend int foo( );
};

// Violation

REPAIR
int foo( );
class A {}; // OK - No friend functions

REFERENCES
Recommended by ParaSoft

Protected member function shall not return non-const handles to private class-data [OOP-123]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a protected member function returns nonconst
reference or pointer to private class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-36

NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.

BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.

EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
int* GetI1()
{

return &_i; // Violation


}
int& GetI2()
{
return _i; // Violation
}
int * GetI3()
{
return _k; // Violation
}
private:
int _i;
int * _k;
};
class Child: public Test
{
public:
void foo()
{
*(GetI1()) = 0; // Encapsulation broken - possible to change
private class data
GetI2() = 0; // Encapsulation broken - possible to change
private class data
*(GetI3()) = 0; // Encapsulation broken - possible to change
private class data
}
};

REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()

{
return _i; // OK
}
const int * GetI3()
{
return _k; // OK
}
private:
int _i;
int * _k;
};
class Child: public Test
{
public:
void foo()
{
// *(GetI1()) = 0; // Not compilable - not possible to change
private class data
// GetI2() = 0; // Not compilable - not possible to change
private class data
// *(GetI3()) = 0; // Not compilable - not possible to change
private class data
}
};

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,

(C) 2005 Pearson Education, Inc.


Chapter: "Class Design and Inheritance", Rule 42
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 9, Rule 9-3-2
6. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not redefine an inherited virtual function with a different default parameter value [OOP-133]
DESCRIPTION
"Virtual functions are dynamically bound, but default parameters are
statically
bound. That means that you may end up invoking a virtual function defined
in a derived class but using a default parameter value from a base class"
This rule detects cases when you redefine an inherited virtual function
with a different default parameter value.

NOTES
Rule does not check:
- functions with template parameters
- non-constant default parameter values
- default parameter values with complex expressions

BENEFITS
This rule prevents misinterpretation which value is passed as default.

EXAMPLE
class Base
{
public:
virtual void func(int i = 1);
};
class Derived: public Base
{
public:
virtual void func(int i = 0);
};

REPAIR
class Base

// Violation

{
public:
virtual void func1(int i = 1);
virtual void func2(int i = 1);
};
class Derived: public Base
{
public:
virtual void func1(int i);
virtual void func2(int i = 1);
};

// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 37
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Inheritance and ObjectOriented Design", Item 38
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 95
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Consider use composition instead of private inheritance [OOP-14-3]


DESCRIPTION
"Use composition whenever you can, and use private inheritance whenever
you
must. When must you? Primarily when protected members and/or virtual
functions
enter the picture, though there's also an edge case where space concerns
can
tip the scales toward private inheritance.(...) it applies only when
you're
dealing with a class that has no data in it. Such classes have no nonstatic
data members; no virtual functions (because the existence of such
functions
adds a vptr to each object see Item 7); and no virtual base classes
(because
such base classes also incur a size overhead see Item 40)."
See also: OOP-37

SINCE
v7.0

BENEFITS
"Private inheritance means nothing during software design, only during
software implementation. And it is useful only in some edge cases."

EXAMPLE
class BaseEmpty {};
class BaseWithOnlyStaticData
{
public:
static int sd;
};
class BaseWithNonVirtualFunction

{
public:
int foo();
};
class Derived1: private BaseEmpty
{
public:
int v;
};
class Derived2: private BaseWithOnlyStaticData
{
public:
int v;
};

// Violation

// Violation

class Derived3: private BaseWithNonVirtualFunction // Violation


{
public:
int v;
};

REPAIR
class BaseEmpty {};
class BaseWithNonStaticData
{
public:
int sd;
};
class BaseWithVirtualFunction
{
public:
virtual int foo();
};
class Intermediate: public virtual BaseEmpty {};
class Derived4: private BaseWithNonStaticData
{

// OK

public:
int v;
};
class Derived5: private Intermediate
{
public:
int v;
};
class Derived6: private BaseWithVirtualFunction
{
public:
int v;
};

// OK

// OK

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 39

Don't change default arguments of virtual functions [OOP-15-1]


DESCRIPTION
"When overriding a virtual function, preserve substitutability;in
particular,
observe the function's pre- and post-conditions in the base class.
Don't change default arguments of virtual functions. Prefer explicitly
redeclaring overrides as virtual. Beware of hiding overloads in the base
class."
See also: TEMPL-06, OOP-17

BENEFITS
This rule prevents misinterpretation which value is passed as default.

EXAMPLE
class A
{
public:
virtual void foo( float x = 1 );
};
class B:public A
{
void foo( float x = 2);
};

// Violation

REPAIR
class A
{
public:
virtual void foo( float x = 1 );
};
class B:public A
{
void foo( float x = 1);
};

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid calling virtual functions from constructors and destructors [OOP-16-1]


DESCRIPTION
Inside constructors and destructors, virtual functions do not behave
"virtually." Called while executing a constructor, a virtual function will
always be resolved to the type of the constructor. The same applies to
destructors. Further, a call from a constructor to a pure virtual function
has undefined behavior.
Hence, in general, using virtual functions in constructors and destructors
is error prone, and may lead to defects ranging from memory leaks to
program crashes.
Alternatives to calling virtual functions in these circumstances most
often
include requirements to call a post-constructor function:
- document the requirements for clients of the code
- call post-constructor during the first call of a member function
- use a factory that insures the proper initialization sequence
This rule detects when you call virtual functions from constructors
and destructors.

BENEFITS
Improves code reliability and maintainability, may identify runtime bugs
in the application.

EXAMPLE
class Base {
public:
Base( ) {
init_Base( );
// Violation
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
init_Base( );
// Violation
init_Derived1( );
// Violation

this->init_Derived2( ); // Violation
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}

REPAIR
class Base {
public:
Base( ) {
Base::init_Base( );
// OK
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
Base::init_Base( );
// OK
Derived::init_Derived1( ); // OK
derived->init_Derived2( ); // OK
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 49

2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve


Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 9
3. Scott Meyers and Martin Klaus, "Examining C++ Program Analyzers",
Dr. Dobbs' Journal, the February 1997,
Chapter: "Constructors/Destructors/Assignment", Item 13
http://www.aristeia.com/ddjpaper1_frames.html
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 71.1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Write a using declaration to redeclare overloaded functions [OOP-17-4]


DESCRIPTION
"Beware of inadvertently hiding overloads in the base class.
If the base class's overloads should be visible, write a using
declaration to redeclare them in the derived class"
See also: OOP-15, TEMPL-06

EXCEPTIONS
Rule checks the nearest base classes.

BENEFITS
This rule prevents hiding overloads in base function.

EXAMPLE
class A {
public:
virtual void foo( float x );
virtual void foo( float x, float y );
};
class B : public A {
// Violation
public:
void foo( float x );
};

REPAIR
class A {
public:
virtual void foo( float x );
virtual void foo( float x, float y );
};
class B : public A {
public:

// OK

void foo( float x );


using A::foo;
};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 33

Avoid "public" data members [OOP-18-2]


DESCRIPTION
This rule detects "public" data members that could be accessed
by untrusted code.
See also: OOP-19

NOTES
Rule skips 'static const' variables.

BENEFITS
Prevents the use of "public" data members. Public data members can be
directly
accessed by any user code.
Using public accessor member functions to return data instead
will prevent unauthorized access.

EXAMPLE
class A {
public:
int iData;
};

// Violation

REPAIR
class A {
private:
int iData;
// OK
public:
const int accessiData( );
};

REFERENCES
1. Ellemtel Coding Standards

http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.1 Considerations Regarding Access Rights - Rule 22
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 41
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 22
4. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Design and Declaration", Item 20
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 67
6. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid 'protected' data members [OOP-19-2]


DESCRIPTION
This rule detects usage of "protected" data members.
See also: OOP-18

NOTES
Rule skips 'static const' variables.

BENEFITS
Prevents the use of "protected" data members. Protected data members,
while
inaccessible within their classes, can be directly accessed by other
untrusted
classes using inheritance. Using protected accessor member functions to
return
data instead will prevent unauthorized access.

EXAMPLE
class A {
protected:
int iProtectedData;
};

// Violation

REPAIR
class A {
private:
int iPrivateData;
protected:
const int accessData();
};

REFERENCES

// OK

1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve


Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 22
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 41
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.1 Considerations regarding Access Rights - Rule 22
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 67
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid explicit cast from derived to a base class [OOP-20-3]


DESCRIPTION
This rule reports violation on any explicit cast from derived to base
class.
Such casts are usually unnecessary and scope resolution operator "::" can
be used instead.
Rarely the "::" operator is not applicable. In such cases we recommend to
rewrite the code to avoid using explicit casts.
Explicit casts can be a source of serious and hard to detect errors.
For example the result of cast can be incorrect if the class definition is
not
visible (if only forward declaration is seen). At the moment of adding the
cast the class definition is visible (e.g. because appropriate header is
included), but later the #include is removed and only forward declaration
is
left. The result of cast might not be correct and program behavior
changes,
which passes unnoticed due to explicit cast.

BENEFITS
Simplifies code, protects from errors.

EXAMPLE
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = (Base *)d;
}
class Base1 {
int f();
};
class Base2 {
int f();
};

};

// Violation

class Derived1 : public Base1, public Base2 { };


int Func1() {
Derived1 *d = new Derived1();
return (static_cast<Base1*>(d))->f();
// Violation
}
class Child1 : public Base1 {};
class Child2 : public Base1 {};
void foo(Child1* c1, Child2* c2, bool b) {
Base1* p = b ? (Base1*)c1 : (Base1*)c2;
}

// Violation

REPAIR
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = d;
}

};

// OK - cast removed

class Base1 {
int f();
};
class Base2 {
int f();
};
class Derived1 : public Base1, public Base2 { };
int Func1() {
Derived1 *d = new Derived1();
return d->Base1::f();
// OK - scope operator used
}
class Child1 : public Base1 {};
class Child2 : public Base1 {};
void foo(Child1* c1, Child2* c2, bool b) {
Base1* p = 0;
if (b) {
p = c1;
// OK - code rewritten
} else {
p = c2;
// OK - code rewritten
}
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 181

Use the virtual keyword if a subclass implements a virtual function [OOP-21-3]


DESCRIPTION
Using the virtual keyword whenever a subclass implements a virtual
function
makes the code more readable, because the reader does not have to refer
back
to the base class to see that the function is virtual. This rule detects
if a subclass implements a virtual function without using a virtual
keyword.

BENEFITS
Readability, as well as more intuitive behavior for deep inheritance
hierarchies, in that functions that are virtual in a base class will
remain virtual in all inherited classes.

EXAMPLE
class A {
public:
virtual int foo( );
};
class B : public A {
public:
int foo( );
};
int B::foo() {
return 5;
}

REPAIR
class A {
public:
virtual int foo( );
};

// Violation

class B : public A {
public:
virtual int foo( );
};

// OK

int B::foo() {
return 5;
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-3-2

Define a virtual destructor in classes used as base classes which have virtual functions [OOP22-1]
DESCRIPTION
All classes which are used as base classes and which have virtual
functions
must define a virtual destructor. If a class, having virtual functions but
without virtual destructors, is used as a base class, there may be a
surprise
if pointers to the class are used. If such a pointer is assigned to an
instance
of a derived class and if delete is then used on this pointer, only the
base
class' destructor will be invoked. If the program depends on the derived
class'
destructor being invoked, the program will fail.
See also: OOP-23, OOP-24, OOP-31

BENEFITS
Define a virtual destructor in order to prevent data corruption.

EXAMPLE
class Base
// Violation
{
public:
virtual void foo( );
~Base( );
};
class Derived : public Base{};

REPAIR
class Base
// OK
{
public:
virtual void foo( );

virtual ~Base( );
};
class Derived : public Base{};

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 26
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 78

If a class has virtual functions it shall have a virtual destructor [OOP-23-2]


DESCRIPTION
Declaring virtual destructors in classes that have virtual functions
causes
the compiler to call destructors for each class from which the object
inherits.
This rule detects if you write a virtual function without also writing
a virtual destructor.
See also: OOP-22, OOP-24, OOP-31

BENEFITS
Prevents memory leaks in derived classes. A class that has virtual
functions
is intended to be used as a base class, so it should have a virtual
destructor
to guarantee that the destructor will be called when the derived object
is referenced through a pointer to the base class.

EXAMPLE
class A
// Violation
{
public:
~A( );
virtual int foo( );
};

REPAIR
class A
// OK
{
public:
virtual ~A( );
virtual int foo( );
};

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 7

Make destructors virtual in base classes [OOP-24-1]


DESCRIPTION
This rule verifies that destructors in base classes are virtual.
Declaring the destructor virtual tells the compiler that it must examine
the object being deleted to see where to start calling destructors.
See also: OOP-22, OOP-23, OOP-31

BENEFITS
Prevents using non-virtual destructor in base classes.

EXAMPLE
class BaseB
{
public:
BaseB() {}
~BaseB() {}
};

// Violation

class Derived : public BaseB


{
public:
Derived() {};
~Derived() {};
};

REPAIR
class BaseA
{
public:
BaseA() {}
virtual ~BaseA() {}
};
class Derived : public BaseA
{
public:

// OK

Derived() {};
~Derived() {};
};

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 7
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 14
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid declaring virtual functions inline [OOP-25-3]


DESCRIPTION
Most compiler implementations use virtual tables (vtbl) to implement
virtual
functions. There have to be one vtbl for a class. It have to be placed
somewhere. It's compiler dependent, but some implementations put vtbl in
object
file that contains definition of first non-inline non-pure virtual
function.
If all virtual functions are inline compiler does not have one place to
put
vtbl - it puts it in all objects that use virtualness of the class.
This increases size of object files.
The simplest solutions is not to make virtual functions inline.

NOTES
Inline destructors defined in interfaces are allowed.
By interface class is meant class which has no member variables
and all member functions (except for destructor) are pure virtual.
"All the destructor calls except for the initial resolution are resolved
statically. Without making the base class virtual destructors inline,
we cannot take advantage of this. If the hierarchy is deep and there
are many objects destructed, it make much of a difference"

EXCEPTIONS
The rule does not report violations on template functions.
Compiler must know the body of a template function. It instantiates and
puts
implementation in each object that uses it. Thus, removing inline does not
help
because virtual table is still put in each object that uses it.

BENEFITS
"The size of a class's vtbl is proportional to the number of virtual
functions
declared for that class (including those it inherits from its base

classes).
There should be only one virtual table per class, so the total amount of
space
required for virtual tables is not usually significant, but if you have a
large
number of classes or a large number of virtual functions in each class,
you may
find that the vtbls take a significant bite out of your address space.
If all virtual functions in a class are declared inline, the most
implementations
then generate a copy of the class's in every object file that uses it.
In large systems, this can lead to programs containing hundreds or
thousands
of copies of a class's!"

EXAMPLE
class A
{
public:
A(int i) : _i( i ) {}
virtual ~A( ) {}

// Violation

private:
int _i;
};

REPAIR
class A
{
public:
A( int i ) : _i( i ) {}
virtual ~A( );
// OK
private:
int _i;
};
A::~A() { }

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 24
2. Jose Lajoie and Stanley Lippman, "Standard C++ Programming:
Virtual Functions and Inlining", September 2000
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Never convert pointers to objects of a derived class to pointers to objects of a virtual base
class [OOP-26-3]
DESCRIPTION
"Never convert pointers to objects of a derived class to
pointers to objects of a virtual base class."

BENEFITS
Rule prevents casting to pointer to virtual base class.

EXAMPLE
class Base {};
class Derived: virtual Base {};
void foo( ) {
Base *b = 0;
Derived *d = 0;
b = (Base*) d;
};

// Violation

REPAIR
Do not convert pointers to objects of a derived class to
pointers to objects of a virtual base class.

REFERENCES
1. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 13 Type Conversions - Rule 45
2. ISO/DIS 26262
point 8.4.4

Declare copy assignment operator for class with reference or const members [OOP-27-3]
DESCRIPTION
"If you want to support assignment in a class containing a reference
member,
you must define the copy assignment operator yourself. Compilers behave
similarly for classes containing const members. It's not legal to modify
const
members, so compilers are unsure how to treat them during an implicitly
generated assignment function. Finally, compilers reject implicit copy
assignment operators in derived classes that inherit from base classes
declaring the copy assignment operator private. After all, compilergenerated
copy assignment operators for derived classes are supposed to handle base
class
parts, too but in doing so, they certainly can't invoke member functions
the derived class has no right to call."
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37,
MRM-40,
MRM-47, OOP-30, OOP-34

SINCE
v7.0

BENEFITS
Support assignment in a class containing a reference
member or const members.

EXAMPLE
class Sample {
public:
Sample( const int value );
const int s;
};

// Violation

REPAIR
class Sample {
public:
Sample( const int value );
Sample& operator=( Sample& );
const int s;
};

// OK

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 5

A pointer to a class may not be converted to a pointer of a second class unless the first class
inherits from the second [OOP-28-4]
DESCRIPTION
This rule detects if a pointer to a class is converted to a pointer of a
second
class when the first class does not inherit from the second.
Such "invalid" downcasting can result in wild pointers and other
disasters.
Use virtual function calls instead.
See also: MISRA2004-11_4

BENEFITS
This rule prevents memory and data corruption.

EXAMPLE
class A {};
class B {};
class D : public B {};
void
{
A
B
D
b
d
}

main( )
*a;
*b;
*d;
= (B*) a; // Violation
= (D*) b; // Violation

REPAIR
class A {};
class B {};
class D : public B {};
void main( )
{
A *a;

B *b;
D *d;
b = (B*) d; // OK
}

REFERENCES
1. ISO/DIS 26262
point 8.4.4

A pointer to an abstract class shall not be converted to a pointer of a class that inherits from
that abstract class [OOP-29-1]
DESCRIPTION
The rule reports a violation if a pointer to an abstract class is cast
to a pointer to class that inherits from that abstract class.
See also: OOP-49, OOP-50

BENEFITS
Prevents illegal casts and ensures that abstraction layer is not bypassed.

EXAMPLE
class B
{
public:
virtual int foo( ) = 0;
};
class D : public B
{
public:
int foo( );
};
void
{
B
D
d
}

main( )
*b;
*d;
= (D*) b; // Violation

REPAIR
Do not cast a pointer to an abstract class to a pointer
to a class that inherits from it.

REFERENCES
1. ISO/DIS 26262
point 8.4.4

Declare the copy constructor and copy assignment operator private not in class itself, but in a
specifically designed base class [OOP-30-3]
DESCRIPTION
"It's possible to move the link-time error up to compile time (always a
good
thing earlier error detection is better than later) by declaring the
copy
constructor and copy assignment operator private not in class itself,
but in a base class specifically designed to prevent copying.
This works, because compilers will try to generate a copy constructor
and a copy assignment operator if anybody even a member or friend
function tries to copy a class object."
See also: CODSTA-CPP-02, CODSTA-CPP-19, CODSTA-CPP-21, CODSTA-CPP-24, MRM04,
MRM-05, MRM-37, MRM-38, MRM-40, MRM-47, MRM-48, OOP-27, OOP-34

SINCE
v7.0

BENEFITS
"The compiler-generated versions of these functions will try
to call their base class counterparts, and those calls will be
rejected, because the copying operations are private in the
base class."

EXAMPLE
class HomeForSale {
public:
HomeForSale();
private:
HomeForSale(const HomeForSale&);
// Violation
HomeForSale& operator=(const HomeForSale&); // Violation
};

REPAIR
class Uncopyable {
protected:
Uncopyable() {}
~Uncopyable() {}
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
};

// OK
// OK

class HomeForSale2 : private Uncopyable { };

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 6
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 68

Make base class destructors public and virtual, or protected and nonvirtual [OOP-31-1]
DESCRIPTION
"If deletion through a pointer to a base class should be allowed,
then base class destructor must be public and virtual.
Otherwise, it should be protected and nonvirtual."
See also: OOP-22, OOP-23, OOP-24

EXCEPTIONS
Base class has no virtual functions and is not meant to be used
polymorphically.

BENEFITS
Rule prevents undefined behaviour of the delete calls on base class
pointers pointing to a derived object.

EXAMPLE
class Base {
public:
virtual int foo();
~Base(); // Violation
};
class Derived : public Base {};

REPAIR
class Base {
public:
virtual int foo();
protected:
~Base(); // OK
};
class Derived : public Base {};

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 50

Never redefine an inherited nonvirtual function [OOP-32-3]


DESCRIPTION
"Nonvirtual functions are statically bound. In essence, a nonvirtual
function will hide its corresponding base class version. Hence a single
derived class object may behave either as a base class object or as a
derived class object depending on the way in which it was accessed either
through a base class pointer/reference or a derived class
pointer/reference.
To avoid this duality in behavior, nonvirtual functions should never be
redefined."
See also: OOP-33

NOTES
This rule reports violations for functions without template parameter.
Rule OOP-33 reports violations for functions with template parameter.

BENEFITS
This rule prevents misinterpretation which function is called.

EXAMPLE
class Base
{
public:
void func1(void) {};
void func2(int x) {};
void func3(int x) {};
};
class Derived: public Base
{
public:
void func1(void) {};
void func2(int x) {};
void func3(int x) {};
};

// Violation
// Violation
// Violation

REPAIR
class Base
{
public:
virtual void func1(void) {};
virtual void func2(int x) {};
void func3(int x) {};
};
class Derived: public Base
{
public:
virtual void func1(void) {};
virtual void func2(int x) {};
void func3_renamed(int x) {};
};

// OK
// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 36
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Inheritance and Object-Oriented Design", Item 37
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 94

Do not redefine an inherited nonvirtual function with template parameter [OOP-33-3]


DESCRIPTION
"Nonvirtual functions are statically bound. In essence, a nonvirtual
function will hide its corresponding base class version. Hence a single
derived class object may behave either as a base class object or as a
derived class object depending on the way in which it was accessed either
through a base class pointer/reference or a derived class
pointer/reference.
To avoid this duality in behavior, nonvirtual functions should never be
redefined."
See also: OOP-32

NOTES
This rule reports violations for functions with template parameter.
Rule OOP-32 reports violations for functions without template parameter.

BENEFITS
This rule prevents misinterpretation which function is called.

EXAMPLE
template <class T>
{
public:
void foo1(T
void foo2(T
void foo3(T
};

class Base

i) {}
i) {}
i) {}

template <class T> class Derived : public Base <T>


{
public:
void foo1(int i) {} // Violation
void foo2(T i) {}
// Violation
void foo3(T i) {}
// Violation
};

REPAIR
template <class T> class Base
{
public:
virtual void foo1(T i) {}
virtual void foo2(T i) {}
void foo3(T i) {}
};
template <class T> class Derived :
{
public:
virtual void foo1(int i) {}
virtual void foo2(T i) {}
void foo3_renamed(T i) {}
};

public Base <T>

// OK
// OK
// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 36
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Inheritance and Object-Oriented Design", Item 37
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 94

Check for assignment to self in operator= [OOP-34-4]


DESCRIPTION
This rule checks your code for aliasing in assignment operators. Not
checking
for assignment to self in operator= can free resources that might be
needed
during the process of allocating new resources.
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37,
MRM-40,
MRM-47, OOP-27, OOP-30

BENEFITS
Checking for assignment to self may also save you a lot of work that you
would otherwise have to do to implement assignments.

EXAMPLE
class A {
public:
A( ) { }
A& operator=( A& a ) {
return *this;
}
};

// Violation

REPAIR
class A {
public:
A( ) { }
A& operator=( A& a ) {
if (&a != this) {
// ...
}
return *this;
}
};

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 11
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 17
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 81

Avoid casts down the inheritance hierarchy [OOP-35-5]


DESCRIPTION
Avoid casts down the inheritance hierarchy.
This rule detects casts from a base class pointer to a subclass pointer.

BENEFITS
Allowing casts down the inheritance hierarchy leads to maintenance
problems,
and downcasting from a base class is always illegal.

EXAMPLE
class Base {};
class Derived: public Base {};
class Derived2: public Derived {};
void foo() {
Base *pb;
Derived *pd = (Derived *) pb;
Base *pb2;
Derived *pd2 = (Derived2 *) pb2;

// Violation

// Violation

REPAIR
class Base {};
void foo() {
Base *pb0;
Base *pd0 = (Base *) pb0;
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,

Chapter: "Inheritance and Object-Oriented Design", Item 39


2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 178

Public member functions shall not return non-const handles to private/protected class-data
[OOP-36-3]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a public member function returns non-const
reference or pointer to private/protected class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-12

NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.

BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.

EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1()
{
return &_i; // Violation

}
int& GetI2()
{
return _i; // Violation
}
int * GetI3()
{
return _k; // Violation
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
*(t.GetI1()) = 0; // Encapsulation broken - possible to change private
class data
t.GetI2() = 0; // Encapsulation broken - possible to change private
class data
*(t.GetI3()) = 0; // Encapsulation broken - possible to change private
class data
}

REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()
{
return _i; // OK
}
const int * GetI3()
{

return _k; // OK
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
// *(t.GetI1()) = 0; // Not compilable - not possible to change private
class data
// t.GetI2() = 0; // Not compilable - not possible to change private
class data
// *(t.GetI3()) = 0; // Not compilable - not possible to change private
class data
}

REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.8 Member Function Return Types - Rule 29
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical

systems, Chapter 6, Section 9, Rule 9-3-2

Prefer composition when don't need inheritance [OOP-37-5]


DESCRIPTION
Inheritance is nearly the strongest relationship we can express in C++,
it's only really appropriate when there is no equivalent weaker
alternative.
"If you can express a class relationship using composition alone,
you should prefer that."
You should avoid inheritance unless you need to:
- override a virtual function
- access a protected member
See also: OOP-14

BENEFITS
Rule improves greater flexibility, compile-time insulation,
shorter compile times and less weirdness.

EXAMPLE
class Base {
public:
virtual int virtualFoo( );
int publicData;
protected:
int protectedData;
};
class DerivedA : public Base {
public:
virtual int moo();
};

// Violation

class DerivedB : public Base {


public:
virtual int virtualMoo( ) {
publicData = 0;
}
};

// Violation

REPAIR
class Base {
public:
virtual int virtualFoo( );
int publicData;
protected:
int protectedData;
};
class DerivedA : public Base {
public:
virtual int virtualFoo( );
};

// OK

class DerivedB : public Base {


public:
int virtualMoo( ) {
return protectedData;
}
};

// OK

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 34

If a class destructor is called and the class has virtual functions it shall have a virtual
destructor [OOP-38-1]
DESCRIPTION
Declaring virtual destructors in classes that have virtual functions
causes
the compiler to call destructors for each class from which the object
inherits.
If a class has virtual functions, has no virtual destructor, and class
destructor is called then the rule reports a violation message.
See also: OOP-23

SINCE
v7.1

BENEFITS
Prevents memory leaks in derived classes. A class that has virtual
functions
is intended to be used as a base class, so it should have a virtual
destructor
to guarantee that the destructor will be called when the derived object
is referenced through a pointer to the base class.

EXAMPLE
class A
{
public:
~A( );
// Violation
virtual int foo( );
};
void foo1(A* a)
{
delete a;
}

REPAIR
class A
{
public:
virtual ~A( );
// OK
virtual int foo( );
};
void foo1(A* a)
{
delete a;
}

REFERENCES
Recommended by Parasoft.

A stateful virtual base shall be explicitly declared in each derived class that accesses it [OOP39-2]
DESCRIPTION
A stateful virtual base shall be explicitly declared
in each derived class that accesses it.

SINCE
v7.1

BENEFITS
"Explicitly declaring a stateful virtual base at each level in a hierarchy
(where that base is used), documents that fact that no assumptions
can be made with respect to the exclusive use of the data contained
within the virtual base."

EXAMPLE
class
class
class
class
class
class

AA
BB
CC
DD
EE
FF

{};
: virtual AA {};
: virtual AA {};
: BB{};
// Violation
: CC{};
// Violation
: DD{};
// Violation

REPAIR
class
class
class
class
class
class

AA
BB
CC
DD
EE
FF

{};
: virtual AA {};
: virtual AA {};
: BB, virtual AA {};
// OK
: CC, virtual AA {};
// OK
: DD, EE, virtual AA {}; // OK

REFERENCES

1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.10 Classes, AV Rule 88.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Hierarchies should be based on abstract classes [OOP-40-4]


DESCRIPTION
Public inheritance hierarchy should start from abstract class.

SINCE
v7.1

BENEFITS
Hierarchies based on abstract classes tend to focus designs toward
producing clean interfaces, keep implementation details out of
interfaces, and minimize compilation dependencies while allowing
alternative implementations to coexist.

EXAMPLE
class B
{
};
class A: public B // Violation
{
};

REPAIR
class B
{
public:
virtual int foo()=0;
/* ... */
};

class A: public B // OK
{

};

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 87

A base class shall not be both virtual and non-virtual in the same hierarchy [OOP-41-2]
DESCRIPTION
A base class shall not be both virtual and non-virtual
in the same hierarchy.

SINCE
v7.1

BENEFITS
Hierarchy becomes easier to comprehend and use.

EXAMPLE
class A {};
class B : virtual A {};
class C : B, A {};

// Violation

REPAIR
class A {};
class B : virtual A {};
class C : B, virtual A {};

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 89
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-1-3
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The copy assignment operator shall be declared protected or private in an abstract class
[OOP-42-3]
DESCRIPTION
"An abstract class represents the interface part of a hierarchy.
Invoking the copy assignment operator from the top of such
a hierarchy bypasses the underlying implementation resulting
in only the base subobjects being copied."

SINCE
v7.2

NOTES
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.

BENEFITS
"Making the abstract copy assignment operator protected allows
access from the derived classes but not from outside the hierarchy.
Making the copy assignment operator private is a common idiom used
to restrict copying objects of the class type."

EXAMPLE
typedef int int32_t;
class B1
{
public:
virtual void f( ) = 0;
B1 & operator= ( B1 const & rhs );
};

REPAIR

// Violation

typedef int int32_t;


class B1
{
public:
virtual void f( ) = 0;
protected:
B1 & operator= ( B1 const & rhs );
};

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-2

A virtual function shall only be overridden by a pure virtual function if it is itself declared as
pure virtual [OOP-43-4]
DESCRIPTION
"A virtual function shall only be overridden by a pure
virtual function if it is itself declared as pure virtual."

SINCE
v7.2

BENEFITS
Rule prevents writing a code contrary to developer expectations.

EXAMPLE
class A
{
public:
virtual void foo ( );
};
class B: public A
{
public:
virtual void foo ( ) = 0; // Violation
};

REPAIR
Do not override non-pure virtual functions by pure virtual functions

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-3

There shall be no more than one definition of each virtual function on each path through the
inheritance hierarchy [OOP-44-3]
DESCRIPTION
"The main aim of this rule is clarity for maintainers and reviewers,
by ensuring that the version of a function that can be executed from
any point in a class hierarchy is unambiguous."

SINCE
v7.2

EXCEPTIONS
"Destructors may be declared virtual in multiple members of a class
hierarchy.
If a function is declared pure and defined in the same class, then that
definition is ignored for this rule."

BENEFITS
"Additionally, where classes form a diamond hierarchy, call
by dominance may occur resulting in a call to a function that
is inconsistent with developer expectations.
This rule also prevents call by dominance."

EXAMPLE
/* Examples of incorrect code */
class A
{
public:
virtual void f1 ( );
virtual void f2 ( ) { }
};
void A::f1 ( )
{
}

class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
};
void B::f2 ( )
{
}

// Violation

// Violation

REPAIR
/* Examples of
class A
{
public:
virtual
virtual
virtual
};
void A::f2 ( )
{
}

correct code */

void f1 ( );
void f2 ( ) = 0;
~A(){}

class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
virtual ~B(){}
};
void B::f2 ( )
{
}

// OK
// OK
// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-1

All constructors that are callable with a single argument of fundamental type shall be declared
explicit [OOP-45-3]
DESCRIPTION
"All constructors that are callable with a single argument
of fundamental type shall be declared explicit."

SINCE
v7.2

NOTES
The following types are fundamental: bool, char, short, int,
long, long long, float, double, long double, wchar_t.

BENEFITS
Rule prevents the constructor from being used to implicitly
convert from a fundamental type to the class type.

EXAMPLE
class C
{
public:
C ( int a ) // Violation
{
}
};

REPAIR
class C
{
public:
explicit C ( int a ) // OK
{

}
};

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-3

A copy constructor shall only initialize its base classes and the non-static members of the
class of which it is a member [OOP-46-3]
DESCRIPTION
"If a compiler implementation detects that a call to a copy constructor
is redundant, then it is permitted to omit that call, even if the copy
constructor has a side effect other than to construct a copy of the
object."
Rule reports a violation if global or static member variable is modified
within a copy constructor.

SINCE
v7.2

NOTES
Rule checks only one nested level of function call.

BENEFITS
"It is therefore important to ensure that a copy constructor does not
modify
the program state as the number of such modifications may be
indeterminate."

EXAMPLE
class A
{
public:
A ( A const & rhs )
: m_i ( rhs.m_i )
{
++m_static;
// Violation
}
private:
int m_i;
static int m_static;

};

REPAIR
Do not modify global or static member variable within a copy constructor.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-1

Classes should not be derived from virtual bases [OOP-47-3]


DESCRIPTION
"The use of virtual bases is not recommended."

SINCE
v7.2

BENEFITS
"The use of virtual base classes can introduce a number of undefined
and potentially confusing behaviours."

EXAMPLE
class B {};
class D: public virtual B {}; // Violation

REPAIR
Do not inherit from virtual base classes

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-1-1

Member data in non-POD class types shall be private [OOP-48-3]


DESCRIPTION
"Member data in non-POD class types shall be private."
non-POD class types are such for which at least one
of following conditions is met:
- is a class (classes are not PODs)
- is a struct/union that:
+ has user declared constructor
+ has private or protected non-static data member
+ has base class
+ has virtual function
+ has non-static member with type non-POD (or array of non-POD)
+ has non-static member with type reference
+ has user declared copy assignment operator
+ has user declared destructor

SINCE
v7.2

BENEFITS
"By implementing class interfaces with member functions,
the implementation retains more control over how the object
state can be modified, and helps to allow a class to be
maintained without affecting clients.

EXAMPLE
typedef signed int int32_t;
class C
{
public:
int32_t b; // Violation
protected:
int32_t c; // Violation
};

REPAIR
typedef signed int int32_t;
class C
{
private:
int32_t b; // OK
int32_t c; // OK
protected:
const int32_t access_b();
const int32_t access_c();
};

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 11, Rule 11-0-1

Casts from a base class to a derived class should not be performed on polymorphic types
[OOP-49-1]
DESCRIPTION
"A downcast occurs when a class type is converted to another class type
that is derived from that first class.
Polymorphism enables strong abstraction between the interface and
implementation
of a hierarchy. Explicit casts bypass this layer of abstraction resulting
in higher levels of coupling and dependency."
"Casting from a base class to a derived class is unsafe unless some
mechanism
is provided to ensure that the cast is legitimate."
See also: OOP-29, OOP-50

SINCE
v7.2

BENEFITS
Prevents illegal casts and ensures that abstraction layer is not bypassed.

EXAMPLE
class B
{
public:
virtual int foo( );
};
class D : public B
{
public:
int foo( );
};
void main( )
{
B *b;

D *d;
d = (D*) b; // Violation
}

REPAIR
Do not cast a pointer to a base class to a pointer to a class
that inherits from it.

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-3

A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of
dynamic_cast [OOP-50-3]
DESCRIPTION
"Since the virtualness of inheritance is not a property of a base class,
the layout of a derived class object, referenced through a virtual base
pointer, is unknown at compile time."
"Casting from a virtual base to a derived class, using any means
other than dynamic_cast has undefined behaviour.
The behaviour for dynamic_cast is defined."
See also: OOP-29, OOP-49

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviours.

EXAMPLE
// The code is not compilable with all compilers
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = static_cast<D*>(pB); // Violation
}

REPAIR

class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = dynamic_cast<D*>(pB);
}

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 179
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-2

Use namespace instead of class or structure containing only static functions [OOP-51-5]
DESCRIPTION
Use namespace instead of class or structure containing only static
functions.
Rule reports a violation if a non-template class contains only static
functions
and does not inherit from any base class.

SINCE
v7.3

BENEFITS
Rule prevents creating unnecessary objects.

EXAMPLE
class A{
static void foo(){}
};

// Violation

void foo(){
A a;
a.foo();
}

REPAIR
namespace A{
void foo(){}
};
void foo(){
A::foo();
}

// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

OPT
Optimization
RULES
Declare variables as locally as possible [OPT-01-3]
Avoid unused local variables [OPT-02-4]
Eliminate unused parameters [OPT-03-2]
Prefer canonical form of ++ and --. Prefer calling the prefix forms [OPT04-3]
Eliminate unused private member variables [OPT-05-3]
Avoid unnecessary local variables [OPT-06-4]
Prefer "a @= b" than "a = a @ b", where "@" is +, -, *, /, % [OPT-07-3]
Prefer "a @= b" than "a = a @ b", where "@" is &, |, ^, <<, >> [OPT-08-3]
Remove unnecessary '== true' in Boolean functions [OPT-09-5]
Do not declare variables in "if", "for", "while", and "do while" statement
[OPT-10-3]
If a file-level static variable is used/referenced in one function only
then include that variable in the function itself [OPT-11-3]
If a file-level static variable is used/referenced in one class only then
include that variable in the class itself [OPT-12-3]
Declare member variables in the descending size order [OPT-13-3]
Pass objects by reference instead of by value [OPT-14-3]
Consider overloading to avoid implicit type conversions [OPT-15-3]
Global function containing recursion, loops or virtual function call
should not be inlined [OPT-16-3]
Avoid inline constructors and destructors [OPT-17-3]
Member function containing recursion or loops should not be inlined [OPT18-3]
Consider using op= instead of stand-alone op [OPT-19-3]
Postpone variable definitions as long as possible [OPT-20-3]
Every switch statement shall have at least one non-empty case clause [OPT21-3]
Useless case statement shall not be permitted [OPT-22-3]
Trivial accessor and mutator functions should be inlined [OPT-23-4]
Trivial forwarding functions should be inlined [OPT-24-4]
Only functions with 1 or 2 statements should be considered candidates for
inline functions [OPT-25-4]
Variables will not be introduced until they can be initialized with
meaningful values [OPT-26-2]
The number of accessor and mutator functions should be minimized [OPT-274]
'strlen' function should not be used to check string against NULL/non-NULL
[OPT-28-3]
Redundant explicit cast to the same type is not allowed [OPT-29-4]

Every defined function shall be called at least once [OPT-30-3]


There shall be no unused parameters (named or unnamed) in non-virtual
functions [OPT-31-3]
All functions with void return type shall have external side effect(s)
[OPT-32-3]
Consider returning object by reference instead of by value [OPT-33-5]

Declare variables as locally as possible [OPT-01-3]


DESCRIPTION
"A variable ought to be declared with the smallest possible scope to
improve
the readability of the code and so that variables are not unnecessarily
allocated. When a variable that is declared at the beginning of a function
is
used somewhere in the code, it is not easy to directly see the type of
the variable.
In addition, there is a risk that such a variable is inadvertently hidden
if a local variable, having the same name, is declared in an internal
block.
Many local variables are only used in special cases which seldom occur.
If a variable is declared at the outer level,
memory will be allocated even if it is not used. In addition, when
variables
are initialized upon declaration, more efficient code is obtained than if
values are assigned when the variable is used."

BENEFITS
Rule prevents from making the program harder to understand and maintain.

EXAMPLE
void foo( ) {
int a;
{
a = 0;
}
}

// Violation

REPAIR
void foo( ) {
{
int a;
a = 0;

// OK

}
}
void fooOK1(){
int b;
if (b > 0) {
b = 10;
}
}

// OK - variable is used in condition

void fooOK1(int j){


int b;
// OK - variable is used inside two different blocks
if (j > 0) {
b = 10;
} else {
b = 20;
}
}
void fooOK2(int p){
int c;
// OK - variable is used in the same block
c = 10;
if (p > 0) {
c++;
}
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 18
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-4-1
4. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 6

5. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid unused local variables [OPT-02-4]


DESCRIPTION
This rule checks if all declared local variables are used. The rule
assumes that
a local variable is used if this variable is found inside body of function
after
definition.
See also: OPT-03, OPT-06

NOTES
Objects can perform some actions in their constructors. Even if they are
not
used later they might have done their job during creation. This rule does
not
consider such objects as "used" and will report a violation.

BENEFITS
Eliminating unused local variables increases efficiency and legibility.

EXAMPLE
class A {
public:
void displBalance();
};
void foo( ) {
A a;
}

// Violation

int func(int j) {
int i = 0; // Violation
return j;
}

REPAIR
class A {
public:
void displBalance( );
};
void foo( ) {
A a;
a.displBalance( );
}
int func(int j) {
int i = j + 1;
return i;
}

// OK

// OK

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3

Eliminate unused parameters [OPT-03-2]


DESCRIPTION
The rule reports violations on parameters that are not used inside body
of function. It is recommended to remove unused parameters or to omit
their names (possible only in C++ language).

EXCEPTIONS
The rule does not report violations on virtual functions and on functions
that are used as callback (an address of function is taken in translation
unit).
The rule does not report violations on unnamed parameters.

BENEFITS
The rule improves legibility and increases efficiency of code.

EXAMPLE
int foo(int i, int k) {
i = 5 * i;
return i;
}

REPAIR
int foo(int i) {
i = 5 * i;
return i;
}

// OK

// Exceptions
class A {
public:
virtual void foo(int a);
};

// Violation

void A::foo(int a){


}

// OK - virtual function

int callback(int a, int b){} // OK - address of function is taken


void useCb(){
int(*fp)(int, int);
fp = callback;
}
int unpar(int a, int){
a++;
return a;
}

// OK - unnamed parameter

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison Wesley, (31 Mar 1996), Item 6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer canonical form of ++ and --. Prefer calling the prefix forms [OPT-04-3]
DESCRIPTION
"In calling code, prefer using the prefix form unless you actually need
the
original value returned by the postfix version. The prefix form is
semantically
equivalent, just as much typing, and often slightly more efficient by
creating
one less object. It is not premature optimization; it is avoiding
premature
pessimization"

BENEFITS
Using rule helps to avoid potential inefficiencies resulting from a need
to
make a temporary copy of a variable or object when postfix form is used.

EXAMPLE
class SampleMemberO {
public:
SampleMemberO& operator++();
SampleMemberO& operator++(int x);
};
class SampleGlobalO {};
SampleGlobalO& operator++( SampleGlobalO& t );
SampleGlobalO& operator++( SampleGlobalO& t, int x );
void myFunction()
{
SampleMemberO obj_MemberO;
SampleGlobalO obj_GlobalO;
obj_MemberO++;
obj_GlobalO++;

// Violation
// Violation

int i=0;
i++;

// Violation

REPAIR
class SampleMemberO {
public:
int m;
SampleMemberO& operator++();
SampleMemberO& operator++(int x);
};
class SampleGlobalO {};
SampleGlobalO& operator++( SampleGlobalO& t );
SampleGlobalO& operator++( SampleGlobalO& t, int x );
void myFunction()
{
SampleMemberO obj_MemberO;
SampleGlobalO obj_GlobalO;
++obj_MemberO;
++obj_GlobalO;

// OK
// OK

int i=0;
++i;

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 28
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
3. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 6

4. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Eliminate unused private member variables [OPT-05-3]


DESCRIPTION
The rule reports a violation if a private member variable is not used in
code.
Initialization in constructor list is not detected as an use of variable.
This rule applies only to the C++ programming language.

NOTES
The rule does not report violations if a class
contains a member function with non accessible body.

BENEFITS
Eliminating unused private member variables
improves legibility and increases efficiency.

EXAMPLE
class A {
public:
A();
int foo(A
private:
int x; //
int y; //
int z; //
};

a);
Violation
Violation
Violation

// initialization is not detected as use


A::A() : x (0), y(1), z (2) {
}
int A::foo(A a){
}

REPAIR

class A {
public:
A();
int foo(A
private:
int x; //
int y; //
int z; //
};

a);
OK
OK
OK

A::A() : x (0), y(1), z (2) {


}
int A::foo(A a){
x = a.y + this->z;
return x;
}

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid unnecessary local variables [OPT-06-4]


DESCRIPTION
The rule reports a violation if a declared local variable is not used
inside
a body of function or is used only in expressions where it could be
removed
without a change of functionality.
See also: OPT-02, OPT-03

NOTES
The rule does not report violations on variables of type class/struct that
have explicitly declared constructor or destructor.

BENEFITS
Eliminating local variables that are not useful increases efficiency
and legibility of code.

EXAMPLE
class A {
};
int func(int p) {
A a;
// Violation
int i = 0; // Violation
i = p;
i++;
return p;
}

REPAIR
class A {
public:
A();

};
int func(int p) {
A a;
// OK - implicit call of constructor can cause additional
action
int i = 0; // OK
i = p;
i++;
return i;
}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3

Prefer "a @= b" than "a = a @ b", where "@" is +, -, *, /, % [OPT-07-3]


DESCRIPTION
Prefer "a @= b" than "a = a @ b", where "@" is +, -, *, /, %.
See also: OPT-08

BENEFITS
Rule improves legibility and increases efficiency of code.

EXAMPLE
void
x
x
x
x
x
}

foo( int
= x + 2;
= x - 2;
= x * 2;
= x / 2;
= x % 2;

x,
//
//
//
//
//

int y ) {
Violation
Violation
Violation
Violation
Violation

x,
//
//
//
//
//

int y ) {
OK
OK
OK
OK
OK

REPAIR
void
x
x
x
x
x
}

foo( int
+= 2;
-= 2;
*= 2;
/= 2;
%= 2;

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer "a @= b" than "a = a @ b", where "@" is &, |, ^, <<, >> [OPT-08-3]
DESCRIPTION
Prefer "a @= b" than "a = a @ b", where "@" is &, |, ^, <<, >>.
See also: OPT-07

BENEFITS
Rule improves legibility and increases efficiency of code.

EXAMPLE
void
x
x
x
x
x
}

foo( int x, int y ) {


= x & 2; // Violation
= x | 2; // Violation
= x ^ 2; // Violation
= x << 2; // Violation
= x >> 2; // Violation

REPAIR
void
x
x
x
x
x
}

foo( int
&= 2;
|= 2;
^= 2;
<<= 2;
>>= 2;

x, int y ) {
// OK
// OK
// OK
// OK
// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Remove unnecessary '== true' in Boolean functions [OPT-09-5]


DESCRIPTION
This rule checks if your code contains unnecessary "==true"s.

BENEFITS
Checking bool expressions equality with true is unnecessary.
Removing unnecessary "== true"s increases legibility and efficiency.

EXAMPLE
bool isPositive(int a);
bool foo()
{
return isPositive(5) == true;
}

// Violation

REPAIR
bool isPositive(int a);
bool foo1()
{
return isPositive(5);
}

// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not declare variables in "if", "for", "while", and "do while" statement [OPT-10-3]
DESCRIPTION
Do not declare variables in "if", "for", "while", and "do while"
statement.
Because such declaration can lead to confusion caused by hiding variable
with
the same name in more global context.

BENEFITS
Rule prevents writing ambiguous code.

EXAMPLE
int bar( int& x );
int lookup( int& x );
void foo( int x ){
if (x == 0) {
int y;
// Violation
y = bar(x);
}
for (x = 0; x < 2;x++) {
int y;
// Violation
y = lookup(x);
bar(y);
}
while (x < 0) {
int y;
// Violation
y = bar(x);
}
do {
int y;
// Violation
y = bar(x);
} while (x < 0);
}

REPAIR

int bar( int& x );


int lookup( int& x );
void foo( int x ){
int y;
// OK
if (x == 0) {
y = bar(x);
}
for (x = 0; x < 2;x++) {
y = lookup(x);
bar(y);
}
while (x < 0) {
y = bar(x);
}
do {
y = bar(x);
} while (x < 0);
}

REFERENCES
Recommended by ParaSoft

If a file-level static variable is used/referenced in one function only then include that variable
in the function itself [OPT-11-3]
DESCRIPTION
If a file-level static variable is used/referenced in one function only,
it is
better to include that variable in the function itself, as if the function
is
never called, the memory for variable will not be allocated.
See also: OPT-12

SINCE
v7.0

NOTES
In C++, global variables which are defined as a const are static by
default.
Ref: ISO14882/1998 (3.5 #3, 7.1.5.1 #2)

BENEFITS
Memory optimization and clarity of intent expression/maintainability.

EXAMPLE
static int i = 0;
const int ci = 0;

// Violation
// Violation only for C++

void clear( ) {
i = ci;
}

REPAIR
void clear( ) {
static int i = 0;

// OK

const int ci = 0;
i = ci;

// OK

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

If a file-level static variable is used/referenced in one class only then include that variable in
the class itself [OPT-12-3]
DESCRIPTION
If a file-level static variable is used/referenced in one class only,
it is better to include that variable in the class itself.
See also: OPT-11

SINCE
v7.0

BENEFITS
Memory optimization and clarity of intent expression/maintainability.

EXAMPLE
static int s;
const static int cs = 0;

// Violation
// Violation

class A
{
void foo1(int i) {
s = i + cs;
}
void foo2(int j ) {
s = j + cs;
}
};

REPAIR
class A
{
static int s;
const static int cs = 0;
void foo1(int i) {
s = i + cs;

// OK
// OK

}
void foo2(int j ) {
s = j + cs;
}
};

REFERENCES
Recommended by ParaSoft

Declare member variables in the descending size order [OPT-13-3]


DESCRIPTION
There are, of course, issues that may not be readily
apparent at the beginning of the project. For instance,
in 64-bit applications, longs and pointers are larger, which
also increases the size of a structure containing these
data types. The layout of your structure elements
determines how much space is required by the structure.
For example, a structure that contains an integer followed
by a long in a 32-bit application is 8 bytes, but a 64-bit
application adds 4 bytes of padding to the first element
of the structure to align the second element on its natural
boundary.
To minimize this padding, reorder the data structure elements
from largest to smallest. However, if data structure elements
are accessed as byte streams, you need to change your
code logic to adjust for the new order of elements in
the data structure.

SINCE
v7.0

NOTES
Following dependencies assumed for this rule:
bool < long
float < double < long double
char < short < int < reference, pointer, long
arrays and objects should be at the beginning of the list of members

BENEFITS
Rule helps to minimize memory consumption

EXAMPLE
class A {

char c;
short int si;
int i;
void* p;
long int li;

// Violation
// Violation
// Violation
// Violation

};

REPAIR
class A {
long int li;
void* p;
int i;
short int si;
char c;
};

REFERENCES
http://www.ddj.com/184406427

// OK

Pass objects by reference instead of by value [OPT-14-3]


DESCRIPTION
This rule detects where an object has been passed by value instead
of by reference. Passing objects by reference is more efficient
than passing by value because no new objects are being created
and because it avoids the "slicing problem."
See also: PB-20, PB-23, OPT-33

EXCEPTIONS
There also may be a situation where the object is so small that it would
be
more efficient to pass by value instead of by reference.
Due to C++'s type system and the fact that QString, RWCString and CString
are implicitly shared, they may be treated like ints or other basic types.

BENEFITS
Improves code consistency and runtime performance.

EXAMPLE
class A {
public:
const A violation( A a ) {
value
return a;
}
};

// Violation - passing parameter by


// Violation - returning by value

REPAIR
class A {
public:
const A& valid( const A &a ) {
return a;
}

// OK
// OK

};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 20
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 22
4. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 43
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125
7. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Consider overloading to avoid implicit type conversions [OPT-15-3]


DESCRIPTION
"Do not multiply objects beyond necessity (Occam's Razor): Implicit type
conversions provide syntactic convenience (but see Item 40). But when the
work
of creating temporary objects is unnecessary and optimization is
appropriate
(see Item 8), you can provide overloaded functions with signatures that
match
common argument types exactly and won't cause conversions."

SINCE
v7.0

BENEFITS
Rule prevents from creating temporary objects and improve optimization of
code.

EXAMPLE
class A {
public:
A(int);
bool operator==(A);
};
class C;
class B {
public:
B(C);
bool operator==(B);
};
class C {
public:
bool operator==(B);
};

// Violation

// Violation

class AR {
public:
AR(int&);
bool operator==(AR&);
};
class CR;
class BR {
public:
BR(CR&);
bool operator==(BR&);
};

// Violation

// Violation

class CR {
public:
bool operator==(BR&);
};

REPAIR
class A {
public:
A(int);
bool operator==(A);
bool operator==(int);
};
bool operator==(int, A);
class C;
class B {
public:
B(C);
bool operator==(B);
bool operator==(C);
};
class C {
public:
bool operator==(B);
};
class AR {

// OK

// OK

public:
AR(int&);
// OK
bool operator==(AR&);
bool operator==(int&);
};
bool operator==(int&, AR&);
class CR;
class BR {
public:
BR(CR&);
bool operator==(BR&);
bool operator==(CR&);
};

// OK

class CR {
public:
bool operator==(BR&);
};

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 29
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Global function containing recursion, loops or virtual function call should not be inlined [OPT16-3]
DESCRIPTION
"Limit most inlining to small, frequently called functions."
Rule disallows inlining for:
global functions with loops, global recursion functions,
global functions with virtual function calls.
See also: OPT-17, OPT-18

SINCE
v7.0

BENEFITS
"This facilitates debugging and binary upgradeability,
minimizes potential code bloat, and maximizes the chances
of greater program speed."

EXAMPLE
inline void sampleFunction( int p ) {
for (int i = 0; i < 10; i++) {
p = p + i;
}
}
inline void otherFunction( ) {
otherFunction( );
}

// Violation

// Violation

REPAIR
void sampleFunction( int p ) {
for (int i = 0; i < 10; i++) {
p = p + i;
}
}

// OK

void otherFunction( ) {
otherFunction( );
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Implementation", Item 33

Avoid inline constructors and destructors [OPT-17-3]


DESCRIPTION
"Functions which invoke other inline functions often become too complex
for the
compiler to be able to make them inline despite their apparent smallness.
This problem is especially common with constructors and destructors.
A constructor always invokes the constructors of its base classes and
member
data before executing its own code."
Rule disallows inlining for constructors and destructors.
See also: OPT-16, OPT-18

NOTES
Inline destructors defined in interfaces are allowed.
By interface class is meant class which has no member variables
and all member functions (except for destructor) are pure virtual.

BENEFITS
"This facilitates debugging and binary upgradeability, minimizes potential
code bloat, and maximizes the chances of greater program speed."

EXAMPLE
class MyClass1 {
public:
inline MyClass1( );
inline ~MyClass1( );
private:
int i;
};
class MyClass2 {
public:
MyClass2( ) {};
~MyClass2( ) {};
private:
int i;

// Violation
// Violation

// Violation
// Violation

};
class MyClass3 {
public:
MyClass3( );
~MyClass3( );
private:
int i;
};

// Violation
// Violation

inline MyClass3::MyClass3(){}
inline MyClass3::~MyClass3(){}

REPAIR
class MyClass1 {
public:
MyClass1( );
~MyClass1( );
private:
int i;
};

// OK
// OK

MyClass1::MyClass1(){}
MyClass1::~MyClass1(){}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 33
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.2 Inline Functions - Rec. 31

Member function containing recursion or loops should not be inlined [OPT-18-3]


DESCRIPTION
"Most compilers refuse to inline functions they deem too complicated
(e.g., those that contain loops or are recursive)."
Rule disallows inlining for member functions with loops
or member recursion functions.
See also: OPT-16, OPT-17

SINCE
v7.0

BENEFITS
"This facilitates debugging and binary upgradeability, minimizes potential
code bloat, and maximizes the chances of greater program speed."

EXAMPLE
class MyClass{
public:
void foo1( ) {
foo1( );
}

// Violation

inline void foo2( int i );


};
void MyClass::foo2( int i ) {
while (i > 0) {
i--;
}
}

REPAIR
class MyClass {

// Violation

public:
void foo1( ) ;
void foo2( int i );
};

// OK
// OK

void MyClass::foo1( ) {
foo1( );
}
void MyClass::foo2( int i ) {
while (i > 0) {
i--;
}
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 33

Consider using op= instead of stand-alone op [OPT-19-3]


DESCRIPTION
When you define stand-alone version of operators:
+ , - , * , / , ^, % , | , & , >> , << (e.g., operator+), the assignment
version of an operator (e.g., operator+=) should be also defined.
"Offering assignment versions of operators as well as stand-alone
versions,
you allow clients of your classes to make the difficult trade-off between
efficiency and convenience."
"You should consider using assignment versions of operators instead
of stand-alone versions whenever performance is at a premium."

BENEFITS
"Assignment versions of operators are more efficient than stand-alone
versions,
because stand-alone versions must typically return a new object, and that
costs
us the construction and destruction of a temporary. Assignment versions of
operators write to their left-hand argument, so there is no need to
generate
a temporary to hold the operator's return value."

EXAMPLE
class A {
public:
};
A& operator+( A& a, A& b );
A& operator-( A& a, A& b );
class B {
public:
B& operator+=( B& b );
};
B& operator+( B& a, B& b );
void foo( ) {
B ba, bb ,bc, bd;

// Violation
// Violation

bb = ba + bc + bd;

// Violation

REPAIR
class A {
public:
A& operator+=( A& a );
A& operator-=( A& a );
};
A& operator+( A& a, A&
A& operator-( A& a, A&
class B {
public:
B& operator+=( B& b
};
B& operator+( B& a, B&
void foo( ) {
B ba, bb ,bc, bd;
bb = ba;
bb += bc;
bb += bd;
}

b );
b );

// OK
// OK

);
b );

// OK
// OK
// OK

REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 22
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125

Postpone variable definitions as long as possible [OPT-20-3]


DESCRIPTION
"Whenever you define a variable of a type with a constructor or
destructor,
you incur the cost of construction when control reaches the variable's
definition, and you incur the cost of destruction when the variable goes
out
of scope. There's a cost associated with unused variables, so you want to
avoid them whenever you can. You're probably thinking that you never
define
unused variables, but you may need to think again. Consider the following
function:
std::string encryptPassword(const std::string& password)
{
using namespace std;
string encrypted;
if (password.length() < MinimumPasswordLength) {
throw logic_error("Password is too short");
}
//... do whatever is necessary to place an
return encrypted;
}
The object encrypted isn't completely unused in this function,
but it's unused if an exception is thrown."

SINCE
v7.0

BENEFITS
Rule improves efficiency of code.

EXAMPLE
class BaseOne {};

int main( ) {
int gc = 0;
BaseOne one;
BaseOne two;
if (gc == 0) {
return 0;
}
one = two;
return gc;
}

// Violation
// Violation

REPAIR
class BaseOne {};
int main( ) {
int gc = 0;
if (gc == 0) {
return 0;
}
BaseOne one;
BaseOne two;
one = two;
return gc;
}

// OK
// OK

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 26

Every switch statement shall have at least one non-empty case clause [OPT-21-3]
DESCRIPTION
A switch statement with no non-empty case-clauses is redundant.
If a switch statement yields a result that can be proven to be always
the same, it is highly likely that there is a programming error.
See also: MISRA2004-15_5, OPT-22

SINCE
v7.1

BENEFITS
The rule detects unneeded code and possible programming errors.

EXAMPLE
int foo(int i) {
switch(i) {
// Violation
case 1:
case 2:
default:
return 0;
}
}

REPAIR
int foo(int i) {
return 0;
}

// OK

REFERENCES
Recommended by ParaSoft

Useless case statement shall not be permitted [OPT-22-3]


DESCRIPTION
Avoid writing useless case statements.
See also: MISRA2004-15_5, OPT-21

SINCE
v7.1

BENEFITS
If an empty case statement is found it is highly likely that there
is a programming error.

EXAMPLE
int foo(int i) {
switch(i)
/* Violation */
{
case 0:
return 1;
case 1:
case 2:
default:
return 0;
}
}

REPAIR
int foo(int i) {
switch(i)
/* OK */
{
case 0:
return 1;
default:
return 0;
}

REFERENCES
Recommended by ParaSoft

Trivial accessor and mutator functions should be inlined [OPT-23-4]


DESCRIPTION
Trivial accessor and mutator functions should be inlined.
Rule reports a violation message if accessor/mutator which does not have:
- loop statements
- virtual function calls
- recursion
- more than 5 statements
is not inline.

SINCE
v7.1

EXCEPTIONS
Template methods, virtual methods.

BENEFITS
Inlining short, simple functions can save both time and space.

DRAWBACKS
Rule assumes that getter/setter (accessor/mutator) methods are methods
with names
starting from get/Get or set/Set prefix followed by underscoring or
capitalized
letter and:
- get method returns member variable or reference to it
- set method sets the value to member variable

EXAMPLE
class A
{

int m_var;
public:
int get_m_var();
void set_m_var();
};

int A::get_m_var()
{
return m_var;
}

// Violation

void A::set_m_var()
{
m_var = 0;
}

// Violation

REPAIR
class A
{
int m_var;
public:
inline int get_m_var();
inline void set_m_var();
};

inline int A::get_m_var()


{
return m_var;
}

// OK

inline void A::set_m_var()


{
m_var = 0;
}

// OK

REFERENCES

1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.13 Functions, AV Rule 122
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Trivial forwarding functions should be inlined [OPT-24-4]


DESCRIPTION
Trivial forwarding functions should be inlined.
Rule reports a violation message if a function performing
only one action i.e. calling another function is not inlined.

SINCE
v7.1

EXCEPTIONS
Constructors, destructors, template methods, virtual methods.

BENEFITS
Inlining short, simple functions can save both time and space.

EXAMPLE
int goo(int a, int b)
{
/* code */
return 1;
}
int foo(int a, int b)
{
return(goo(a,b));
}

REPAIR
int goo(int a, int b)
{
/* code */
return 1;

// Violation

}
inline int foo(int a, int b) // OK
{
return(goo(a,b));
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 124
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Only functions with 1 or 2 statements should be considered candidates for inline functions
[OPT-25-4]
DESCRIPTION
Only functions with 1 or 2 statements should be considered
candidates for inline functions.
Rule reports a violation message if inlined function has more
than 2 statements.

SINCE
v7.1

BENEFITS
Inlining complex functions may lead to significant code bloat
as well as to complicate debugging efforts.

DRAWBACKS
Each declared variable is counted as a separate statement.
int a, b, c;

// counted as 3 statements

EXAMPLE
inline int foo(int a)
{
int b = 0;
b = (b-a)/a;
return b;
}

// Violation

REPAIR
int foo(int a)
{
int b = 0;

// OK

b = (b-a)/a;
return b;
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 121
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Variables will not be introduced until they can be initialized with meaningful values [OPT-26-2]
DESCRIPTION
Variables will not be introduced until they can be initialized with
meaningful values.
Rule reports a violation message if:
- value assigned to local variable during initialization is not used (i.e.
there is
no variable usage after initialization statement and before new value
assignment)
- local variable is prematurely declared and is only used in for loop

SINCE
v7.1

NOTES
Rule is enabled for C++ only.

BENEFITS
Prevent clients from accessing variables without meaningful values.

EXAMPLE
int f(int);
void fun_1(int x)
{
int i;

int max=0;

// Violation: i is prematurely declared


// (the intent is to use i in the for loop only)
// Violation: max initialized with a dummy value

max = f(x);
for (i=0 ; i<max ; ++i)
{
}

REPAIR
int f(int);
void fun_2(int x)
{
int max = f(x);

// OK: max not introduced until meaningful


// value is available

for(int i = 0; i < max; i++) // OK


{
}
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 143
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The number of accessor and mutator functions should be minimized [OPT-27-4]


DESCRIPTION
The number of accessor and mutator functions should be minimized
to number of member variables. Rule reports a violation message
if number of setter methods or number of getter methods exceeds
number of member variables.

SINCE
v7.1

NOTES
Rule assumes that setter/getter (mutator/accessor) methods are methods
with names starting from get/Get or set/Set prefix and followed by
underscoring or capitalized letter.

BENEFITS
Numerous accessors and mutators may indicate that a class simply serves
to aggregate a collection of data rather than to embody an abstraction
with a well-defined state or invariant. In this case, a struct with
public data may be a better alternative.

EXAMPLE
class Sample // Violation
{
private:
int m_var;
public:
int get_m_var();
void set_m_var();
void set_m_var(int a);
};

REPAIR
class Sample // OK
{
private:
int m_var;
public:
int get_m_var();
void set_m_var(int a = 0);
};

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 123
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

'strlen' function should not be used to check string against NULL/non-NULL [OPT-28-3]
DESCRIPTION
Rule reports a violation if strlen() is used to check strings for
NULL/non-NULL. Using the strlen() forces the processor to walk
through the whole string what is very costly. Such checks can
be performed more efficiently if only the first character of the
string is checked for NULL/non-NULL.

SINCE
v7.2

BENEFITS
Rule improves efficiency of code.

EXAMPLE
#include <string.h>
void myFunction()
{
const char* x = "string";
int a = 1;
if (strlen(x) == 0)
a++;
}

REPAIR
#include <string.h>
void myFunction()
{
const char* x = "string";
int a = 1;

// Violation

if (x[0] == 0)
a++;

// OK

REFERENCES
Recommended by ParaSoft

Redundant explicit cast to the same type is not allowed [OPT-29-4]


DESCRIPTION
"Explicit casting between identical types is unnecessary and clutters
code.
Furthermore it can mask problems if changes are made to the code (e.g. one
of
the types changes and a conversion with possible loss of information
occurs)"

SINCE
v7.2

BENEFITS
"The use of casting should be sufficient to cause the calculations
required
to occur with the desired precision. Unnecessary casting adds the
possibility
of confusion, and may be such that its interaction with the rules of
promotion
leads to results other than those expected. Unnecessary casting may also
lead
to code which is harder to maintain, should the types of variables
change."

EXAMPLE
typedef int INT;
int someFunction1();
INT someFunction2();
void foo(int p)
{
/* ... */
p = (int)someFunction1();
p = (int)someFunction2();
}

// Violation
// Violation

REPAIR
typedef int INT;
int someFunction1();
INT someFunction2();
void foo(int p)
{
/* ... */
p = someFunction1();
p = someFunction2();
}

// OK
// OK

REFERENCES
1. Origin: Misra Guidelines - Rule 44
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 181

Every defined function shall be called at least once [OPT-30-3]


DESCRIPTION
"Every defined function shall be called at least once."
The rule reports a violation if a defined function is not used in provided
translation units

SINCE
v7.2

NOTES
The rule checks following functions:
- in C:
- static functions,
- in C++:
- non-template global static functions,
- non-template global functions in anonymous namespaces,
- non-template non-static non-operator private member functions

BENEFITS
"Functions or procedures that are not called may be symptomatic of a
serious
problem, such as missing paths."

EXAMPLE
static void foo() // Violation
{
/* ... */
}
int main()
{
return (0);
}

REPAIR
static void foo() // OK
{
/* ... */
}
int main()
{
foo();
return (0);
}

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-10

There shall be no unused parameters (named or unnamed) in non-virtual functions [OPT-31-3]


DESCRIPTION
"There shall be no unused parameters (named or unnamed) in non-virtual
functions."

SINCE
v7.2

EXCEPTIONS
"An unnamed parameter in the definition of a function that is used as
a callback does not violate this rule."

BENEFITS
"Unused function parameters are often due to design changes and can
lead to mismatched parameter lists."

EXAMPLE
int Foo(int i, int k)
{
i = 5;
return i;
}

// Violation

REPAIR
int Foo(int i)
{
i = 5;
return i;
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-11

All functions with void return type shall have external side effect(s) [OPT-32-3]
DESCRIPTION
A function which does not return a value and which does not have external
side
effects will only consume time and will not contribute to the generation
of any
outputs, which may not meet developer expectations.
The following are examples of external side effects:
- Reading or writing to a file, stream, etc.;
- Changing the value of a non local variable;
- Changing the value of an argument having reference type;
- Using a volatile object;
- Raising an exception.

SINCE
v7.2

BENEFITS
Rule prevents unnecessary time consumption.

EXAMPLE
void foo( void ) // Violation
{
int local;
local = 0;
}

REPAIR
int foo( int p ) // OK
{
int local;
local = 10*p;
/* ... */
return local;

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-8

Consider returning object by reference instead of by value [OPT-33-5]


DESCRIPTION
This rule reports a violation if an object of type class/struct/union
is returned from function by value. In this case could consider
returning this object by reference. It could more efficient than returning
by value, however could be unsafe in some cases. So, the user should check
himself the definition of function before the changes, to be sure that a
new
code is safe and more efficient than previous one.
See also: PB-20, OPT-14

SINCE
v7.2

BENEFITS
Improves code consistency and runtime performance.

EXAMPLE
class Foo{};
class A {
public:
Foo foo();
Foo goo( A& a ) {
return foo();
}
};

// Violation
// Violation

REPAIR
class A2 {
public:
Foo& foo();
Foo& goo( A2& a ) {
return foo();
}

// OK

};

REFERENCES
Recommended by ParaSoft

PB
Possible Bugs
RULES
Do not dereference pointer type expressions [PB-01-3]
Do not use assignments inside a(b), a[b], and cast [PB-02-3]
Using mixed types in ternary operator is not allowed [PB-03-3]
Return value of a function must match declared return type [PB-05-3]
Assignment operator should have operands of compatible types [PB-06-3]
Do not assign signed constants to unsigned integer variables [PB-08-3]
Operators should not return value by reference [PB-09-2]
Don't treat arrays polymorphically [PB-10-3]
Declared types of formal and actual parameters to functions must match
[PB-11-3]
Do not cast a signed char to an unsigned int [PB-12-3]
Do not call delete on non-pointers [PB-13-1]
Incorrect End-Of-String (EOS) definition [PB-14-3]
Don't assign the dividend of two integers to a floating-point type [PB-153]
Avoid assigning out-of-range value to char type [PB-16-3]
Avoid assigning out-of-range value to unsigned char type [PB-17-3]
Avoid overloading on a pointer and a numerical type [PB-18-3]
Do not create inline non-member functions that contain local static data
[PB-19-3]
Avoid slicing function arguments / return value [PB-20-3]
Properly terminate character strings [PB-21-1]
Do not use increment and decrement expressions inside a(b), a[b], and cast
[PB-22-3]
The class object should be passed by reference if the class has non-static
pointers and has no declared copy constructor [PB-23-1]
The definition of a constructor shall not contain default arguments that
produce a signature identical to that of the implicitly-declared copy
constructor [PB-24-2]
Unsigned arithmetic shall not be used [PB-25-2]
Public and protected methods should not be invoked by class constructor
[PB-26-2]
A string literal shall not be modified [PB-27-2]
The following character sequences shall not appear in header file names:
', \, /*, //, or " [PB-28-2]
The left-hand operand of a right-shift operator shall not have a negative
value [PB-29-2]
More than one 'enum' type shall not be used as a switch condition or a
label in a case statement [PB-30-3]
Do not call 'sizeof' on constants [PB-31-3]

Do not call 'sizeof' on a pointer type [PB-32-3]


Avoid implicit type conversions involving enum types [PB-33-3]
Third parameter to 'memcpy'/'strncpy'/'memmove' should not depend on
second [PB-34-3]
Assignment operators shall not be used in conditions without brackets [PB35-3]
An object's dynamic type shall not be used from the body of its
constructor or destructor [PB-36-3]
The unbounded functions of library <cstring> shall not be used [PB-37-3]
Narrow and wide string literals shall not be concatenated [PB-38-3]
A function shall not return a reference or a pointer to a parameter that
is passed by reference or const reference [PB-39-3]
A function shall not return a reference or a pointer to an automatic
variable (including parameters), defined within the function [PB-40-3]
An identifier with array type passed as a function argument shall not
decay to a pointer [PB-41-3]
An object shall not be assigned to an overlapping object [PB-42-3]
All constructors of a class should explicitly call a constructor for all
of its immediate base classes and all virtual base classes [PB-43-3]
The terminate() function shall not be called implicitly [PB-44-3]
There should be no mismatch between the '%s' or '%c' tag from format
string and its corresponding argument in 'printf' function invocation [PB45-3]
There should be no mismatch between the '%f' tag from format string and
its corresponding argument in 'printf' function invocation [PB-46-3]
There should be no mismatch between the '%i' or '%d' tag from format
string and its corresponding argument in 'printf' function invocation [PB47-3]
There should be no mismatch between the '%u' tag from format string and
its corresponding argument in 'printf' function invocation [PB-48-3]
There should be no mismatch between the '%p' tag from format string and
its corresponding argument in 'printf' function invocation [PB-49-3]
There should be no difference between the number of tags from format
string and the number of corresponding argument in 'printf' function
invocation [PB-50-3]
Pointer arithmetic shall not be applied to pointers that address variables
of non-array type [PB-51-3]

Do not dereference pointer type expressions [PB-01-3]


DESCRIPTION
Do not use dereferenced pointer type expressions.

BENEFITS
Improves safety and readability of code.

EXAMPLE
int* pFun();
void goo()
{
int* ptr;
int a, b, c;
a = *ptr++;
b = *pFun();
c = *(ptr + 5);
}

// Violation
// Violation
// Violation

REPAIR
int* pFun();
void goo()
{
int* ptr;
int* ptr2;
int a, b, c;
ptr++;
a = *ptr;

// OK

ptr2 = pFun();
b = *ptr2;

// OK

ptr2 = ptr + 5;
c = *ptr2;
// OK

REFERENCES
Recommended by ParaSoft

Do not use assignments inside a(b), a[b], and cast [PB-02-3]


DESCRIPTION
Do not use assignments inside a(b), a[b], and cast.
See also: MISRA2004-12_3 (operator sizeof), PB-22 (increment and decrement
expression)

BENEFITS
Rule increases legibility, efficiency and prevents possible bugs
related to aftereffects of unnecessary shortcuts in the code.

EXAMPLE
void foo( int i )
{
int* x;
x[ i = 0 ];
// Violation
foo( i = 0 );
// Violation
i = (int) (x = 0); // Violation
}

REPAIR
Do not use assignments inside a(b), a[b] and cast.

REFERENCES
Recommended by ParaSoft

Using mixed types in ternary operator is not allowed [PB-03-3]


DESCRIPTION
Do not use mixed types in ternary operators.

BENEFITS
Rule prevents implicit conversions which may result in a loss of
information
and improves readability and maintainability of code.

EXAMPLE
void foo( ) {
int x;
int y;
x = ((y > 5) ? 1.1 : 0.2);
}

// Violation

REPAIR
void foo( ) {
int x;
int y;
x = ((y > 5) ? 1 : 0);
}

REFERENCES
Recommended by ParaSoft

// OK

Return value of a function must match declared return type [PB-05-3]


DESCRIPTION
The rule reports a violation if a type of returned value does not match
to declared function's return type.
A violation is not reported if a function returns:
- a typedef or reference to returned type
- a type that differs only by const or volatile qualifier from returned
type
- a pointer to non-void object or to function
- a reference to base class of returned type
See also: MISRA-043, PORT-14, MISRA2004-10_1 (group), PB-06, PB-11

NOTES
In C language the type of a single character constant is 'int', but this
rule
assumes it as 'char' (similarly as is defined in C++) to prevents
confusions.

BENEFITS
Rule prevents implicit conversions which may result in a loss of
information
and improves readability and maintainability of code.

EXAMPLE
float foo1( int i ) {
return i;
}

// Violation

void* foo3(int* ptr ) {


return ptr;
// Violation
}

REPAIR
typedef int int_t;

float foo1( int i ) {


return (float)i;
}

// OK

void* foo2(int* ptr ) {


return (void*)ptr;
}

// OK

int foo3(const volatile int_t cvi ) {


return cvi;
// OK
}
int foo4(int& ref ) {
return ref;
}

REFERENCES
Recommended by ParaSoft

// OK

Assignment operator should have operands of compatible types [PB-06-3]


DESCRIPTION
The rule reports violations on assignments where types of operands are not
compatible.
As compatible type is recognized:
- the same type
- typedef to type
- reference to type
- type differs only by const or volatile qualifier
See also: MISRA-043, PORT-14, MISRA2004-10_1 (group), PB-05, PB-11

NOTES
The rule does not report violation if object or reference/pointer to
object
from derived class is assigned to reference/pointer to object from base
class.

BENEFITS
Rule prevents data loss and improves readability
and maintainability of code.

EXAMPLE
void foo1(signed int a, int& ref, int* ptr){
const short cs = 10;
unsigned int b;
float f;
void* pvoid;
b = a;
b = ref;
a = f;
pvoid = ptr;
b = cs + 10;
}

//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
typedef unsigned int u_int;
void foo1(u_int a, u_int& ref, int* ptr){
short s;
unsigned int b;
float f;
void* pvoid;
b = a;
b = ref;
a = (unsigned int)f;
pvoid = (void*)ptr;
s = 10;
}

REFERENCES
Recommended by ParaSoft

//
//
//
//
//

OK
OK
OK
OK
OK

Do not assign signed constants to unsigned integer variables [PB-08-3]


DESCRIPTION
The rule reports a violation if:
- signed constant is assigned to unsigned variable/parameter
- signed constant is passed as argument to function on position where is
declared a parameter of unsigned type
- signed constant is returned from function that has unsigned return type
Rule triggers only when a value of constant is smaller than zero.
See also: INIT-02, MISRA2004_10_1_a

SINCE
v7.0

NOTES
Rule does not report violations on initializations. In this case
violations
are reported by rule INIT-02.

BENEFITS
Rule prevents undesirable implicit casts.

EXAMPLE
void foo1(unsigned int ui){
unsigned char uc;
ui = -10;
// Violation
uc = -20;
// Violation
}
unsigned int foo2(){
foo1(-10);
return -20;
}

// Violation
// Violation

REPAIR
void foo1(signed int ui){
signed char uc;
ui = -10;
// OK
uc = -20;
// OK
}
signed int foo2(){
foo1(-10);
return -20;
}

REFERENCES
Recommended by ParaSoft

// OK
// OK

Operators should not return value by reference [PB-09-2]


DESCRIPTION
This rule detects when you return a reference where you are supposed to
return
an object. The following operators should not return value by reference:
a&b, a^b, a|b, ~a, a!=b, a<=b, a<b, a==b, a>=b, a>b, a!b, a&&b, a||b,
+a, -a, a%b, a*b, a+b, a-b, a/b

BENEFITS
Prevents returning a reference instead of an object
what may result in corrupt data or a memory leak.

EXAMPLE
class A {
public:
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
};

operator&
operator^
operator|
operator!=
operator<=
operator<
operator==
operator>=
operator>
operator&&
operator||
operator%
operator*
operator+
operatoroperator/
operator~
operator!
operator+
operator-

(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(

A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
);
);
);
);

);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation

(a & b)
(a ^ b)
(a | b)
(a != b)
(a <= b)
(a < b)
(a == b)
(a >= b)
(a > b)
(a && b)
(a || b)
(a % b)
(a * b)
(a + b)
(a - b)
(a / b)
(~a)
(!a)
(+a)
(-a)

REPAIR
class A {
public:
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
};

operator&
operator^
operator|
operator!=
operator<=
operator<
operator==
operator>=
operator>
operator&&
operator||
operator%
operator*
operator+
operatoroperator/
operator~
operator!
operator+
operator-

(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(

A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
);
);
);
);

);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK

(a & b)
(a ^ b)
(a | b)
(a != b)
(a <= b)
(a < b)
(a == b)
(a >= b)
(a > b)
(a && b)
(a || b)
(a % b)
(a * b)
(a + b)
(a - b)
(a / b)
(~a)
(!a)
(+a)
(-a)

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 21
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 23

Don't treat arrays polymorphically [PB-10-3]


DESCRIPTION
"Arrays are ill-adjusted: Treating arrays polymorphically is a gross type
error that your compiler will probably remain silent about.
Don't fall into the trap."

BENEFITS
Rule prevents leading code to grief.
Array operations almost always involve pointer arithmetic,
so arrays and polymorphism don't mix.

EXAMPLE
class BST {
public:
void cleanBSTArray(BST array[], int numElements)
{
for (int i = 1; i < numElements; ++i)
{
array[i] = array[0];
}
}
void deleteArray(BST array[])
{
delete [] array;
}
};
class BalancedBST: public BST {};
void foo()
{
BalancedBST *p;
BST BSTArray[10];
BalancedBST bBSTArray[10];
p->cleanBSTArray(bBSTArray, 10);
p->deleteArray(bBSTArray);

// Violation
// Violation

REPAIR
class BST {
public:
void cleanBSTArray(BST array[], int numElements)
{
for (int i = 1; i < numElements; ++i)
{
array[i] = array[0];
}
}
void deleteArray(BST array[])
{
delete [] array;
}
};
class BalancedBST: public BST {};
void foo()
{
BalancedBST *p;
BST BSTArray[10];
BalancedBST bBSTArray[10];
p->cleanBSTArray(BSTArray, 10);
p->deleteArray(BSTArray);

// OK
// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 100
2. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Basics", Item 3

3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS


Chapter 4.10 Classes, AV Rule 96
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Declared types of formal and actual parameters to functions must match [PB-11-3]
DESCRIPTION
The type of parameters passed to a function should be compatible
with expected types defined in prototype.

BENEFITS
Rule improves readability and maintainability and prevents errorneous
code.

EXAMPLE
void foo(int a, int b)
{
}
void goo(float a, float b)
{
foo(a, b);
// Violation
}

REPAIR
void foo(int a, int b)
{
}
void goo(int a, int b)
{
foo(a, b);
// OK
}

REFERENCES
Recommended by ParaSoft

Do not cast a signed char to an unsigned int [PB-12-3]


DESCRIPTION
The loss of sign (sign errors), can occur when converting from a signed
type
to an unsigned type. If an explicit cast is used to conversion from a
signed
char type to an unsigned int type then counterintuitively a value of
expression
could be changed.

BENEFITS
Prevents loss of sign (sign errors).

EXAMPLE
int foo( char ch )
{
unsigned int i = 10u
if((unsigned int) ch > i){
return 0;
} else {
return 1;
}
}

// Violation

REPAIR
int foo( unsigned char ch )
{
unsigned int i = 10u
if((unsigned int) ch > i){
return 0;
} else {
return 1;
}
}

// OK

REFERENCES
Recommended by ParaSoft

Do not call delete on non-pointers [PB-13-1]


DESCRIPTION
This rule checks whether you call delete on non-pointer.

BENEFITS
Prevents calling delete on non-pointer what results in an invalid operand.

EXAMPLE
class Rhino {
public:
Rhino( );
Rhino( char* );
Rhino( const char* );
operator char*( );
};
void func()
{
Rhino r;
delete( r );
}

// Violation

REPAIR
class Rhino {
public:
Rhino( );
Rhino( char* );
Rhino( const char* );
operator char*( );
};
void func()
{
Rhino *r = new Rhino();
delete r ; // OK
}

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Incorrect End-Of-String (EOS) definition [PB-14-3]


DESCRIPTION
If the end of string is defined, then should be defined as '\0'.
Do not define EOS as NULL nor as 0.

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#define EOS 0 // Violation
#undef EOS
#define EOS NULL // Violation
#undef EOS

REPAIR
#define EOS '\0' // OK
#undef EOS

REFERENCES
Recommended by ParaSoft

Don't assign the dividend of two integers to a floating-point type [PB-15-3]


DESCRIPTION
This rule checks whether you assign the dividend of two integers
to a floating-point type (float, double, long double).

BENEFITS
Rule prevents possible loss of fraction.

EXAMPLE
void func()
{
int a = 3;
int b = 4;
double d;
d = a / b;// Violation
}

REPAIR
void func()
{
int a = 3;
int b = 4;
double d;
d = ((double)a) / b;// OK
}

REFERENCES
Recommended by ParaSoft

Avoid assigning out-of-range value to char type [PB-16-3]


DESCRIPTION
This rule checks whether constants are greater than the char type's
legal range. Rule checks assigning and initialization.
Range of values of char type is -128 to 127.

BENEFITS
Prevents using illegal values as chars.

EXAMPLE
void foo()
{
char c1, c2;
char c3 = 170;
char c4 = -130;
c1 = 145;
c2 = -154;
}

//
//
//
//

Violation
Violation
Violation
Violation

//
//
//
//

OK
OK
OK
OK

REPAIR
void fooOK()
{
char c1, c2;
char c3 = 70;
char c4 = -30;
c1 = 45;
c2 = -54;
}

REFERENCES
Recommended by ParaSoft

Avoid assigning out-of-range value to unsigned char type [PB-17-3]


DESCRIPTION
This rule checks whether constants are greater than the unsigned
char type's legal range. Rule checks assigning and initialization.
Range of values of unsigned char type is 0 to 255.

BENEFITS
Prevents using illegal values as chars.

EXAMPLE
void foo()
{
unsigned char uc1, uc2 = 0;
unsigned char uc3 = 298;
// Violation
unsigned char uc4 = -15;
// Violation
uc1 = 289;
// Violation
uc2 = (-5);
// Violation
}

REPAIR
void fooOK()
{
unsigned char uc1, uc2 = 0;
unsigned char uc3 = 98;
// OK
unsigned char uc4 = 15;
// OK
uc1 = 89;
// OK
uc2 = (5);
// OK
}

REFERENCES
Recommended by ParaSoft

Avoid overloading on a pointer and a numerical type [PB-18-3]


DESCRIPTION
Calling with an argument of zero will invoke the numerical type
even though it is intuitively ambiguous.

BENEFITS
Prevents overloading on a pointer and a numerical type.

EXAMPLE
class A {
public:
void func(A a, int *i) { }
void func(A a, long i) { }// Violation
};

REPAIR
Do not overload on a pointer and a numerical type.

REFERENCES
Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 25

Do not create inline non-member functions that contain local static data [PB-19-3]
DESCRIPTION
"If you create an inline non-member function containing a local static
object,
you may end up with more than one copy of the static object in your
program!"

SINCE
v7.0

BENEFITS
Rule prevents from declaring inline local variable inside inline function.

EXAMPLE
inline int increase( ) {
static int count = 0;
count++;
return count;
}

// Violation

REPAIR
int increase( ) {
static int count = 0;
count++;
return count;
}

// OK

REFERENCES
Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Techniques", Item 26

Avoid slicing function arguments / return value [PB-20-3]


DESCRIPTION
This rule detects where an object of classs with virtual methods has been
passed or returned by value instead of by reference. Passing / returning
objects by reference is more efficient than passing by value because no
new objects are being created and because it avoids the "slicing problem."
See also: OPT-14, PB-23

SINCE
v7.0

BENEFITS
Rule prevents slicing problem, improves code consistency
and runtime performance.

EXAMPLE
class A {
public:
virtual void someFun();
const A violation( A a ) {
value
return a;
}
};

// Violation - passing parameter by

REPAIR
class A {
public:
virtual void someFun();
const A& valid( const A &a ) {
return a;
}
};

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 20
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 22
4. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 43
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 117

Properly terminate character strings [PB-21-1]


DESCRIPTION
Programmers may sometimes by mistake use a string "\0" when they indeed
intend to use the NULL character '\0' for string termination. While most
C++ compilers will not compile assigning such a string to an array
element,
C compilers allow that. This mistake, while easy to detect, may cause
memory
corruption and program crash.

SINCE
v7.0

BENEFITS
Rule prevents a possible program crash by checking proper string
termination.

EXAMPLE
struct S {
char pc[10];
}* ps = 0;
void foo( ) {
char pc[10];
ps->pc[0] = "\0";
pc[0] = "\0";
}

REPAIR
struct S {
char pc[10];
}* ps = 0;
void foo( ) {
char pc[10];

// Violation
// Violation

ps->pc[0] = '\0';
pc[0] = '\0';

// OK
// OK

REFERENCES
1. http://cwe.mitre.org/data/definitions/170.html
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not use increment and decrement expressions inside a(b), a[b], and cast [PB-22-3]
DESCRIPTION
Do not use increment and decrement expressions inside a(b), a[b], and
cast.
See also: MISRA2004-12_3 (operator sizeof), PB-02 (assign expression)

BENEFITS
Rule increases legibility, efficiency and prevents possible bugs
related to aftereffects of unnecessary shortcuts in the code.

EXAMPLE
void foo( int i )
{
int* x;
x[ i++ ];
foo( i++ );
i = (int) (x++);
}

// Violation
// Violation
// Violation

REPAIR
Do not use increment and decrement expressions inside a(b), a[b] and cast.

REFERENCES
Recommended by ParaSoft

The class object should be passed by reference if the class has non-static pointers and has
no declared copy constructor [PB-23-1]
DESCRIPTION
This rule detects where an object containing pointer member fields has
been
passed by value using a compiler-generated copy constructor. Passing such
objects by reference avoids possible problems with improper bitwise
copying
member pointers.
If a class/struct has non-static pointer member fields, has no declared
copy
constructor, and class/struct object is passed by value then the rule
reports
a violation message.
See also: OPT-14, PB-20

SINCE
v7.1

EXCEPTIONS
The rule excludes from checking objects of type class/struct which names
end with 'iterator' (e.g 'iterator', 'const_iterator',
'normal_iterator',...)

BENEFITS
Rule helps to avoid possible problems with bitwise copying member
pointers.

EXAMPLE
class A;
void foo1(A a);
class A
{

int *x;
};
void foo(void)
{
A a;
foo1(a);
}

// Violation

REPAIR
class A;
void foo1(A &a);

class A
{
int *x;
};
void foo(void)
{
A a;
foo1(a);
}

// OK - passed by reference

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 117
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The definition of a constructor shall not contain default arguments that produce a signature
identical to that of the implicitly-declared copy constructor [PB-24-2]
DESCRIPTION
The definition of a member function shall not contain default arguments
that
produce a signature identical to that of the implicitly-declared copy
constructor for the corresponding class/structure.

SINCE
v7.1

BENEFITS
If the class definition does not explicitly declare a copy constructor,
one is declared implicitly. Thus, for the class definition
class X
{
X(const X&, int);
};
a copy constructor is implicitly-declared. If the user-declared
constructor
is later defined as
X::X(const X& x, int i =0)
{
/* ... */
}
then any use of X's copy constructor is ill-formed because of the
ambiguity.

EXAMPLE
class A
{
A(const A&, int);
A(const A&);

};
A::A(const A& x, int i =0) // Violation
{
/* ... */
}

REPAIR
class A
{
A(const A&, int i=0);
A(const A&);
};
A::A(const A& x, int i) // OK
{
/* ... */
}

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Unsigned arithmetic shall not be used [PB-25-2]


DESCRIPTION
Unsigned arithmetic shall not be used.
Rule reports a violation message if type of
arithmetic expression operand is unsigned type.

SINCE
v7.1

BENEFITS
Over time, unsigned values will likely be mixed with signed values what
is error prone as it subjects operations to numerous arithmetic
conversion and integral promotion rules.

EXAMPLE
void foo(unsigned p)
{
unsigned int a = 0;
int b = 0;
b = p + a;

// Violation

REPAIR
void foo(signed p)
{
signed int a = 0;
int b = 0;
b = p + a;
}

// OK

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 163

Public and protected methods should not be invoked by class constructor [PB-26-2]
DESCRIPTION
The intent of this rule is to prevent an object from being used before it
is in
a fully initialized state. This may occur when a class constructor invokes
a public or protected method that requires the object to be fully
initialized as a pre-condition of method invocation.
Rule reports a violation message if class constructor invokes public or
protected method.
See also: OOP-16, INIT-06

SINCE
v7.1

BENEFITS
Public (and in some cases protected) methods assume object initialization
and class invariants have been established prior to invocation. Thus,
invocation of such methods during object construction risks the use of
uninitialized or invalid data since class invariants can not be guaranteed
before an object is fully constructed.

EXAMPLE
class A
{
public:
A();
void foo();
private:
int obj1;
};

A::A()
{
foo();
}

// Violation

REPAIR
Do not call public/protected methods from constructor.

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 71
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A string literal shall not be modified [PB-27-2]


DESCRIPTION
A string literal shall not be modified. Rule reports violations if
a string literal is assigned to non-const variable, parameter or
expression.

SINCE
v7.1

BENEFITS
The effect of attempting to modify a string literal is undefined.

EXAMPLE
void moo(char * p)
{
}
void foo()
{
char* c1 = "Hello";
char c2[] = "Hello";
char c3[6] = "Hello";
char* c12;
c12 = "Hello";
moo("Hello");
}

// Violation
// Violation
// Violation
// Violation
// Violation

REPAIR
void moo(const char * p)
{
}
void foo()
{

const char* c1 = "Hello";


const char c2[] = "Hello";
const char c3[6] = "Hello";
const char* c12;
c12 = "Hello";
moo("Hello");
}

// OK
// OK
// OK
// OK
// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The following character sequences shall not appear in header file names: ', \, /*, //, or " [PB-282]
DESCRIPTION
The following character sequences shall not appear in header file
names: ', \, /*, //, or ".

SINCE
v7.1

BENEFITS
If any of the character sequences ', \, /*, //, or " appears in a
header file name (i.e. <h-char-sequence>), the resulting behavior is
undefined.

EXAMPLE
#include "foo's.h" // Violation

REPAIR
#include <foo_s.h> // OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 53.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The left-hand operand of a right-shift operator shall not have a negative value [PB-29-2]
DESCRIPTION
The rule reports a violation message if as left-hand operand of rightshift
operator is used one from the following options:
- constant with a negative value
- unary operator '-' followed by parameter, variable or expression
- parameter or variable of signed type
- expression of signed type that contains parameter, variable,
dereferenced
pointer or function call of signed type

SINCE
v7.1

BENEFITS
Rule prevents implementation-defined behaviours.
"For e1 >> e2, if e1 has a signed type and a negative value, the value
of (e1 >> e2) is implementation-defined."

EXAMPLE
void foo(signed int signed_param)
{
signed int signed_variable;
int variable;
signed int* ptr_signed_variable;
signed_param >> 5;
signed_variable >> 5;
-variable >> 5;
-100 >> 5;
-100u >> 5;
*ptr_signed_variable >> 5;
}

//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation

REPAIR
void foo(unsigned int unsigned_param)
{
unsigned int unsigned_variable;
int variable;
unsigned int* ptr_signed_variable;
unsigned_param >> 5;
unsigned_variable >> 5;
(unsigned int)variable >> 5;
100 >> 5;
100u >> 5;
*ptr_signed_variable >> 5;

//
//
//
//
//
//

OK
OK
OK
OK
OK
OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

More than one 'enum' type shall not be used as a switch condition or a label in a case
statement [PB-30-3]
DESCRIPTION
Using labels with different enum types in a switch statement may cause
problem because enum members from different enum types could have the
same value but different meanings. Using different enum types in a switch
statement expression and labels may lead to unreachable code because the
two enum types could be in different ranges.
Rule reports a violation message in situations where enum type used as a
switch
expression is different than enums type used as labels in a switch
statement
or more than one enum type is used as labels in a switch statement.

SINCE
v7.2

BENEFITS
Rule prevents unreachable code and improves readability and
maintainability.

DRAWBACKS
Rule may not detect all violation cases in C code.

EXAMPLE
typedef enum E1 {EA, EB, EC} E1;
typedef enum F1 {FA = 3, FB = 4, FC = 5} F1;
void MyFunction(E1 e, int i) {
switch(e)
{
case FA :
// Violation
i++;
case FB :
// Violation

break;
default:
i++;
break;
}
}

REPAIR
typedef enum E1 {EA, EB, EC} E1;
typedef enum F1 {FA = 3, FB = 4, FC = 5} F1;
void MyFunction(E1 e, int i) {
switch(e)
{
case EA :
// OK
i++;
case EB :
// OK
break;
default:
i++;
break;
}
}

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not call 'sizeof' on constants [PB-31-3]


DESCRIPTION
Rule reports a violation if a constant is used as sizeof operator
argument.
Sizeof operator with int constant as argument returns the size of an
integer
which doesn't seem to be what programmer wanted.

SINCE
v7.2

BENEFITS
Rule prevents situations in which instead of using the actual type as
the argument of the sizeof operator, the constant is mistakenly used.

EXAMPLE
#define MAX 10
void myFunction()
{
sizeof(MAX);
sizeof(2);
}

// Violation
// Violation

REPAIR
Do not use sizeof on constants.

REFERENCES
Recommended by ParaSoft

Do not call 'sizeof' on a pointer type [PB-32-3]


DESCRIPTION
Sizeof should not be used on a pointer type.
Using the pointer of the type as the argument of the sizeof operator
makes the sizeof operator return the size of pointer
(which is 4 in a 32-bit platform).
See also: MRM-45

SINCE
v7.2

BENEFITS
Rule prevents situations in which instead of using the actual type as the
argument of the sizeof operator, the pointer of the type is mistakenly
used.

EXAMPLE
typedef int * pint;
void myFunction(int* ptr_a)
{
pint ptr_b;
sizeof(ptr_a);
sizeof(ptr_b);
sizeof(pint);
sizeof(int *);

//
//
//
//

Violation
Violation
Violation
Violation

}
void mySndFunction(char tab10[10], char tabX[], char * ptr)
{
sizeof tab10;
// Violation
sizeof tabX;
// Violation
sizeof ptr;
// Violation
}

REPAIR
Do not use sizeof on pointers.

REFERENCES
1. ISO/DIS 26262
point 8.4.4

Avoid implicit type conversions involving enum types [PB-33-3]


DESCRIPTION
Implicit conversions between:
* enum and not enum types
* enum and different enum types
are not allowed.

SINCE
v7.2

BENEFITS
Prevents depending on the value of enum constant which can change

EXAMPLE
enum ABC0{A0, B0, C0};
void foo1(int arg1){}
int foo(int p)
{
ABC0 x;
int i = x; // Violation
foo1(x);
// Violation
return x; // Violation
}

REPAIR
enum ABC0{A0, B0, C0};
void foo1(int arg1){}
int foo(int p)
{
ABC0 x;

int i = (int)x; // OK
foo1((int)x);
// OK
return (int)x; // OK
}

REFERENCES
1. ISO/DIS 26262
point 8.4.4

Third parameter to 'memcpy'/'strncpy'/'memmove' should not depend on second [PB-34-3]


DESCRIPTION
Rule reports a violation message if a third parameter
of 'memcpy', 'memmove', or 'strncpy' function depends on a second.

SINCE
v7.2

BENEFITS
Rule prevents undefined behavior.

EXAMPLE
#include <string.h>
void foo(void)
{
const int array1[10] = {0,1,2,3,4,5,6,7,8,9};
int array2[10];
memcpy ( array2, array1, sizeof(array1)); // Violation
}

REPAIR
#include <string.h>
void foo(void)
{
const int array1[10] = {0,1,2,3,4,5,6,7,8,9};
int array2[10];
memcpy ( array2, array1, sizeof(array2)); // OK
}

REFERENCES
Recommended by ParaSoft

Assignment operators shall not be used in conditions without brackets [PB-35-3]


DESCRIPTION
Assignment operators shall not be used in conditions without brackets.
Missing the brackets causes that only one branch is executed and the
assignment may lead to unexpected program behavior.
See also: MISRA2004-13_1

SINCE
v7.2

BENEFITS
Rule prevents unexpected program behavior.

EXAMPLE
class A
{
void foo();
};
void A::foo()
{
int i = 1;
int j = 0;
if(i = j)j++;
}

REPAIR
class A
{
void foo();
};
void A::foo()
{

// Violation

int i = 1;
int j = 0;
if( (i = j) )j++;

// OK

REFERENCES
Recommended by ParaSoft

An object's dynamic type shall not be used from the body of its constructor or destructor [PB36-3]
DESCRIPTION
"During construction and destruction of an object, its final type
may be different to that of the completely constructed object."
"Member functions (including virtual member functions) can be called for
an
object under construction. Similarly, an object under construction can be
the
operand of the typeid operator or of a dynamic_cast. However, if these
operations are performed in a ctor-initializer (or in a function called
directly or indirectly from a ctor-initializer) before all the meminitializers
for base classes have completed, the result of the operation is
undefined."

SINCE
v7.2

BENEFITS
"The result of using an object's dynamic type in a constructor or
destructor may not be consistent with developer expectations."

EXAMPLE
/* Examples of incorrect code */
#include <typeinfo>
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
typeid ( B2 );
// Violation
foo ( );
// Violation
dynamic_cast< B2* > ( this ); // Violation

}
};

REPAIR
/* Examples of correct code */
#include <typeinfo>
class B1
{
public:
B1 ( )
{
typeid ( B1 ); // OK - B1 not polymorphic
}
};
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
B2::foo ( );
// OK - not a virtual call
}
};

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-1
2. ISO/DIS 26262
point 8.4.4

The unbounded functions of library <cstring> shall not be used [PB-37-3]


DESCRIPTION
"The strcpy, strcmp, strcat, strchr, strspn, strcspn, strpbrk, strrchr,
strstr,
strtok and strlen functions within the <cstring> library can read or write
beyond the end of a buffer, resulting in undefined behaviour."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strcpy ( array, pChar ); // Violation
}

REPAIR
/* Ideally, a safe string handling library should be used.
Use of bounded functions (e.g. strncpy) is also possible. */
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strncpy ( array, pChar, 10 ); // OK
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Narrow and wide string literals shall not be concatenated [PB-38-3]


DESCRIPTION
Concatenation of wide and narrow string literals leads to undefined
behaviour.

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
wchar_t array[] = "Hello" L"World";

// Violation

REPAIR
wchar_t array[] = L"Hello" L"World";

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-5

A function shall not return a reference or a pointer to a parameter that is passed by reference
or const reference [PB-39-3]
DESCRIPTION
"A function shall not return a reference or a pointer to a parameter that
is
passed by reference or const reference. It is implementation-defined
behaviour
whether the reference parameter is a temporary object or a reference to
the
parameter. If the implementation uses a local copy (temporary object),
this
will be destroyed when the function returns. Any attempt to use such an
object
after its destruction will lead to undefined behaviour."

SINCE
v7.2

BENEFITS
Rule prevents non-deterministic behaviour.

EXAMPLE
int* foo2 ( int& x )
{
return ( &x );
}

// Violation

REPAIR
Do not return a reference or a pointer to a parameter that is passed by
reference or const reference

REFERENCES

MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-3

A function shall not return a reference or a pointer to an automatic variable (including


parameters), defined within the function [PB-40-3]
DESCRIPTION
"A function shall not return a reference or a pointer to an automatic
variable
(including parameters), defined within the function."

SINCE
v7.2

BENEFITS
"Automatic variables are destroyed at the end of the function call.
Returning a reference or pointer to such a variable allows it to be used
after its destruction, leading to undefined behaviour."

EXAMPLE
int* foo( ) {
int i;
return &i; // Violation
}
int& bar( ) {
int i;
return i; // Violation
}

REPAIR
int foo( ) {
int i = 0;
return i; // OK
}
int bar( ) {
int i = 0;

return i;

// OK

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-1

An identifier with array type passed as a function argument shall not decay to a pointer [PB41-3]
DESCRIPTION
"When a variable with array type decays to a pointer, its bounds are
lost."

SINCE
v7.2

BENEFITS
"If a design requires arrays of different lengths, then a class should
be used to encapsulate the array objects and so ensure that the
dimensionality
is maintained."

EXAMPLE
typedef int int32_t;
void f1( int32_t p[ 10 ] );
void f2( int32_t *p );
void b ()
{
int32_t a[ 10 ];
f1( a ); // Violation
f2( a ); // Violation
}

REPAIR
typedef int int32_t;
void f1( int32_t ( &p )[ 10 ] );

void b ()
{
int32_t a[ 10 ];
f1( a );
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-12

An object shall not be assigned to an overlapping object [PB-42-3]


DESCRIPTION
"An object shall not be assigned to an overlapping object."
Rule detects if two different members of the same union are assigned
to each other using the same object

SINCE
v7.2

BENEFITS
"Assigning between objects that have an overlap in their physical storage
leads to undefined behaviour."

EXAMPLE
union U {
int
long
double
};

iValue;
lValue;
dValue;

void main( ) {
union U a, b;
union U *p;
a.dValue = a.lValue;
p->dValue = p->iValue;
}

REPAIR
union U {
int
long
double
};

iValue;
lValue;
dValue;

// Violation
// Violation

void main( ) {
union U a, b;
union U *p, *q;
a.dValue = b.lValue;
p->dValue = q->iValue;
}

// OK
// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-2-1

All constructors of a class should explicitly call a constructor for all of its immediate base
classes and all virtual base classes [PB-43-3]
DESCRIPTION
"All constructors of a class should explicitly call a constructor for all
of
its immediate base classes and all virtual base classes."

SINCE
v7.2

NOTES
Rule will also report a violation if class does not define any
constructors
and has a base class with a constructor.

BENEFITS
This rule reduces confusion over which constructor will be used,
and with what parameters.

EXAMPLE
class A
{
public:
A ( )
{
}
};

class B : public A
{
public:
B ( ) // Violation
{

}
};

REPAIR
class A
{
public:
A ( )
{
}
};

class B : public A
{
public:
B ( ): A() // OK
{
}
};

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-2

The terminate() function shall not be called implicitly [PB-44-3]


DESCRIPTION
"It is implementation-defined whether the call stack is unwound before
terminate() is called, so the destructors of any automatic objects may
or may not be executed."

SINCE
v7.2

BENEFITS
Rule prevents implementation-defined behaviour.

EXAMPLE
class C
{
public:
C() { throw 1; }
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}

REPAIR
class C
{

// Violation

public:
C()
{
try
{
/* ... */
throw 1;
}
catch(...)
{
/* ... */
}
}
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}

// OK

REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-3

There should be no mismatch between the '%s' or '%c' tag from format string and its
corresponding argument in 'printf' function invocation [PB-45-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if an argument passed in for a tag "%s" is
not:
- pointer to char or void
- array of char type
- class containing 'String' in name and member function conversion
operator
- typedefs to above types
- constant '0' (null)
or if an argument passed in for a tag "%c" is not:
- unsigned char
- integer constant with a value lower than 256
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-46, PB-47, PB-48, PB-49, PB-50

NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n

BENEFITS
The rule prevents program crashes and unintended side-effects.

EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
printf("file %s, number %s", name, value);
printf("file %s, letter %c", name, value);
}

// Violation
// Violation

REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
unsigned char ch = 'c';
printf("file %s, number %u", name, value);
printf("file %s, letter %c", name, (unsigned char)value);
printf("file %s, letter %c", name, ch);
}

REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/

// OK
// OK
// OK

There should be no mismatch between the '%f' tag from format string and its corresponding
argument in 'printf' function invocation [PB-46-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if an argument passed in for a tag "%f" is
not:
- float type
- double type
or if an argument passed in for a tag "%Lf" is not:
- long double type
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-47, PB-48, PB-49, PB-50

NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n

BENEFITS
The rule prevents program crashes and unintended side-effects.

EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
float fl = 10.2f;
long double ld = 1.0001L;
printf("Value: %f", value);
printf("Value: %Lf", fl);
printf("Value: %f", ld);
}

// Violation
// Violation
// Violation

REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
float fl = 10.2f;
long double ld = 1.0001L;
printf("Value: %u", value);
printf("Value: %f", (float)value);
printf("Value: %f", fl);
printf("Value: %Lf", ld);
}

//
//
//
//

OK
OK
OK
OK

REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/

There should be no mismatch between the '%i' or '%d' tag from format string and its
corresponding argument in 'printf' function invocation [PB-47-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if:
- an argument passed in for a tag "%i", "%d", "%li", "%ld", "%Ii", "%Id",
"%I32i", "%I32d" is not:
- parameter/variable of type signed int, signed long, short, char, enum,
bool
- expression of type int, long, short, char, enum, bool
- typedefs to above types
- constants of int or long type in a range: -2147483648 to 2147483647
- an argument passed in for a tag "%hi", "%hd" is not:
- parameter/variable of type signed short, char, enum, bool
- expression of type short, char, enum, bool
- typedefs to above types
- constants in a range: -32768 to 32767
- an argument passed in for a tag "%hhi", "%hhd" is not:
- parameter/variable of type signed char
- expression of type char, enum, bool
- typedefs to above types
- constants in a range: -128 to 127
- an argument passed in for a tag "%lli", "%lld" is not:
- signed long long
- typedef to above type
- constants of long long type
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-46, PB-48, PB-49, PB-50

NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n

BENEFITS
The rule prevents program crashes and unintended side-effects.

EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value

signed
signed
signed
signed
signed

int: %i", value);


short: %hi", i);
char: %hhi", f);
long long: %lli", 100);
long: %ld", &i);

REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
signed short s;

//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

long l;
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value

unsigned int: %u", value);


signed short: %hi", s);
signed short: %hi", (short)i);
float: %f", f);
signed long long: %lli", 100ll);
signed long: %ld", l);

//
//
//
//
//
//

OK
OK
OK
OK
OK
OK

REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/

There should be no mismatch between the '%u' tag from format string and its corresponding
argument in 'printf' function invocation [PB-48-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if:
- an argument passed in for a tag "%u", "%lu", "%Iu", "%I32u" is not:
- parameter/variable/expression of type unsigned char, unsigned short,
unsigned int or unsigned long
- typedefs to above types
- constants of int or long type in a range: 0 to 4294967295
- an argument passed in for a tag "%hu" is not:
- parameter/variable/expression of type unsigned char or unsigned short
- typedefs to above types
- constants in a range: 0 to 65535
- an argument passed in for a tag "%hhu" is not:
- parameter/variable/expression of type unsigned char
- typedef to unsigned char type
- constants in a range: 0 to 255
- an argument passed in for a tag "%llu" is not:
- parameter/variable/expression of type unsigned long long
- typedef to above type
- constants of long long type
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-46, PB-47, PB-49, PB-50

NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier

where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n

BENEFITS
The rule prevents program crashes and unintended side-effects.

EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value

unsigned
unsigned
unsigned
unsigned
unsigned

int: %u", i);


short: %hu", value);
char: %hhu", f);
long long: %llu", 100);
long: %lu", &i);

//
//
//
//
//

Violation
Violation
Violation
Violation
Violation

REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
unsigned short int us;
unsigned long int ul;
printf("Value unsigned int: %u", value);
printf("Value unsigned short: %hu", us);

// OK
// OK

printf("Value
printf("Value
printf("Value
printf("Value

unsigned
unsigned
unsigned
unsigned

short: %hu", (unsigned short)value);


char: %f", f);
long long: %llu", 100ull);
long: %lu", ul);

REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/

//
//
//
//

OK
OK
OK
OK

There should be no mismatch between the '%p' tag from format string and its corresponding
argument in 'printf' function invocation [PB-49-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if an argument passed in for a tag "%p" is
not:
- pointer
- typedef to pointer
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-46, PB-47, PB-48, PB-50

NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n

BENEFITS
The rule prevents program crashes and unintended side-effects.

EXAMPLE
#include <stdio.h>
int main(){
int i;
int* ptr;
printf("Value: %p", i);
printf("Value: %p", 0);
printf("Value: %p", *ptr);
}

// Violation
// Violation
// Violation

REPAIR
#include <stdio.h>
int main(){
int i;
int* ptr;
printf("Value: %p", &i);
printf("Value: %i", 0);
printf("Value: %p", ptr);
}

// OK
// OK
// OK

REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/

There should be no difference between the number of tags from format string and the number
of corresponding argument in 'printf' function invocation [PB-50-3]
DESCRIPTION
The rule reports a violation if a number of tags specified in a 'format'
string is different than the number optional function arguments.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
See also: PB-45, PB-46, PB-47, PB-48, PB-49

NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n

BENEFITS
The rule prevents program crashes and unintended side-effects.

EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
printf("file %s, number %u", name);
printf("file %s, number %u", name, name, value);
}

// Violation
// Violation

REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
printf("file %s, number %u", name, value);
}

// OK

REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Pointer arithmetic shall not be applied to pointers that address variables of non-array type
[PB-51-3]
DESCRIPTION
"Pointer arithmetic shall only be applied to pointers that address an
array or
array element.
Addition and subtraction of integers (including increment and decrement)
from
pointers that do not point to an array or array element results in
undefined
behaviour."
See also: MISRA2004-17_1

SINCE
v9.0

NOTES
The rule assumes that a pointer does not point to an array or array
element
if to pointer is assigned null or an address of variable of non-array
type.

BENEFITS
Rule makes the code more readable and less confusing.

EXAMPLE
/* example of incorrect code */
void func(int* ptr1, int a[5]){
int i;
int* ptr2 = 0;
int* ptr3;
ptr1 = &i;
ptr1++;

/* Violation */

ptr3 = ptr2 + 1; /* Violation */


}

REPAIR
/* example of correct code */
void func(int* ptr1, int a[5]){
int i;
int* ptr2 = &a;
int* ptr3 = &a[3];
ptr1++;
/* OK - ptr1 may points to whatever */
ptr1 = ptr2 + 1; /* OK - ptr2 points to an array */
ptr3++;
/* OK - ptr3 points to an array element */
}

REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 17

PFO
Physical File Organization
RULES
Don't define entities with linkage in a header file [PFO-01-3]
Use multiple include guards [PFO-02-3]
An include file should not contain more than one class definition [PFO-033]
Include constant string describing file [PFO-04-3]
File with extension '.c' may not include other files with extension '.c'
[PFO-05-3]
Never include other files in a file with extension '.icc' [PFO-06-3]
Use multiple include guards with pattern based on the header file name
[PFO-07-3]
Use mechanism that prevents multiple inclusion of the file i.e. include
guards or "#pragma once" preprocessor directive [PFO-08-3]
"#pragma once" preprocessor directive should not be used in source files
[PFO-09-3]

Don't define entities with linkage in a header file [PFO-01-3]


DESCRIPTION
"Header files should be used to declare objects, functions, inline
functions,
function templates, typedefs, macros, classes, and class templates and
shall
not contain or produce definitions of objects or functions (or fragment of
functions or objects) that occupy storage."
See also: MISRA2004-8_5

NOTES
As a headers rule detects files with extensions ".h", ".hh", ".hxx", ".i"
(e.g. "file.h", "file.hh", "file.hxx", "file.i").

EXCEPTIONS
The following definitions are allowed in a header file:
- inline functions
- function templates
- static data members of class templates
- const variables if they have internal or no linkage (C++ mode)
- static const variables

BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.

EXAMPLE
/* file.h */
void f1(){}
int var;
class C {
void f2();
};

// Violation
// Violation

void C::f2() {}

// Violation

/* file.cpp */
#include "file.h"

REPAIR
/* file.h */
void f1();
extern int var;
class C {
void f2();
};
template <typename T>
void f3 ( T ) { }

// OK
// OK

// OK

/* file.cpp */
#include "file.h"
void f1(){}
int var;
void C::f2() {}

REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-1
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 61
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 39

Use multiple include guards [PFO-02-3]


DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-07, PFO-08, MISRA2004-19_15

BENEFITS
Rule improves maintainability and optimization of code.

EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present

REPAIR
// file foo.hh
// OK
#ifndef FOO_HH
#define FOO_HH
int i;
#endif

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 27
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-3

An include file should not contain more than one class definition [PFO-03-3]
DESCRIPTION
The rule reports a violation if in a header file is declared
more than one class. Rule does not count nested classes.
See also: NAMING-32

NOTES
A header file is defined as any file that is included via #include.

BENEFITS
Rule makes source code more readable.

EXAMPLE
// file.cpp
#include "file.hh"
// file.hh
class testClass1{};
class testClass2{};

// Violation

REPAIR
// file.cpp
#include "file.hh"
// file.hh
class testClass1{};

// OK - only one class definition

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rec. 3

Include constant string describing file [PFO-04-3]


DESCRIPTION
"Every implementation file should declare a local constant string that
describes
the file so that UNIX command 'what' can be used to obtain information
on the file revision."

BENEFITS
Improves possibility of obtaining information on the file revision.

EXAMPLE
// Violation - No local constant string describing the file

REPAIR
// OK
static const char* sccsid =
"@(#) Exception.cc ; rev. A, Copyright ... ";

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 include Files - Rec 12

File with extension '.c' may not include other files with extension '.c' [PFO-05-3]
DESCRIPTION
.c or .C files (implementation files) are intended to be
compiled on their own, and not included in other files.
This is a well accepted physical organization model for
C and C++ code.
Many build environments are set up
to automatically compile every .c file. If in addition a .c
file is included in another .c file, this will result in
link errors.

BENEFITS
Rule improves maintainability and readability of code, as
well as prevents build errors.

EXAMPLE
//file.c
#include "file2.c"

// Violation

REPAIR
1. Compile each .c file separately and link them.
2. Develop a convention for naming implementation files
to be included that does not use .c or .C extensions.

REFERENCES
Recommended by Parasoft

Never include other files in a file with extension '.icc' [PFO-06-3]


DESCRIPTION
"Never include other files in an .icc file."

BENEFITS
Rule prevents including other files in an .icc file.

EXAMPLE
// some.icc
#include <stdio.h>

// Violation

REPAIR
// File some.icc do not include any other files

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rec. 13

Use multiple include guards with pattern based on the header file name [PFO-07-3]
DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-02, PFO-08, and MISRA2004-19_15

NOTES
If the name of file is filename.h the name in multiple inclusion
mechanism should be converted to the following format FILENAME_H
(capitalized
and with extension preceded by underscoring)

BENEFITS
Rule improves maintainability and optimization of code.

EXAMPLE
// file goo.hh
#ifndef GUARD_GOO // Violation - naming convention not followed
(GUARD_GOO)
#define GUARD_GOO
int i;

#endif /*GUARD_GOO*/

REPAIR
// file goo.hh
#ifndef GOO_HH // OK
#define GOO_HH
int i;
#endif /*GUARD_HH*/

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7

Use mechanism that prevents multiple inclusion of the file i.e. include guards or "#pragma
once" preprocessor directive [PFO-08-3]
DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be either:
- #pragma once - preprocessor directive
or
- include guards defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-02, PFO-07, and MISRA2004-19_15

SINCE
v7.1

BENEFITS
Rule improves maintainability and optimization of code.

EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present

REPAIR
// file foo.hh
// OK
#pragma once

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 35

"#pragma once" preprocessor directive should not be used in source files [PFO-09-3]
DESCRIPTION
#pragma once is a non-standard but widely supported preprocessor directive
designed to cause the current header file to be included only once in a
single
compilation. Using #pragma once in source files is useless because source
files
are not meant to be included by other files. However, if source file with
#pragma once directive is meant to be included by other files one should
reconsider if this file should not be a header file.

BENEFITS
Rule improves maintainability and optimization of code.

EXAMPLE
// file foo.cpp
#pragma once
// Violation

REPAIR
// file foo.h
#pragma once

// OK

REFERENCES
Recommended by ParaSoft

PORT
Portability
RULES
Use capital 'L' instead of lowercase 'l' to indicate long [PORT-01-5]
Assigning result of ints operation to long without casting at least one of
the ints is not allowed [PORT-02-3]
Don't use hard coded value of offset in structures [PORT-03-2]
Don't use hex constant '0xffffffff' as an error marker [PORT-04-2]
A pointer to a long should not be casted to an int pointer [PORT-05-2]
Do not assign a long int to an int [PORT-06-3]
Do not pass long casted to an int in function call [PORT-07-3]
Constant assignment to long should not involve int literals [PORT-08-3]
Do not initialize a long int with int literals [PORT-10-3]
Do not cast an int pointer to a long pointer [PORT-11-2]
Do not assign the value from 32 bit multiplication to long type [PORT-123]
The type int shall always be declared as unsigned int or signed int [PORT13-3]
Avoid conversions from "shorter" type to "longer" type in assignment
[PORT-14-3]
Do not cast from "shorter" type to "longer" type [PORT-15-3]
Avoid conversions from a "shorter" type to a "longer" type in function
calls [PORT-16-3]
Don't use 'i64' or 'L' suffixes directly [PORT-17-3]
Instead of casting a long type operand of an expression to int cast the
result of the expression [PORT-19-3]
Do not declare variables of long type directly [PORT-20-3]
Do not assign a long value to a double [PORT-21-3]
Use arrays of int types instead of large arrays of longs [PORT-22-5]
Use arrays of int types instead of dynamic allocated large arrays of longs
[PORT-23-5]
Don't use large arrays of pointers to bool, char, short, int and float
types [PORT-24-5]
User-specified identifiers (internal and external) will not rely on
significance of more than 64 characters [PORT-25-2]
Algorithms shall not make assumptions concerning the order of allocation
of nonstatic data members separated by an access specifier [PORT-26-2]
Avoid implicit conversions to a type of narrower size [PORT-27-3]
Avoid conversions of constant values to a narrower type [PORT-28-3]

Use capital 'L' instead of lowercase 'l' to indicate long [PORT-01-5]


DESCRIPTION
"Lower case letter 'l' (ell) can easily be confused with the digit '1'
(one).
This can be particularly confusing when indicating that an integer literal
constant is a long value. The compliant solution improvises by using an
upper
case 'L' instead of lower case 'l' to disambiguate the visual appearance.
Likewise, you should use 'LL' rather than 'll' when indicating that an
integer
literal constant is a long long value."

BENEFITS
The rule prevents confusions and improves the readability of code.

EXAMPLE
#define S1 11l

// Violation

void foo1(){
long l;
long long ll;
unsigned long ul;
ul = 11lu;
// Violation
l = 11l;
// Violation
ll = 11111ll; // Violation
}

REPAIR
#define S1 11L

// OK

void foo1(){
long l;
long long ll;
unsigned long ul;

ul = 11LU;
// OK
l = 11L;
// OK
ll = 11111LL; // OK
}

REFERENCES
CERT C Secure Coding Standard, Declarations and Initialization, DCL16-C

Assigning result of ints operation to long without casting at least one of the ints is not allowed
[PORT-02-3]
DESCRIPTION
When assigning result of ints operation to long, you should cast at least
one
of the ints to a long before the operation.

BENEFITS
When operating on ints, you should at least cast one of the ints to along
before the operation. Otherwise, you may have a loss of information.

EXAMPLE
void foo() {
int a = 72;
int b = 55;
long result = 0;
result = (long)(a*b);
}

// Violation

REPAIR
void foo() {
int a = 72;
int b = 55;
long result = 0;
result = (long)((long)a*b);
}

REFERENCES
Recommended by ParaSoft

// OK

Don't use hard coded value of offset in structures [PORT-03-2]


DESCRIPTION
This rule checks whether you are using the hardcoded value of offset in
structures. On a 32-bit architecture, offset has 4 bytes (4*8bit=32 bit),
but if the architecture is changed to 64-bit, the offset will increase to
8 bytes (*8*bit=64bit). Let the compiler calculate the field.

BENEFITS
By following this rule, you let the compiler calculate the field of
offset.

EXAMPLE
#include <stddef.h>
#define ARCH32 true
#ifdef ARCH32
#define __int3264 int //32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 //64-bit type on win64
//(warning: long on win64 is 32-bit type)
#else //unix64
#define __int3264 long //64-bit type on unix64 (long on unix64 is 64-bit
type)
#endif
#endif
struct myStruct {
void *ptr;
int i;
};
void foo() {
myStruct s;
myStruct *ps = new myStruct();
int j;
s.i = 22;
ps->i = 22;
j= *(int *)((unsigned __int3264)&s + sizeof(void*));
j= *(int *)((unsigned __int3264)&s + 4 );

// Violation
// Violation

j=
j=
j=
j=

*(int
*(int
*(int
*(int

*)((unsigned
*)((unsigned
*)((unsigned
*)((unsigned

__int3264)&s.i + 0 );
__int3264)ps + sizeof(void*));
__int3264)ps + 4);
__int3264)&ps->i + 0);

//
//
//
//

Violation
Violation
Violation
Violation

REPAIR
#include <stddef.h>
#define ARCH32 true
#ifdef ARCH32
#define __int3264 int //32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 //64-bit type on win64
//(warning: long on win64 is 32-bit type)
#else //unix64
#define __int3264 long //64-bit type on unix64 (long on unix64 is 64-bit
type)
#endif
#endif
struct myStruct {
void *ptr;
int i;
};
void foo() {
myStruct s;
myStruct *ps = new myStruct();
int j;
s.i = 22;
ps->i = 22;
j= *(int *)((unsigned __int3264)&s + offsetof(myStruct,i)); // OK
j= *(int *)((unsigned __int3264)ps + offsetof(myStruct,i)); // OK
}

REFERENCES
Recommended by ParaSoft

Don't use hex constant '0xffffffff' as an error marker [PORT-04-2]


DESCRIPTION
"Sometimes the value '-1' is used as an error code or other special marker
and it is written as '0xffffffff'. This expression is incorrect on a 64bit
platform, so you should explicitly define the value '-1'."

BENEFITS
The rule prevents writing an error prone code.

EXAMPLE
#ifndef size_t
typedef unsigned int size_t;
#endif
#define INVALID_RESULT (0xFFFFFFFFu)
#define NULL 0

// Violation

size_t MyStrLen(const char *str) {


size_t n;
if (str == NULL)
return INVALID_RESULT;
// ...
return n;
}

REPAIR
#ifndef size_t
typedef unsigned int size_t;
#endif
#define INVALID_RESULT (size_t(-1))
#define NULL 0
size_t MyStrLen(const char *str) {
size_t n;

// OK

if (str == NULL)
return INVALID_RESULT;
// ...
return n;
}

REFERENCES
http://software.intel.com/en-us/articles/lessons-on-development-of-64-bitcc-applications/
Lesson 9.

A pointer to a long should not be casted to an int pointer [PORT-05-2]


DESCRIPTION
"Do not assume that int and long have the same size."
A pointer to a long should not be casted to an int pointer.
See also: PORT-06, PORT-07, PORT-08, PORT-10, PORT-11, PORT-12

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo() {
int *intPointer;
long *longPointer;
intPointer = (int *)longPointer; // Violation
}

REPAIR
Do not cast long pointer to int pointer.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2

Do not assign a long int to an int [PORT-06-3]


DESCRIPTION
"Do not assume that int and long have the same size."
Assigning a long int to an int may result in truncation when porting
from 32 bit to 64 bit applications.
See also: PORT-05, PORT-07, PORT-08, PORT-10, PORT-11, PORT-12

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo(){
int iVal = 72;
long lVal = 6;
iVal = lVal;// Violation
iVal = (int)lVal; // Violation
}

REPAIR
Do not assign a long int to an int.

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2

Do not pass long casted to an int in function call [PORT-07-3]


DESCRIPTION
"Do not assume that int and long have the same size."
Assigning a long int to an int may result in truncation
when porting from 32 bit to 64 bit applications.
See also: PORT-05, PORT-06, PORT-08, PORT-10, PORT-11, PORT-12

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo(int iVal){
long lVal;
foo(lVal);// Violation
foo((int)lVal);// Violation
}

REPAIR
Do not assign a long int to an int.

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2

Constant assignment to long should not involve int literals [PORT-08-3]


DESCRIPTION
"Do not assume that int and long have the same size."
Constant assignment to long should not involve int literals.
See also: PORT-05, PORT-06, PORT-07, PORT-10, PORT-11, PORT-12

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo() {
long longValue;
longValue &= ~(0x0000000000000101); // Violation
longValue = 0x0000000000000101; // Violation
}

REPAIR
void foo() {
long longValue;
longValue &= ~(0x0000000000000101L); // OK
longValue = 0x0000000000000101L; // OK
}

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2

Do not initialize a long int with int literals [PORT-10-3]


DESCRIPTION
"Do not assume that int and long have the same size."
An int literal is 32 bits in length. Assignment of int literal
to long data value could lead to garbage in the upper 32 bits,
or truncation if the int literal takes up more than 32 bits.
See also: PORT-05, PORT-06, PORT-07, PORT-08, PORT-11, PORT-12

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo(){
long lVal = 1;
}

// Violation

REPAIR
void foo(){
long lVal = 1L; // OK
}

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2

Do not cast an int pointer to a long pointer [PORT-11-2]


DESCRIPTION
"A pointer to an int is not compatible with a pointer to a long. Even the
use
of explicit casting is not correct."
A pointer to an int has 4-byte alignment, and a pointer to long has 8-byte
alignment on some 64-bit platforms.
See also: PORT-05, PORT-06, PORT-07, PORT-08, PORT-10, PORT-12

NOTES
The rule checks only explicit casts.

BENEFITS
The rule prevents misaligned memory accesses on 64-bit platforms.

EXAMPLE
void f2005() {
int *intPointer;
long *longPointer;
longPointer = (long *)intPointer;// Violation
}

REPAIR
Do not cast an int pointer to a long pointer.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
2. http://developers.sun.com/solaris/articles/64_bit_driver.html
3.1.1 Converting Driver Code to Be 64-Bit Clean, Example 3

Do not assign the value from 32 bit multiplication to long type [PORT-12-3]
DESCRIPTION
"Do not assume that int and long have the same size."
32 bit multiplication assigned to long value may result in truncation.
See also: PORT-05, PORT-06, PORT-07, PORT-08, PORT-10, PORT-11

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo() {
long longValue;
longValue = 2000000 * 3000000;
}

// Violation

REPAIR
void foo() {
long longValue;
longValue = 2000000L * 3000000;
}

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2

The type int shall always be declared as unsigned int or signed int [PORT-13-3]
DESCRIPTION
"Do not assume that an int is 32 bits long (it may be only 16 bits long)."

BENEFITS
Complying with this rule leads to safer and more readable code.

EXAMPLE
void foo()
{
int a; // Violation
};
int goo();

// Violation

REPAIR
void foo()
{
signed int a;
};
unsigned int goo();

// OK

// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 3

Avoid conversions from "shorter" type to "longer" type in assignment [PORT-14-3]


DESCRIPTION
"Be careful not to make conversion from a shorter type to a longer one."
See also: PB-06, MISRA-043, PORT-15, PORT-16

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo1() {
int intValue;
long longValue = 1L;
longValue = intValue;// Violation
}
void foo2() {
int intValue=1;
float floatValue;
floatValue = intValue;// Violation
}

REPAIR
Do not make conversion from a shorter type to a longer one.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 6
2. ISO/DIS 26262
point 8.4.4

Do not cast from "shorter" type to "longer" type [PORT-15-3]


DESCRIPTION
"Be careful not to make conversion from a shorter type to a longer one."
See also: PORT-14, PORT-16, MISRA2004-10_1, MISRA2004-10_2

BENEFITS
Rule prevents loss of data.

EXAMPLE
void foo3() {
int longValue = 1L;
(double)longValue;// Violation
}

REPAIR
Do not make conversion from a shorter type to a longer one.

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 6

Avoid conversions from a "shorter" type to a "longer" type in function calls [PORT-16-3]
DESCRIPTION
Under 32 bit platform double can hold all significant bits.
Under 64 bit platform double has 52 significant bits, and bits can be
lost.
See also: PORT-14, PORT-15

BENEFITS
Rule prevents loss of data.

EXAMPLE
void moo (double d) {}
void foo () {
long longValue = 1L;
moo(longValue);// Violation
}

REPAIR
void moo (double d) {}
void foo () {
double longValue = 1;
moo(longValue);// OK
}

REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 6
2. ISO/DIS 26262
point 8.4.4

Don't use 'i64' or 'L' suffixes directly [PORT-17-3]


DESCRIPTION
If integer constant suffixes are used in the code, you might need to
modify
the code for use on 64-bit architecture, because the 'L' or 'l' suffix
(meaning long) in Windows(64-bit) is a 32-bit type. Windows(64-bit) uses
the 'i64' suffix.

BENEFITS
Adding a centrally defined macro in the file will make the code generic,
so that it can be compiled for use on both the UNIX(64-bit)
and the Windows(64-bit) operating systems.

EXAMPLE
void foo(){
long l;
unsigned long ul;
l = 123456789l;
l = 123456789L;
ul = 123456789ul;
ul = 123456789uL;
}

//
//
//
//

Violation
Violation
Violation
Violation

REPAIR
#ifdef _WIN64
#define CONST3264(a) (a##i64)
#else
#define CONST3264(a) (a##L)
#endif
void foo(){
long l;
unsigned long ul;
l = CONST3264( 123456789 );
// OK
ul = CONST3264( 123456789u ); // OK
}

REFERENCES
http://software.intel.com/en-us/articles/support-integer-constant-typesuffixes-on-64-bit-architecture/

Instead of casting a long type operand of an expression to int cast the result of the expression
[PORT-19-3]
DESCRIPTION
The rule reports a violation if you use explicit cast to 'int' on operand
of long type. When you cast an operand from a long to an int type, then
some data could be removed and the result of expression could be not
according
to expectations.

BENEFITS
The rule prevents loss of data.

EXAMPLE
void foo()
{
int int1, int2;
long longValue;
int2 = ((int)longValue)/int1; // Violation
}

REPAIR
void foo()
{
int int1, int2;
long longValue;
int2 = (int)(longValue/int1); // OK
}

REFERENCES
Recommended by ParaSoft

Do not declare variables of long type directly [PORT-20-3]


DESCRIPTION
This rule checks whether you avoid using long.
On win32/unix32/win64, long has 32-bit. On unix64, long has 64-bit.
Instead of long, use your own type or specific variable definition.

BENEFITS
By following this rule, you can prevent data loss.

EXAMPLE
#define ARCH32 true
#ifndef __int3264
#ifdef ARCH32
#define __int3264 int // 32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 // 64-bit type on win64
#else //unix64
#define __int3264 int64_t // 64-bit type on unix64
#endif
#endif
#endif
long lVal;
// Violation

REPAIR
#define ARCH32 true
#ifndef __int3264
#ifdef ARCH32
#define __int3264 int // 32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 // 64-bit type on win64
#else //unix64
#define __int3264 int64_t // 64-bit type on unix64
#endif
#endif

#endif
__int3264 newlVal; // OK

REFERENCES
Recommended by ParaSoft

Do not assign a long value to a double [PORT-21-3]


DESCRIPTION
Under the 32 bit platform, double can hold all significant bits.
Under the 64 bit platform, double has 52 significant bits, and bits can be
lost.
See also: MISRA-043, PB-06

BENEFITS
This rule checks for possible truncation and prevents data loss.

EXAMPLE
void foo()
{
double doubleValue;
long longValue = 1L;
doubleValue = longValue;
}

// Violation

REPAIR
Do not assign a long value to a double.

REFERENCES
Recommended by ParaSoft

Use arrays of int types instead of large arrays of longs [PORT-22-5]


DESCRIPTION
"Large arrays of long or unsigned long types, can cause serious
performance degradation in the LP64 data-type model as compared
to arrays of int or unsigned int types. Large arrays of long types cause
significantly more cache misses and consume more memory.
Therefore, if int works just as well as long for the application purposes,
it's better to use int rather than long."
See also: PORT-23, PORT-24

Note: This rule checks for static allocated arrays of longs that consist
over 2^16-1
elements.

SINCE
v7.0

BENEFITS
Reduction of memory consumption and avoiding possible performance
degradation.

EXAMPLE
typedef long LONG;
long tab1[12];
long tab2[65536];
long int tab3[65536];
long tab4[256][32][16];
unsigned long int tab5[65536];
LONG tab6[100000];

REPAIR

//
//
//
//
//
//

OK
Violation
Violation
Violation
Violation
Violation

long tab1[12];
int tab2[65536];
int tab4[256][32][16];
unsigned int tab5[65536];
int tab6[100000];

//
//
//
//
//

OK
OK
OK
OK
OK

REFERENCES
1. Converting 32-bit Applications Into 64-bit Applications: Things to
Consider
http://developers.sun.com/prodtech/cc/articles/ILP32toLP64Issues.html
2. Multiplatform Porting to 64 Bits
http://www.ddj.com/184406427

Use arrays of int types instead of dynamic allocated large arrays of longs [PORT-23-5]
DESCRIPTION
"Large arrays of long or unsigned long types, can cause serious
performance degradation in the LP64 data-type model as compared
to arrays of int or unsigned int types. Large arrays of long types cause
significantly more cache misses and consume more memory.
Therefore, if int works just as well as long for the application purposes,
it's better to use int rather than long."
See also: PORT-22, PORT-24

Note: This rule checks for dynamic allocated arrays of longs that consist
over 2^16-1
elements.

SINCE
v7.0

BENEFITS
Reduction of memory consumption and avoiding possible performance
degradation.

EXAMPLE
long *arr1 = new long[70000];

// Violation

REPAIR
int *arr1 = new int[70000];

// OK

REFERENCES
1. Converting 32-bit Applications Into 64-bit Applications: Things to
Consider

http://developers.sun.com/prodtech/cc/articles/ILP32toLP64Issues.html
2. Multiplatform Porting to 64 Bits
http://www.ddj.com/184406427

Don't use large arrays of pointers to bool, char, short, int and float types [PORT-24-5]
DESCRIPTION
"Large arrays of long or unsigned long types, can cause serious
performance degradation in the LP64 data-type model as compared
to arrays of int or unsigned int types. Large arrays of long types cause
significantly more cache misses and consume more memory(...)
This is also an argument for using arrays of int types instead of arrays
of pointers. Some C applications suffer from serious performance
degradation after conversion to the LP64 data-type model because
they rely on many, large, arrays of pointers"
See also: PORT-22, PORT-23

Note: Rule report violation large (over 2^16 elements) arrays to pointers
to bool, char, short, int and float types.

SINCE
v7.0

BENEFITS
Reduction of memory consumption and avoiding possible performance
degradation.

EXAMPLE
int* arr1[100000];
float* arr2[100000];

// Violation
// Violation

REPAIR
int arr1[100000];
float arr2[100000];

REFERENCES

// OK
// OK

1. Converting 32-bit Applications Into 64-bit Applications: Things to


Consider
http://developers.sun.com/prodtech/cc/articles/ILP32toLP64Issues.html
2. Multiplatform Porting to 64 Bits
http://www.ddj.com/184406427

User-specified identifiers (internal and external) will not rely on significance of more than 64
characters [PORT-25-2]
DESCRIPTION
Identifiers names consisting of more than 64 characters should not be
used.

SINCE
v7.1

BENEFITS
Rule ensures that code can be ported between the majority of
compilers/linkers
without requiring modification (shortening) of identifiers names

EXAMPLE
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam) //
Violation 65 chars
{
}

REPAIR
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam)
64 chars
{
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

// OK

Chapter 4.9 Style, AV Rule 46

Algorithms shall not make assumptions concerning the order of allocation of nonstatic data
members separated by an access specifier [PORT-26-2]
DESCRIPTION
This rule is intended to prohibit an application from making assumptions
concerning the order in which non-static data members, separated by an
access specifier, are ordered.
Rule reports a violation message if static_cast type is pointer to class
with non-static data members separated by an access specifier.

SINCE
v7.1

BENEFITS
The order of allocation of nonstatic data members, separated by an
access-specifier, is unspecified.

EXAMPLE
class A
{
protected: // a could be stored before b, or vice versa
int a;
private:
int b;
};

class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);

// Violation
// application

assumes that objects of


// type A will

always have attribute a


// stored before
attribute b.
}

REPAIR
struct A
{
int a;
int b;
};
class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);

// OK
// attributes in B

not separated
// by an access
specifier
}

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 210.1

Avoid implicit conversions to a type of narrower size [PORT-27-3]


DESCRIPTION
The rule reports a violation if parameter/variable/expression of integral
type is implicitly converted to a narrower integral type
or parameter/variable/expression of floating type is implicitly converted
to a narrower floating type.

SINCE
v9.2

NOTES
The rule does
- conversions
- conversions
- conversions

not check:
of constant expressions.
of bit fields
between integral and floating types

Enumeration types are treated in the same way as integral types.

BENEFITS
The rule prevents possible loss of data.

EXAMPLE
enum E1_int{
E1_int = 0xFFFF,
E2_int
}e1;
void foo(unsigned int i){
unsigned char c1 = e1;
unsigned char c2 = i;
}

// Violation
// Violation

REPAIR
enum E1_int{
E1_int = 0xFFFF,
E2_int
}e1;
void foo(){
unsigned int c = e1;
// OK
unsigned char c2 = (unsigned int)i; // OK
}

REFERENCES
Recommended by ParaSoft

Avoid conversions of constant values to a narrower type [PORT-28-3]


DESCRIPTION
The rule reports a violation if an integer or enumeration constant is
passed
to a type that is not enough to hold its value.

SINCE
v9.2

NOTES
The rule does not report violations on complex constant expressions.

BENEFITS
The rule prevents a loss of data.

EXAMPLE
void foo1(){
unsigned char c = 256;
short s = 32768;
int i = 2147483648;
}

// Violation
// Violation
// Violation

REPAIR
void foo1(){
unsigned short c = 256;
int s = 32768;
unsigned int i = 2147483648;
}

REFERENCES

// OK
// OK
// OK

Recommended by ParaSoft

PREPROC
Preprocessor
RULES
Avoid macros [PREPROC-01-3]
Don't use macros in include statement [PREPROC-02-2]
Don't redefine primitive types [PREPROC-03-4]
Don't define part of statement [PREPROC-04-4]
In a macro function, use parentheses before and after multiplication or
division [PREPROC-05-2]
Do not allow relative path names in #include statements [PREPROC-06-2]
Incorrect 'NULL' definition [PREPROC-07-5]
The #include pre-processor directive will only be used to include header
(*.h) files [PREPROC-08-3]
The #include directive shall use the <filename.h> notation to include
header files [PREPROC-09-2]
The #ifndef and #endif pre-processor directives will only be used to
prevent multiple inclusions of the same header file [PREPROC-10-3]
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include [PREPROC-11-2]
C++ macros shall only be used for include guards, type qualifiers, or
storage class specifiers [PREPROC-12-3]
Macro should not contain token pasting, variable argument list nor
recursive macro calls [PREPROC-13-3]
All macros must expand into complete syntactic units [PREPROC-14-3]
Pointer dereference operations may not be hidden in macro definitions
[PREPROC-15-3]

Avoid macros [PREPROC-01-3]


DESCRIPTION
Macros are generally an obsolete construct inherited from C language.
The main problems with macros are that they:
- are not type-safe
- are expanded by the preprocessor so debugging them is not possible
- can compile by pure luck creating ugly problems with the program

EXCEPTIONS
Macros are almost never necessary in C++. Exceptions to this rule are:
- #ifdef
- #ifndef
- #if
- #if defined
when used as include guards and for conditional compilation.

BENEFITS
Improves code reliability and maintainability.

EXAMPLE
#define PI 3.14

// Violation

REPAIR
const double PI = 3.14; // OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS

Chapter 4.6 Pre-Processing Directives, AV Rule 31


3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1

Don't use macros in include statement [PREPROC-02-2]


DESCRIPTION
This rule checks that macros are not used in the include statement.
Including header files with "#define" predefined makes code hard
to read and understand.

BENEFITS
Readability and clarity.

EXAMPLE
/* Notice:
* You must be sure that your compiler can do that
* and that given header file is available
* Works with gcc
*/
#define A(string) #string
#define HEADER_FILE(nr) A(MacroWithinInclude ## nr)
#include HEADER_FILE(12)

// Violation

#include "MacroWithinInclude12"

// OK

REPAIR
Don't use macros in include statement

REFERENCES
Recommended by ParaSoft

Don't redefine primitive types [PREPROC-03-4]


DESCRIPTION
This rule checks whether you are redefining primitive types
using #define directive. This increases code readability
by avoiding the creation of new unnecessary types.

BENEFITS
Readability.

EXAMPLE
#define T30 char
#define T31 unsigned char

// Violation
// Violation

REPAIR
#define T30 char_def
#define T31 unsigned_char_def

REFERENCES
Recommended by ParaSoft

// OK
// OK

Don't define part of statement [PREPROC-04-4]


DESCRIPTION
This rule checks whether you are defining part of a statement.
Defining a part of a statement makes code unreadable
and is extremely error prone.

BENEFITS
Prevents making code unreadable.

EXAMPLE
#define PARTIAL(a) ((a) * // Violation

REPAIR
#define PARTIAL(a) ((a) * (a)) // OK

REFERENCES
Recommended by ParaSoft

In a macro function, use parentheses before and after multiplication or division [PREPROC-052]
DESCRIPTION
This rule checks whether parentheses are used before and after division
or multiplication in function-like macros.

EXCEPTIONS
The rule does not report violation if as an operand of division
or multiplication is used a number constant or other division
or multiplication.

BENEFITS
Improves the readability of code and ensures operations order.

EXAMPLE
#define
#define
#define
#define
#define
#define

DIVISION_1(x) ( x / (x))
// Violation
DIVISION_2(x) ((x) / 2 + 5) // Violation
DIVISION_3(x) (256 / x)
// Violation
MULTI_1(x) (x * (x))
// Violation
MULTI_2(x) ((x) * 2 + 5)
// Violation
MULTI_3(x) (256 * x)
// Violation

REPAIR
#define
#define
#define
#define
#define
#define
#define
#define

DIVISION_1(x) ( (x) / (x))


DIVISION_2a(x) ((x) / (2 + 5))
DIVISION_2b(x) (((x) / 2) + 5)
DIVISION_3(x) (256 / (x))
MULTI_1(x) ( (x) * (x))
MULTI_2a(x) ((x) * (2 + 5))
MULTI_2b(x) (((x) * 2) + 5)
MULTI_3(x) (256 * (x))

//
//
//
//
//
//
//
//

OK
OK
OK
OK
OK
OK
OK
OK

REFERENCES
Recommended by ParaSoft

Do not allow relative path names in #include statements [PREPROC-06-2]


DESCRIPTION
Do not allow relative path names in #include statements.
Rule disallows usage of:
- any "/" symbols in user include directive ("pathname")
- "/" symbols at the beginning of include file in system
include directive (<pathname>)
- any ".." symbols

BENEFITS
Rule prevents specifying relative file names in #include directives.

EXAMPLE
#include "inc/foo.hh"
#include "inc/../foo.hh"
#include <sys/../time.h>

// OK
// Violation
// Violation

REPAIR
#include "inc/foo.hh"
#include "inc/foo.hh"
#include <sys/time.h>

// OK
// OK
// OK

REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 10

Incorrect 'NULL' definition [PREPROC-07-5]


DESCRIPTION
This rule checks whether your definition of void is (void *)0.

BENEFITS
Any other usage of NULL is misleading and error prone.

EXAMPLE
#define NULL 0 // Violation
#undef NULL
#define NULL
// Violation
#undef NULL

REPAIR
#define NULL (void*)0
// OK
#undef NULL
#define NULL ((void*)0) // OK
#undef NULL

REFERENCES
Recommended by ParaSoft

The #include pre-processor directive will only be used to include header (*.h) files [PREPROC08-3]
DESCRIPTION
The #include pre-processor directive will only be used to include
header (*.h) files.

SINCE
v7.1

EXCEPTIONS
In the case of template class or function definitions, the code may be
partitioned into separate header and implementation files. In this
case, the implementation file may be included as a part of the header
file. Rule allows for mentioned exception if the implementation file
has the same name as a header file.

BENEFITS
Rule improves the clarity of code.
The only files included in a .cpp file should be the relevant
header (*.h) files.

EXAMPLE
// file.cpp
#include <file2.cpp>
#include <file3.hh>

// Violation
// Violation

// file.h
#include <file2.cpp>
#include <file3.hh>

// Violation
// Violation

REPAIR
// file.cpp

#include <file2.h>
#include <file3.h>
// file.h
#include <file.cpp>
file.cpp
#include <file2.h>
#include <file3.h>

// OK - header (*.h) file


// OK - header (*.h) file

// OK - corresponding to file.h implementation file


// OK - header (*.h) file
// OK - header (*.h) file

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 32

The #include directive shall use the <filename.h> notation to include header files [PREPROC09-2]
DESCRIPTION
The #include directive shall use the <filename.h> notation to include
header files.

SINCE
v7.1

BENEFITS
The include form "filename.h" is typically used to include local header
files.
However, due to the unfortunate divergence in vendor implementations, only
the <filename.h> form will be used.

EXAMPLE
#include "foo.h" // Violation

REPAIR
#include <foo.h>
// OK
#include <dir1/dir2/foo.h> // OK: relative path used

REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Filess, AV Rule 33

The #ifndef and #endif pre-processor directives will only be used to prevent multiple
inclusions of the same header file [PREPROC-10-3]
DESCRIPTION
The #ifndef and #endif pre-processor directives will only be used
as defined in below example to prevent multiple inclusions of the
same header file.
#ifndef Header_filename
#define Header_filename
// Header declarations...
#endif

SINCE
v7.1

BENEFITS
Conditional code compilation should be kept to a minimum as it can
significantly obscure testing and maintenance efforts.

EXAMPLE
#ifndef MAX

// Violation

int max = 10;


#endif

// Violation

int a;

REPAIR
#ifndef FOO_H
#define FOO_H
int max = 10;
int a;

// OK

#endif

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 28
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

Only the following pre-processor directives shall be used: #ifndef, #define, #endif, #include
[PREPROC-11-2]
DESCRIPTION
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include

SINCE
v7.1

BENEFITS
Limit the use of the pre-processor to those cases where it is necessary.

EXAMPLE
#pragma once // Violation

REPAIR
#ifndef FOO_H
#define FOO_H
/* ... */
#endif

// OK

REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 26
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

C++ macros shall only be used for include guards, type qualifiers, or storage class specifiers
[PREPROC-12-3]
DESCRIPTION
"C++ macros shall only be used for include guards, type qualifiers, or
storage
class specifiers. These are the only permitted uses of macros. C++ offers
const variable and function templates, which provide a type-safe
alternative
to the preprocessor."

SINCE
v7.2

NOTES
List of type qualifiers and storage class specifiers:
// type qualifiers:
const
volatile
// storage class specifiers:
auto
register
static
extern
mutable

BENEFITS
Improves code reliability and maintainability.

EXAMPLE
#define PI 3.14

REPAIR

// Violation

#define STOR extern


// OK storage class specifier
const double PI = 3.14; // OK

REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-2

Macro should not contain token pasting, variable argument list nor recursive macro calls
[PREPROC-13-3]
DESCRIPTION
"The use of the preprocessor must be limited to the inclusion of header
files
and simple macro definitions. Token pasting, variable argument lists
(ellipses),
and recursive macro calls are not allowed."

SINCE
v7.3

NOTES
The rule detects only direct recursion and indirect recursion if it is
limited
to two level and macros are defined in the same file.

BENEFITS
"The C preprocessor is a powerful obfuscation tool that can destroy code
clarity and befuddle many text based checkers. The effect of constructs
in unrestricted preprocessor code can be extremely hard to decipher,
even with a formal language definition in hand."

EXAMPLE
#define PASTING(a, b) a ## b

// Violation - Token pasting

#define ELLIP(a, b, ...) a + b

// Violation - ellipsis

#define RECUR(a, b) RECUR(a, a)

// Violation - recursion

REPAIR
Do not use token pasting, variable argument lists (ellipses),

nor recursive macro calls

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

All macros must expand into complete syntactic units [PREPROC-14-3]


DESCRIPTION
"All macros must expand into complete syntactic units. The restriction of
macro
definitions to the definition of complete syntactic units means that all
macro
bodies must be enclosed in either round or curly braces."
See also: MISRA2004-19_4

SINCE
v7.3

EXCEPTIONS
The rule does not report violations on macros defined as character, string
or
number constants, for example:
#define CONST1 10
// OK
#define CONST2 'A'
// OK
#define CONST3 "foo" // OK
Such cases are simple enough to not require braces.
Note that negative numbers like -10 are still violations of this rule.

BENEFITS
"The C preprocessor is a powerful obfuscation tool that can destroy code
clarity and befuddle many text based checkers. The effect of constructs
in unrestricted preprocessor code can be extremely hard to decipher,
even with a formal language definition in hand."

EXAMPLE
#define MAC1(a, b) a + b

REPAIR

// Violation - no braces

#define MAC1(a, b) (a + b)

// OK

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8

Pointer dereference operations may not be hidden in macro definitions [PREPROC-15-3]


DESCRIPTION
"The use of pointers should be restricted. Pointer dereference operations
may not be hidden in macro definitions"

SINCE
v7.3

BENEFITS
"Pointers are easily misused, even by experienced programmers. They can
make it
hard to follow or analyze the flow of data in a program, especially by
toolbased
static analyzers."

EXAMPLE
#define MAC1(a, b) *a + b
#define MAC2(a, b) (a + *b)

// Violation
// Violation

REPAIR
Do not use pointer dereference operations in macro definitions.

REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 9

QT
Qt Best Practices
RULES
Every QObject subclass should contain a Q_OBJECT macro [QT-01-3]
QObject must not be inherited more than one time [QT-02-3]
It's only possible to connect a signal to a slot or a signal to another
signal [QT-03-3]
The methods inside the SIGNAL and SLOT macros have to exist [QT-04-1]
Mark signal emissions with the keyword "emit" to distinguish a signal
emission from a normal method call [QT-05-3]
Do not set Idle or Critical priority to QThreads. Use High/Low/Med only
[QT-06-3]
Do not force thread termination by calling QThread::terminate() [QT-07-1]
If using lock on a mutex in a function, release the lock in the same
function [QT-08-3]
Do not call new on QMutexLocker [QT-09-1]
Declare a copy constructor and operator= for any Qt - inherited objects
that have pointers [QT-10-3]
Do not use setWindowFlags function on a Widget [QT-11-4]
Do not directly set specific Widget attributes that are set by Qt kernel
[QT-12-1]
Never mix const and non-const iterators in assignment [QT-13-3]
If you use Q_DECLARE_FLAGS, you must also use
Q_DECLARE_OPERATORS_FOR_FLAGS [QT-14-3]
Q_DECLARE_OPERATORS_FOR_FLAGS must be in the global namespace,
Q_DECLARE_FLAGS inside the enum's namespace [QT-15-3]
The getters and setters of a Q_PROPERTY must exist and the types must
match [QT-16-3]
Properties of enum types must use Q_ENUMS [QT-17-3]
Non-const function should not be called on the Qt object [QT-18-3]

Every QObject subclass should contain a Q_OBJECT macro [QT-01-3]


DESCRIPTION
Every QObject subclass should contain a Q_OBJECT macro.
Otherwise the Qt meta type system won't work with that class.

BENEFITS
While it is possible to use QObject as a base class without the Q_OBJECT
macro
and without meta-object code, neither signals and slots nor any of the
other
features meta type based features (Properties, class name, inheritance
checking, I18N, dynamic QObject casting) will be available if the Q_OBJECT
macro is not used. From the meta-object system's point of view, a QObject
subclass without meta code is equivalent to its closest ancestor with
meta-object code. This means for example, that QMetaObject::className()
will
not return the actual name of your class, but the class name of this
ancestor.
Also, using the dynamic casting function
T qobject_cast ( QObject * object )
will only be able to cast to the ancestor class type.

EXAMPLE
#include <QtCore/QObject>
class QFigure: public QObject
{
Q_OBJECT
private:
Q_DISABLE_COPY(QFigure)
};
class QCircle: public QFigure
present
{
private:
Q_DISABLE_COPY(QCircle)

// Violation - no Q_OBJECT macro

};

REPAIR
#include <QtCore/QObject>
class QFigure: public QObject
{
Q_OBJECT
private:
Q_DISABLE_COPY(QFigure)
};
class QCircle: public QFigure
{
Q_OBJECT

// OK

private:
Q_DISABLE_COPY(QCircle)
};

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/metaobjects.html

QObject must not be inherited more than one time [QT-02-3]


DESCRIPTION
QObject must not be inherited more than one time.

BENEFITS
The meta-object system cannot properly merge the meta-information from two
QObject derived classes. The resulting meta-object file may or may not
compile,
and you will not be able to access all the signals and slots from both
super
classes. You will also not be able to cast the object to both super
classes.
Multiple inheritance from QObjects would also mean duplication of internal
data structures.

EXAMPLE
#include <QtCore/QObject>
#include <QtGui/QWidget>
class ClipboardInterface : public QObject
{
Q_OBJECT
public slots:
void cut();
void copy() const;
void paste();
private:
Q_DISABLE_COPY(ClipboardInterface)
};
class CustomWidget : public QWidget, public ClipboardInterface //
Violation
{
// inherits from two
QObjects
Q_OBJECT

private:
Q_DISABLE_COPY(CustomWidget)
};

REPAIR
// for workaround detailed description visit:
// http://doc.trolltech.com/qq/qq15-academic.html
#include <QtCore/QObject>
#include <QtGui/QWidget>
class ClipboardInterface
{
public:
virtual void cut() = 0;
virtual void copy() const = 0;
virtual void paste() = 0;
};
class ClipboardWrapper;
class CustomWidget : public QWidget, public ClipboardInterface
{
Q_OBJECT

// OK

public:
CustomWidget(QWidget *parent = 0);
void cut();
void copy() const;
void paste();
private:
ClipboardWrapper *wrapper;
Q_DISABLE_COPY(CustomWidget)
};
class ClipboardWrapper : public QObject, public ClipboardInterface
{
Q_OBJECT
public:
ClipboardWrapper(QObject *parent): QObject(parent)

{
Q_ASSERT(parent);
wrappedObject = qobject_cast<CustomWidget *>(parent);
Q_ASSERT(wrappedObject);
}
public slots:
void cut() { wrappedObject->cut(); }
void copy() const { wrappedObject->copy(); }
void paste() { wrappedObject->paste(); }
private:
ClipboardInterface *wrappedObject;
Q_DISABLE_COPY(ClipboardWrapper)
};

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/qq/qq15-academic.html#multipleinheritance

It's only possible to connect a signal to a slot or a signal to another signal [QT-03-3]
DESCRIPTION
Connecting a signal and a slot can be done by calling QObject::connect.
It's only possible to connect a signal to a slot or a signal to another
signal.

BENEFITS
Slots are to be considered observers, and are not possible to connect
together
as there would be no source of signal to trigger the slots. However, you
may
connect several slots to one signal. A slot cannot have a signal connected
to
it, but a signal can have a slot connected to it; the direction of the
connection is important. You can connect as many signals as you want to a
single
slot, and a signal can be connected to as many slots as you need. It is
even
possible to connect a signal directly to another signal.
(This will emit the second signal immediately whenever the first is
emitted.)

EXAMPLE
#include <QtCore/QObject>
class MyQObject: public QObject
{
Q_OBJECT
public:
MyQObject();
public slots:
int sampleSlot(QString qStr, const MyQObject& myQObjRef, int* i);
signals:
void someSignal(QString qStr);

private:
Q_DISABLE_COPY(MyQObject)
};
void myFunction(QString qStr)
{
MyQObject obj1, obj2;
QObject::connect(&obj1,
//
Violation
SLOT(sampleSlot(QString, const MyQObject&, int*)),
&obj2, SIGNAL(someSignal(QString)));
QObject::connect(&obj1,
//
Violation
SLOT(sampleSlot(QString, const MyQObject&, int*)),
&obj2, SLOT(sampleSlot(QString, const MyQObject&,
int*)));
}

REPAIR
#include <QtCore/QObject>
class MyQObject: public QObject
{
Q_OBJECT
public:
MyQObject();
public slots:
int sampleSlot(QString qStr, const MyQObject& myQObjRef, int* i);
signals:
void someSignal(QString qStr);
private:
Q_DISABLE_COPY(MyQObject)
};
void myFunction(QString qStr)
{
MyQObject obj1, obj2;
QObject::connect(&obj1, SIGNAL(someSignal(QString)),

// OK

&obj2, SIGNAL(someSignal(QString)));
QObject::connect(&obj1, SIGNAL(someSignal(QString)),
// OK
&obj2, SLOT(sampleSlot(QString, const MyQObject&,
int*)));
}

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/signalsandslots.html

The methods inside the SIGNAL and SLOT macros have to exist [QT-04-1]
DESCRIPTION
The methods inside the SIGNAL and SLOT macros have to exist (the arguments
have to match) and they have to be tagged as Q_SLOTS or Q_SIGNALS.
Here we have a simple example where we try to output a goodbye message,
note
that the name of the slot in the connection doesn't match the declaration.
The example will compile and run, but not produce the expected result.

NOTES
"Q_SLOTS" and "Q_SIGNALS" is equivalent to "slots" and "signals".

BENEFITS
Qt's signal & slot mechanism is very powerful since it offers dynamic
connections between signals and slots at runtime. This supports
development
of flexible scriptable and dynamic user interfaces, but comes with a
price:
The compiler won't warn you if a signal and slot connection is invalid at
compile time. You will get a warning at run time, which is usually too
late.
This rule enforces validity of signal and slot connection at code analysis
time.

EXAMPLE
#include <QtGui/QtGui>
class MyWidget: public QWidget
{
Q_OBJECT
public:
MyWidget( char* initText ) { qDebug() << initText; }
public slots:
void showGoodByeMessage() { qDebug() << "GoodBye"; }
private:

Q_DISABLE_COPY(MyWidget)
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWidget w1( "New MyWidget" );
MyWidget w2( "New MyWidget" );
w1.show();
w2.show();
// Violation showGoodBye() is not slot method
QObject::connect(&app, SIGNAL(lastWindowClosed()),
&w1, SLOT(showGoodBye()));
return app.exec();
}

REPAIR
#include <QtGui/QtGui>
class MyWidget: public QWidget
{
Q_OBJECT
public:
MyWidget( char* initText ) { qDebug() << initText; }
public slots:
void showGoodByeMessage() { qDebug() << "GoodBye"; }
private:
Q_DISABLE_COPY(MyWidget)
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWidget w1( "New MyWidget" );
MyWidget w2( "New MyWidget" );
w1.show();

w2.show();
// OK
QObject::connect(&app, SIGNAL(lastWindowClosed()),
&w1, SLOT(showGoodByeMessage()));
return app.exec();
}

REFERENCES
Recommended by Parasoft and Trolltech

Mark signal emissions with the keyword "emit" to distinguish a signal emission from a normal
method call [QT-05-3]
DESCRIPTION
Signal emissions should be marked with the keyword "emit",
to distinguish a signal emission from a normal method call.

BENEFITS
"emit" expands to nothing, so it's not necessary, but considered good
style.

EXAMPLE
#include <QtCore/QObject>
class QFigure : public QObject
{
Q_OBJECT
public:
void someSignal(double);
void test();
signals:
void someSignal(int);
private:
Q_DISABLE_COPY(QFigure)
};
void QFigure::test()
{
emit someSignal(1);
emit someSignal(1.5); // Violation - someSignal(double) is not a signal
someSignal(1);
// Violation - emit keyword omitted
someSignal(1.5);
}

REPAIR
#include <QtCore/QObject>
class QFigure : public QObject
{
Q_OBJECT
public:
void someSignal(double);
void test();
signals:
void someSignal(int);
private:
Q_DISABLE_COPY(QFigure)
};
void QFigure::test()
{
emit someSignal(1);
someSignal(1.5);
emit someSignal(1);
someSignal(1.5);
}

// OK
// OK

REFERENCES
Recommended by Parasoft and Trolltech

Do not set Idle or Critical priority to QThreads. Use High/Low/Med only [QT-06-3]
DESCRIPTION
Do not set Idle or Critical priority to QThreads. Use High/Low/Med only.

BENEFITS
Idle and Critical settings can cause live-lock or starvation.
Some Operating Systems will not allow escalating the priorities of
threads,
so the results are platform specific.

EXAMPLE
#include <QtGui/QtGui>
void myFunction( QThread* qt1, QThread* qt2 ) {
qt1->start( QThread::IdlePriority );
qt2->setPriority( QThread::IdlePriority );
}

// Violation
// Violation

REPAIR
#include <QtGui/QtGui>
void myFunction( QThread* qt1, QThread* qt2 ) {
qt1->start( QThread::NormalPriority );
qt2->setPriority( QThread::InheritPriority );
}

REFERENCES
Recommended by Parasoft and Trolltech

// OK
// OK

Do not force thread termination by calling QThread::terminate() [QT-07-1]


DESCRIPTION
Do not force thread termination by calling QThread::terminate().

BENEFITS
This function is dangerous and its use is discouraged. The thread may or
may
not be terminated immediately, depending on the operating systems
scheduling
policies. The thread can be terminate at any point in its code path.
Threads
can be terminated while modifying data. There is no chance for the thread
to
cleanup after itself, unlock any held mutexes, etc.

EXAMPLE
#include <QtGui/QtGui>
class MyQThread : public QThread
{
Q_OBJECT
public:
void terminate();
void run();
MyQThread();
private:
Q_DISABLE_COPY(MyQThread)
};
void MyQThread::terminate()
{
QThread::terminate(); // Violation
}
void foo(){
MyQThread qt;

qt.terminate();
}

REPAIR
Do not use QThread::terminate(). Return from the thread's run() function
instead, or throw an exception and catch it at the end of run().

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qthread.html#terminate

If using lock on a mutex in a function, release the lock in the same function [QT-08-3]
DESCRIPTION
If using lock on a mutex in a function, release the lock in the same
function.

BENEFITS
Not unlocking a locked mutex in the same function may lead to inconsistent
locks and unlocks, which will in turn lead to potential deadlocks in your
code.
To ensure that a locked mutex is always unlocked when the function ends,
both
by normal and exception code paths, consider using the QMutexLocker
convenience
class.

EXAMPLE
#include<QtGui/QtGui>
void myExample(bool isBlue, bool isFigure)
{
QMutex m;
QMutex n;
m.lock();
if (isBlue && isFigure)
return;

// Violation

m.unlock();
/* code */
m.lock();
n.lock();
}

REPAIR

// Violation
// Violation

#include<QtGui/QtGui>
void myExample(bool isBlue, bool isFigure)
{
QMutex m;
QMutex n;
m.lock();

// OK

if (isBlue && isFigure){


m.unlock();
return;
// OK
}else{
m.unlock();
}
m.lock();
n.lock();

// OK
// OK

/* code */
m.unlock();
n.unlock();

// OK
// OK

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qmutex.html#details

Do not call new on QMutexLocker [QT-09-1]


DESCRIPTION
Do not call new on QMutexLocker. The example shows the wrong usage
of QMutexLocker, the example compiles and works, but contains
a timebomb (deadlock after INT_MAX iterations). The code can be
fixed by putting the QMutexLocker on the stack.

BENEFITS
QMutexLocker is only a convenience class for locking and unlocking a
mutex.
The whole point is to keep the class on the stack, so an exception in your
code
will also release the mutex, should something fail.

EXAMPLE
#include <QtCore/QMutex>
#include <limits.h>
QMutex mutex;
int i = 0;
void increaseCounter()
{
QMutexLocker *locker = new QMutexLocker(&mutex);
if (i == INT_MAX) {
qDebug("WARNING: Maximum count reached!!");
return;
}
++i;
delete locker;
}

REPAIR
#include <QtCore/QMutex>
#include <limits.h>

// Violation

QMutex mutex;
int i = 0;
void increaseCounter()
{
QMutexLocker locker(&mutex);

// OK

if (i == INT_MAX) {
qDebug("WARNING: Maximum count reached!!");
return;
}
++i;
}

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qmutexlocker.html

Declare a copy constructor and operator= for any Qt - inherited objects that have pointers [QT10-3]
DESCRIPTION
The assignment operator and copy constructor should be private without
an implementation for all QObject subclasses.

BENEFITS
Classes which have pointers as members cannot be copied around with the
compiler implemented copy constructors or assignment operator, as that
will
break implicit sharing and may lead to unexpected crashes.

EXAMPLE
#include <QtGui/QtGui>
class MyQObject : public QObject
{
Q_OBJECT
};

// Violation

class MyQWidget : public QWidget


{
Q_OBJECT

// Violation

public:
MyQWidget( MyQWidget& );
MyQWidget& operator=( MyQWidget& );
};

REPAIR
#include <QtGui/QtGui>
class MyQObject : public QObject
{
Q_OBJECT

// OK

private:
MyQObject( MyQObject& );
MyQObject& operator=( MyQObject& );
};
class MyQWidget : public QWidget
{
Q_OBJECT
private:
Q_DISABLE_COPY(MyQWidget)
};

REFERENCES
Recommended by Parasoft and Trolltech

// OK

Do not use setWindowFlags function on a Widget [QT-11-4]


DESCRIPTION
Do not use setWindowFlags function on a Widget.

BENEFITS
Using setWindowFlags in your code can result in widgets which disappear
and
reappear, and change their looks. The widget is destroyed and recreated
for
each call. The setWindowFlags function should only be used on a widget is
not
yet shown.

EXAMPLE
#include <QtGui/QWidget>
class PreviewWindow : public QWidget
{
Q_OBJECT
public:
PreviewWindow( QWidget *parent = 0, Qt::WindowFlags flags = 0 );
void setWindowFlags( Qt::WindowFlags flags );
void setProperty( Qt::WindowFlags flags )
{
setWindowFlags( flags );
//
Violation
}
private:
Q_DISABLE_COPY(PreviewWindow)
};
void updatePreview( )
{
Qt::WindowFlags flags = 0;
PreviewWindow *previewWindow = new PreviewWindow( 0, flags );
PreviewWindow previewWindowObj( 0, flags );

previewWindow->setWindowFlags( flags );
Violation
previewWindowObj.setWindowFlags( flags );
Violation
}

//
//

REPAIR
#include <QtGui/QWidget>
class PreviewWindow : public QWidget
{
Q_OBJECT
public:
PreviewWindow( QWidget *parent = 0, Qt::WindowFlags flags = 0 );
void setWindowFlags( Qt::WindowFlags flags );
void setProperty( Qt::WindowFlags flags )
{
// OK
}
private:
Q_DISABLE_COPY(PreviewWindow)
};
void updatePreview( )
{
Qt::WindowFlags flags = 0;
PreviewWindow *previewWindow = new PreviewWindow( 0, flags );
PreviewWindow previewWindowObj( 0, flags );
}

REFERENCES
Recommended by Parasoft and Trolltech

// OK
// OK

Do not directly set specific Widget attributes that are set by Qt kernel [QT-12-1]
DESCRIPTION
Do not directly set specific Widget attributes that are set by Qt kernel.

BENEFITS
Qt uses the widget attributes to signal states to the rest of the
framework.
Altering the attributes which are set by the Qt kernel may have adverse
effects,
and in worst case make your application crash.

EXAMPLE
#include <QtGui/QWidget>
class PreviewWindow : public QWidget
{
Q_OBJECT
public:
PreviewWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0);
private:
Q_DISABLE_COPY(PreviewWindow)
};
void updatePreview( Qt::WindowFlags flags )
{
PreviewWindow *previewWindow = new PreviewWindow( 0, flags );
previewWindow->setAttribute(Qt::WA_UnderMouse, true);
previewWindow->setAttribute(Qt::WA_Disabled, true);
previewWindow->setAttribute(Qt::WA_SetPalette, true);
previewWindow->setAttribute(Qt::WA_SetCursor, true);
previewWindow->setAttribute(Qt::WA_SetFont, true);
previewWindow->setAttribute(Qt::WA_Disabled, true);
}

//
//
//
//
//
//

Violation
Violation
Violation
Violation
Violation
Violation

REPAIR
Do not directly set specific Widget attributes that are set by Qt kernel.

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qt.html#WidgetAttribute-enum

Never mix const and non-const iterators in assignment [QT-13-3]


DESCRIPTION
Never mix const and non-const iterators in assignment.

BENEFITS
When mixing const and non-const iterators you loose the benefits of using
const iterators, as the non-const iterator may detach the data it iterates
on.
Also, using non-const iterators on a const data set will not work, and
will
result in a compile error.

EXAMPLE
#include <QtGui/QWidget>
void myFunction()
{
QList<int> nonConstList;
for (QList<int>::ConstIterator it = nonConstList.begin(); ; ) //
Violation
{
}
}

REPAIR
#include <QtGui/QWidget>
void myFunction()
{
QList<int> nonConstList;
const QList<int> constList;
for (QList<int>::ConstIterator it = nonConstList.constBegin(); ; )
OK
{
}

//

for (QList<int>::ConstIterator cit = constList.begin(); ; )


OK
{
}
}

REFERENCES
Recommended by Parasoft and Trolltech

//

If you use Q_DECLARE_FLAGS, you must also use Q_DECLARE_OPERATORS_FOR_FLAGS


[QT-14-3]
DESCRIPTION
If you use Q_DECLARE_FLAGS, you must also use
Q_DECLARE_OPERATORS_FOR_FLAGS.

BENEFITS
Q_DECLARE_FLAGS creates a type-safe way of storing OR-combinations of enum
values. Q_DECLARE_OPERATORS_FOR_FLAGS declares a global operator|() for
these
type-safe flags, so they may be used outside the scope of where the flags
are declared.

EXAMPLE
#include <QtGui/QtGui>
enum Value { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Values,Value)

// Violation

REPAIR
#include <QtGui/QtGui>
enum Value { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Values,Value)
Q_DECLARE_OPERATORS_FOR_FLAGS(Values)

REFERENCES
Recommended by Parasoft and Trolltech

// OK

Q_DECLARE_OPERATORS_FOR_FLAGS must be in the global namespace,


Q_DECLARE_FLAGS inside the enum's namespace [QT-15-3]
DESCRIPTION
Q_DECLARE_OPERATORS_FOR_FLAGS must be in the global namespace,
Q_DECLARE_FLAGS inside the enum's namespace.

BENEFITS
By declaring the flags in the enums scope and the operators in the global
scope, you may type-safely OR together scoped flags. If either
Q_DECLARE_FLAGS
or Q_DECLARE_OPERATORS_FOR_FLAGS is in the wrong scope, you will not be
able
to OR together the flags anywhere in your code, even if you use the
correct
scopes on the flags.

EXAMPLE
#include <QtGui/QtGui>
namespace N
{
enum Value { FirstVal, SecondVal, ThirdVal };
namespace M
{
Q_DECLARE_FLAGS(Values, Value)
Q_DECLARE_OPERATORS_FOR_FLAGS(Values)
}
}
namespace S
{
enum Item { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Items, Item)
Q_DECLARE_OPERATORS_FOR_FLAGS(Items)
}

// Violation
// Violation

// Violation

REPAIR
#include <QtGui/QtGui>
namespace N
{
enum Value { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Values, Value)
}
Q_DECLARE_OPERATORS_FOR_FLAGS(N::Values)
namespace S
{
enum Item { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Items, Item)
}
Q_DECLARE_OPERATORS_FOR_FLAGS(S::Items)

REFERENCES
Recommended by Parasoft and Trolltech

// OK

// OK

// OK

// OK

The getters and setters of a Q_PROPERTY must exist and the types must match [QT-16-3]
DESCRIPTION
The getters and setters of a Q_PROPERTY must exist and the types must
match.

BENEFITS
The Q_PROPERTY macro tells the Qt meta type system how to get and set
a property. The property has a type, a name and getter and setter
methods. The getter should return the type of the property and have no
arguments, the setter should have exactly one argument that is either the
property's type or a const reference to the type.

EXAMPLE
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };
class MyQObject: public QObject

// Violation (wrong return type


// and only one argument allowed)

{
Q_OBJECT
Q_ENUMS(MyEnum)
Q_PROPERTY(MyEnum id READ id WRITE setId)
public:
void id();
void setId(MyEnum, int);

// wrong return type


// only one argument allowed

private:
Q_DISABLE_COPY(MyQObject)
};

REPAIR
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };

class MyQObject: public QObject


// OK
{
Q_OBJECT
Q_ENUMS(MyEnum)
Q_PROPERTY(MyEnum id READ id WRITE setId)
public:
MyEnum id();
void setId(MyEnum);
private:
Q_DISABLE_COPY(MyQObject)
};

REFERENCES
Recommended by Parasoft and Trolltech

Properties of enum types must use Q_ENUMS [QT-17-3]


DESCRIPTION
Properties of enum types must use Q_ENUMS. This makes sure that Qt
Designer
and other tools using the Qt introspection correctly recognize the
property.

BENEFITS
Q_ENUM registers an enum with the Qt meta-object system, so that a
property
of this type can be properly introspected. This lets Designer modify the
value
if it's a widget member, and QSA to alter the property value.

EXAMPLE
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };
class MyQObject: public QObject // Violation
{
Q_OBJECT
Q_PROPERTY(MyEnum id READ id WRITE setId)
public:
MyEnum id();
void setId(MyEnum);
private:
Q_DISABLE_COPY(MyQObject)
};

REPAIR
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };

class MyQObject: public QObject // OK


{
Q_OBJECT
Q_ENUMS(MyEnum)
Q_PROPERTY(MyEnum id READ id WRITE setId)
public:
MyEnum id();
void setId(MyEnum);
private:
Q_DISABLE_COPY(MyQObject)
};

REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/properties.html

Non-const function should not be called on the Qt object [QT-18-3]


DESCRIPTION
The violation is reported when the data is pulled out of the object
through
a non-const function for use in a const expression. For example, the
QList::at(int) is a const function, whereas operator[] (list_obj[i]) is a
non-const function. Since a non-const function is used the implicitly
shared class has no option but to detach its data from the shared data as
it
doesn't know if the user will actually use the data reference to alter it;
like in
list_obj[i] = 1234;
// Set new value
list_obj.at(i) = 1234; // Not possible, const T & at (int i) const
Note that this really depends on how clever the compiler is, as some
compilers
can understand that you meant the
const T & operator[] (int i) const
in some cases. But generally it is strongly suggested that developers
don't
rely on this, since if the compiler does not understand this difference
they
will have a potential huge speed loss with too many detachments of the
implicit
data sharing. So, in the cases where the developer knows a const variable
is
what he wants he should use the const-only function

SINCE
v7.0

BENEFITS
Qt has many implicitly shared classes. These classes share their data
(very little overhead), but will detach from one another, and do a deep
copy
(heavy, a "normal" copy and update of internal structures) when a nonconst

function is called on the object.

EXAMPLE
#include <QtCore/QList>
// Using the non-const operator[](int) function
int main(int argc, char **argv)
{
QList<int> list_obj;
list_obj << 10 << 100 << 1000;
QList<int> copy = list_obj; // Create a shared copy
for (int i = 0; i < list_obj.size(); ++i)
printf("Index %d: %d\n", i, list_obj[i]); // Violation, detaches
return 0;
}

REPAIR
#include <QtCore/QList>
// Using the const at(int) function
int main(int argc, char **argv)
{
QList<int> list_obj;
list_obj << 10 << 100 << 1000;
list_obj[1] = 20;

// OK
// OK

QList<int> copy = list_obj; // Create a shared copy


for (int i = 0; i < list_obj.size(); ++i)
printf("Index %d: %d\n", i, list_obj.at(i)); // OK
return 0;
}

REFERENCES
Recommended by Parasoft and Trolltech

SECURITY
Security
RULES
Avoid functions which use time from standard C library [SECURITY-01-2]
Avoid functions which use random numbers from standard C library
[SECURITY-02-2]
Usage of system properties should be restricted [SECURITY-03-2]
Use care to ensure that LoadLibrary() will load the correct library
[SECURITY-04-2]
Avoid using functions printf/wprintf with only one variable parameter
[SECURITY-05-2]
Avoid functions which use time from MFC library [SECURITY-06-3]
Don't use unsafe C functions that do write to range-unchecked buffers
[SECURITY-07-3]
Avoid using functions fprintf/fwprintf with only two parameters, when
second parameter is a variable [SECURITY-08-2]
Avoid using data() function from 'string' class of standard library
[SECURITY-09-2]
Avoid using vfork() function [SECURITY-10-2]
Avoid using unsecured shell functions that may be affected by shell
metacharacters [SECURITY-11-2]
Avoid using unsafe string functions which may cause buffer overflows
[SECURITY-12-2]
Avoid using unsafe string functions that do not check bounds [SECURITY-132]
Do not use scanf and fscanf functions without specifying variable size in
format string [SECURITY-14-2]
Do not print potentially sensitive information, resulting from an
application error into exception messages [SECURITY-15-2]
Never use gets() [SECURITY-16-1]
Avoid passing non-const parameters or variables into exec [SECURITY-17-2]
Avoid passing dynamically created strings into exec [SECURITY-18-2]
Usage of functions prone to race is not allowed [SECURITY-19-2]
Avoid passing user input into methods as parameters [SECURITY-20-2]
Do not use 'syslog' function for logging purposes [SECURITY-21-2]
Do not use mbstowcs() function [SECURITY-22-2]
Beware of functions which may return the current directory or the windows
directory [SECURITY-23-2]
Avoid using InitializeCriticalSection [SECURITY-24-2]
Avoid using thread-unsafe functions [SECURITY-25-2]
Do not use 'setuid' in source code [SECURITY-26-2]
Don't use chmod(), chown(), chgrp() [SECURITY-27-2]
Standard random number generators should not be used to generate
randomness for security reasons [SECURITY-28-2]

Do not use obsolete C routine ulimit() [SECURITY-29-2]


Avoid using 'getpw' function in program code [SECURITY-30-2]
Do not use 'cuserid' function [SECURITY-31-2]
Avoid using obsolete C routine 'usleep' [SECURITY-32-2]
Usage of functions which do not properly handle non-NULL terminated
strings is not allowed [SECURITY-33-2]
Avoid using environment variables [SECURITY-34-2]
Don't trust any value of command line if attacker can set them [SECURITY35-2]
Never use unfiltered data from an untrusted user as the format parameter
[SECURITY-36-2]
Do not use weak encryption functions [SECURITY-37-2]
Untrusted data is used as a loop boundary [SECURITY-38-2]

Avoid functions which use time from standard C library [SECURITY-01-2]


DESCRIPTION
This rule detects usage of time-related functions from the standard C
library
See also: MISRA2004-20_12

BENEFITS
Prevents the use of functions from standard C library,
which may open security holes.
Getting the current system time might be suspicious
and could lead to security problems
if used as a key for accessing sensitive information
or allow access to specific functions.
Do not use the following functions:
time, clock, ctime, gmtime, localtime, mktime, strftime.

EXAMPLE
#include <time.h>
void dangerFunction(time_t time);
int main ()
{
time_t rawtime;
tm * ptm;
time ( &rawtime );
// Violation
ptm = gmtime ( &rawtime ); // Violation
dangerFunction(rawtime);
return 0;
}

REPAIR
Remove usage of time-related functions from the standard C library

REFERENCES

1. David A. Wheeler, Programming Secure Applications for Unix-like Systems


(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid functions which use random numbers from standard C library [SECURITY-02-2]
DESCRIPTION
This rule detects the use of the following functions from standard C
library,
which generate random numbers:
-rand
-random
-randomize
-srand

BENEFITS
Prevents the use of functions that use random numbers from standard C
library.
Since rand() and similar functions use the last generated number
as the seed to create the next number,
it is possible to guess or calculate the next number.
Quite frequently, random session IDs for Web sessions
are generated with random number generator.
Since the random number generators from Standard C library
are not sufficiently strong,
hackers can guess the next number and spoof the sessions,
gaining access to privileged data.

EXAMPLE
#include <stdlib.h>
#include <time.h>
void main( void )
{
srand((unsigned)time( NULL ));
int y = rand();
}

// Violation
// Violation

REPAIR
Remove usage of rand(), random(), randomize(), srand() functions.

REFERENCES
1. http://www.dwheeler.com/flawfinder/
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
4. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-327
http://cwe.mitre.org/top25/#CWE-327

Usage of system properties should be restricted [SECURITY-03-2]


DESCRIPTION
This rule detects code that uses system properties, or environment
variables.

BENEFITS
By controlling use of environment variables in the applications, they are
made
more secure. Environment variables can be used as security holes.
If a malicious user passes a specifically crafted string into a running
program
via an environment variable, a buffer overflow attack can be launched.
On the other hand, if a program writes sensitive information
(such as a password) into an environment variable with putenv, it can be
captured and used to gain unauthorized privileges or access to sensitive
data.

EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *envvar;
envvar = getenv( "LIB" );
putenv( "LIB=c:\\mylib;c:\\yourlib" );
}

// Violation
// Violation

REPAIR
Do not use system properties and environment variables in source code.

REFERENCES
1. https://buildsecurityin.uscert.gov/portal/article/knowledge/coding_rules/RULE_0051.xml
2. PCI Data Security Standard (PCI DSS) Version 1.2

Requirement 6: Develop and maintain secure systems and applications

Use care to ensure that LoadLibrary() will load the correct library [SECURITY-04-2]
DESCRIPTION
"Ensure that you specify a fully-qualified filename for the library to
ensure
that the correct library is always loaded.
When a library needs to be loaded you should consider using LoadLibraryEx
with
the LOAD_WITH_ALTERED_SEARCH_PATH parameter to ensure that the correct
library
is loaded."
The rule reports a violation if in code is used the function LoadLibrary
or the function LoadLibraryEx without LOAD_WITH_ALTERED_SEARCH_PATH
argument.

NOTES
"If you cannot use LoadLibraryEx, ensure that the lpszFileName parameter
is a fully qualified filename, including the file extension. If it is not
fully
qualified, then the intended module can be substituted by an attacker.
Also, the system will use '.dll' for the file extension if it is not
specified,
so '.' should be appended to the end if the intended library file does not
have
an extension."

BENEFITS
The use of this rule prevents than an attacker could inject a Trojan horse
DLL
within your process by placing a 'tainted' DLL in a location in the DLL
search
path that is found before the intended DLL.

EXAMPLE
#include <windows.h>
void foo()

{
HMODULE hModule1 = LoadLibrary(TEXT("someapp.dll"));

// Violation

HMODULE hModule2 = LoadLibraryEx(


TEXT("someapp.dll"),
NULL,
0
);

// Violation

REPAIR
#include <windows.h>
void foo()
{
HMODULE hModule = LoadLibraryEx(
TEXT("C:\\The\\Right\\Directory\\someapp.dll"),
NULL,
LOAD_WITH_ALTERED_SEARCH_PATH
);
}

// OK

REFERENCES
1. https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/766BSI.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid using functions printf/wprintf with only one variable parameter [SECURITY-05-2]
DESCRIPTION
This rule detects the use of the functions printf/wprintf with only one
variable parameter and no format specifiers.

BENEFITS
This rule prevents security attack using format strings. If a printf
functions
is passed a variable without format specifiers, the variable can contain
a cleverly formatted string (including format characters %n, %x, and %s)
that can be used to execute malicious instructions or crash the
application.

EXAMPLE
#include <wchar.h>
#include <stdio.h>
void foo( ) {
char* caption = "caption";
wchar_t widechar = L'x';
printf( caption );
wprintf( &widechar );

// Violation
// Violation

REPAIR
#include <wchar.h>
#include <stdio.h>
void foo( ) {
char* caption = "caption";
wchar_t wch = L'x';
int k = 7;
printf( "char: %s", caption );
printf( "int: %s", k );

// OK
// OK

wprintf( L"wide char:%ls", wch );// OK


wprintf( L"int: %d ", k );
// OK
}

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/controlformatting.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-134
http://cwe.mitre.org/top25/#CWE-134

Avoid functions which use time from MFC library [SECURITY-06-3]


DESCRIPTION
This rule detects usage of time-related functions from MFC library.

BENEFITS
Prevents the use of functions from MFC library, which may open security
holes.
Getting the current system time might be suspicious and could lead to
security
problems if used as a key for accessing sensitive information or allow
access
to specific functions. Do not use the following functions:
- GetTime
- GetYear
- GetMonth
- GetDay
- GetHour
- GetMinute
- GetSecond
- GetDayOfWeek

EXAMPLE
#include <afx.h>
void dangerFunction(time_t t);
int main () {
CTime t(NULL);
time_t Time = t.GetTime(); // Violation
t.GetHour();
// Violation
t.GetMinute();
// Violation
dangerFunction(Time);
return 0;
}

REPAIR
Remove usage of functions from MFC library, which may open security hole.

REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Don't use unsafe C functions that do write to range-unchecked buffers [SECURITY-07-3]


DESCRIPTION
Don't use the unsafe C legacy: strcpy, strcat, sprintf, vsprintf, gets,
strncpy, strncat, snprintf, fgets - functions that do write to rangeunchecked
buffers, and/or do not check and correctly handle out-of-bounds errors.
See also: SECURITY-12,SECURITY-13,SECURITY-16

BENEFITS
Rule prevents using functions which may cause overflow.

EXAMPLE
#include <string.h>
void foo( void ) {
char* str1 = "testcase";
char* str2 = "testcase";
char* str3 = 0;
str3 = strcat( str1, str2 );
}

// Violation

REPAIR
Don't use the unsafe C legacy.

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 99
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid using functions fprintf/fwprintf with only two parameters, when second parameter is a
variable [SECURITY-08-2]
DESCRIPTION
This rule detects the use of the functions fprintf/wfprintf with two
parameters
and no format specifiers, when second parameter is a variable parameter.

BENEFITS
This rule prevents security attack using format strings.
If a fprintf functions is passed a variable without format specifiers,
the variable can contain a cleverly formatted string
(including format characters %n, %x, and %s) that can be used to execute
malicious instructions or crash the application.

EXAMPLE
#include <stdio.h>
#include <wchar.h>
void foo( ) {
FILE *stream;
char
c = '\n';
wchar_t d=8;
stream = fopen( "fprintf.out", "w" );
fprintf( stream, &c );
fwprintf( stream, &d );
fclose( stream );
}

REPAIR
#include <stdio.h>
#include <wchar.h>
void foo( ) {
FILE *stream;

// Violation
// Violation

int
i = 10;
char
s[] = "example string";
char
c = '\n';
unsigned short d=8;
stream = fopen( "fprintf.out", "w" );
fprintf( stream,"abcd");
// OK
fprintf( stream, "%s%c", s, c );// OK
fprintf( stream, "%d\n", i );
// OK
fwprintf(stream,L"abc:%d",i);
fwprintf(stream,L"abcd");

// OK
// OK

fclose( stream );
}

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/controlformatting.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-134
http://cwe.mitre.org/top25/#CWE-134

Avoid using data() function from 'string' class of standard library [SECURITY-09-2]
DESCRIPTION
This rule detects code that uses the data() member function from string
class
of standard library.

BENEFITS
String::data() returns the character string contained in the string object
without a terminating character. In certain contexts, especially when
interfacing with C-style legacy code, this may lead to buffer overflows
and other string-related security vulnerabilities.
Instead of using the data() function, use c_str(),
which always returns a terminated string.

EXAMPLE
#include <string>
void bar(const char* param);
void foo()
{
using namespace std;
string str1 ( "example string" );
bar(str1.data());
// Violation
string *ptr;
ptr=&str1;
const char *ptr2 =

ptr->data();

REPAIR
#include <string>
void bar(const char* param);

// Violation

void foo()
{
using namespace std;
string str1 ( "example string" );
bar(str1.c_str());
string *ptr;
ptr=&str1;
const char *ptr2 =

ptr->c_str();

// OK

// OK

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/libraryc.html#STD-STRING
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid using vfork() function [SECURITY-10-2]


DESCRIPTION
This rule detects code that uses vfork() functions.

BENEFITS
Prevents the use of the vfork() function,
which can easily fail when the code changes
or even when the compiler version changes.
There are a number of problems with vfork().
From a portability point-of-view,
the problem with vfork() is that it's actually fairly tricky
for a process to not interfere with its parent,
especially in high-level languages.
The "not interfering" requirement applies to the actual machine code
generated,
and many compilers generate hidden temporaries
and other code structures that cause unintended interference.
Use the fork() function instead of the vfork() function.

EXAMPLE
#include <unistd.h>
void main( void )
{
vfork( ); // Violation
}

REPAIR
#include <unistd.h>
void main( void )
{
fork( ); // OK
}

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoidvfork.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid using unsecured shell functions that may be affected by shell metacharacters
[SECURITY-11-2]
DESCRIPTION
This rule detects code that uses environment functions:
popen, system, execlp, execvp, _exec, exec
According to David A. Wheeler (see reference below):
"Many systems, such as the command line shell and SQL interpreters,
have "metacharacters" - characters that are not interpreted as data.
Those characters are: { & ; ` ' \ " | * ? ~ < > ^ ( ) [ ] { } $ \n \r }.
Such characters might commands, or delimit data from commands or other
data.
If your program invokes those other systems and allows attackers to insert
such metacharacters, the usual result is that an attacker can completely
control your program.
What makes the shell metacharacters particularly pervasive is that several
important library calls, such as popen() and system() are implemented
by calling the command shell, meaning that they will be affected by shell
metacharacters too.
Similarly, execlp() and execvp() may cause the shell to be called.
Many guidelines suggest avoiding popen(), system(), execlp(), execvp()
entirely and use execve() directly in C when trying to spawn a process."

BENEFITS
Prevents the use of unsecured shell functions.

EXAMPLE
#ifdef __GNUC__
#include <unistd.h>
#else
#include <process.h>
#endif
void main( void ) {
execl( "c:\\command.com", "", "_execl", "", "" );
}

// Violation

REPAIR
Do not use unsecured system functions in your program.

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/handlemetacharacters.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Avoid using unsafe string functions which may cause buffer overflows [SECURITY-12-2]
DESCRIPTION
This rule detects code that uses unsafe string functions from C library:
strcpy, strcat, sprintf, vsprintf, gets
According to David A. Wheeler (see reference below),
"C functions users must avoid using dangerous functions
that do not check bounds unless they've ensured
that the bounds will never get exceed.
Functions to avoid in most cases (or ensure protection) include the
functions
strcpy(), strcat(), sprintf() (with cousin vsprintf()), and gets().
These should be replaced with functions such as
strncpy(), strncat(), snprintf(), fgets(), respectively."
See also; SECURITY-12,SECURITY-13, SECURITY-16

BENEFITS
Prevents the use of functions which may cause buffer overflows.

EXAMPLE
#include <string.h>
void test()
{
char buffer[16];
strcpy(buffer, "To be ");
strcat(buffer, "or not to be");
}

// Violation
// Violation

REPAIR
#include <string.h>
void test()
{
char buffer[16];
strncpy(buffer, "To be ", 7);
strncat(buffer, "or not to be", 6);

// OK
// OK

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dangersc.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Avoid using unsafe string functions that do not check bounds [SECURITY-13-2]
DESCRIPTION
This rule detects code that uses unsafe string functions:
scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf, realpath,
getopt, getpass, streadd, strecpy, strtrns, getwd, snprintf
According to David A. Wheeler (see reference below),
"C functions users must avoid using dangerous functions
that do not check bounds unless they've ensured
that the bounds will never get exceeded.
The function strlen() should be avoided
unless you can ensure that there will be a terminating NIL character to
find.
The scanf() family (scanf(), fscanf(), sscanf(), vscanf(), vsscanf(),
and vfscanf()) is often dangerous to use;
do not use it to send data to a string without controlling the maximum
length
(the format %s is a particularly common problem).
Other dangerous functions that may permit buffer overruns
(depending on their use) include realpath(), getopt(), getpass(),
streadd(),
strncpy(), and strtrns().
You must be careful with getwd();
the buffer sent to getwd() must be at least PATH_MAX bytes long.
The select() helper macros FD_SET(), FD_CLR(), and FD_ISSET()
do not check that the index fd is within bounds;
make sure that fd >= 0 and fd <= FD_SETSIZE
(this particular one has been exploited in pppd).
Unfortunately, snprintf()'s variants have additional problems.
Officially, snprintf() is not a standard C function
in the ISO 1990 (ANSI 1989) standard,
though sprintf() is, so not all systems include snprintf()
others call sprintf directly what could make horrible thing."
See also: SECURITY-07,SECURITY-12, SECURITY-16

BENEFITS
Prevents the use of functions which may cause overflows.

EXAMPLE

#include <stdio.h>
void main( void ) {
char* str = 0;
scanf( "%s", str );
}

// Violation

REPAIR
Remove usage of unsafe string functions.

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dangersc.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Do not use scanf and fscanf functions without specifying variable size in format string
[SECURITY-14-2]
DESCRIPTION
This rule detects code that uses 'scanf' and 'fscanf' functions
without specifying variable size in format string.

BENEFITS
Typically, scanf functions are used to read user-specified parameters
into arrays of variables.
Unless the size of variables in format strings is specified,
an attacker may use crafted strings to exploit buffer overflows
with fixed size arrays.
By requiring to constrain the format specification using variable sizes,
the rule prevents this security vulnerability.

EXAMPLE
#include <stdio.h>
void main( ) {
char tcChar[10];
char cChar;
float fFloat;
FILE *stream;
stream = fopen( "fprintf.out", "w" );
scanf("%s",&tcChar);
scanf("%f",&fFloat);

// Violation
// Violation

fscanf(stream,"%s",&tcChar);
// Violation
fscanf(stream,"%c%f",&cChar,&fFloat); // Violation
}

REPAIR
#include <stdio.h>
void

main( ) {

char tcChar[10];
char cChar;
float fFloat;
FILE *stream;
stream = fopen( "fprintf.out", "w" );
scanf("%c",&cChar);
scanf("%10s",&tcChar);
scanf("%5f",&fFloat);

// OK
// OK
// OK

fscanf(stream,"%c",&cChar);
fscanf(stream,"%10s",&tcChar);
fscanf(stream,"%5f",&fFloat);

// OK
// OK
// OK

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/ccpp.html
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO
/control-formatting.html
https://buildsecurityin.us-cert.gov/portal/article/knowledge
/coding_rules/RULE_0119.xml
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Do not print potentially sensitive information, resulting from an application error into
exception messages [SECURITY-15-2]
DESCRIPTION
Do not print potentially sensitive information,
resulting from an application error into exception messages.
Rule disallows printing messages in catch block.

BENEFITS
Prevents the application from leaking potentially sensitive information,
resulting from an application error.

EXAMPLE
#include <stdlib.h>
#include <stdio.h>
class LoginException{
public:
int tmp;
char* getMessage();
};
class CLogin {
public:
void login(){};
};
void log( char *text){};
void foo( int i ) {
CLogin lc;
try {
lc.login();
} catch (LoginException le1) {
// login failed
::printf( le1.getMessage() ); // Violation
exit( 1 );
}
}

REPAIR
#include <stdlib.h>
#include <stdio.h>
class LoginException{
public:
int tmp;
char* getMessage();
};
class CLogin {
public:
void login(){};
};
void log( char *text){};
void foo( int i ) {
CLogin lc;
try {
lc.login();
} catch (LoginException le2) {
exit( 1 );
}
}

// OK

REFERENCES
1. http://www.atsec.com/downloads/pdf/secure-coding-guidelines.pdf
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Never use gets() [SECURITY-16-1]


DESCRIPTION
"Never use gets(). Because it is impossible to tell without knowing the
data
in advance how many characters gets() will read, and because gets() will
continue to store characters past the end of the buffer, it is extremely
dangerous to use. It has been used to break computer security. Use fgets()
instead."
See also: SECURITY-07,SECURITY-12,SECURITY-13

BENEFITS
Prevents the use of function which may cause buffer overflows.

EXAMPLE
#include <stdio.h>
void main( ) {
char line[100];
printf( "Input a string: " );
gets( line );
printf( "The line entered was: %s\n", line );

// Violation

REPAIR
#include <stdio.h>
void main( ) {
char line[100];
printf( "Input a string: " );
fgets( line, 100, stdin );
printf( "The line entered was: %s\n", line );
}

// OK

REFERENCES
1. Linux Programmer's Manual (3),
http://trajano.us.es/clases/lcd/man/man3/ungetc.3.html
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
4. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Avoid passing non-const parameters or variables into exec [SECURITY-17-2]


DESCRIPTION
This rule detects code that passes dynamically created strings in to exec.
Note: Rule checks if parameter or variable passed to exec is not const
See also: SECURITY-18

BENEFITS
An attacker can potentially insert a malicious string fragment
into a dynamically created string.
Such fragment may allow the attacker to execute a specified command,
resulting in a security breach.

EXAMPLE
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#define _execl execl
#else
#include <process.h>
#endif
void foo( ) {
char *param = "C:\\command.com";
_execl( param, "", "_execl", "", NULL );
}

REPAIR
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#define _execl execl
#else
#include <process.h>
#endif
void foo( ) {

// Violation

_execl( "C:\\command.com", "", "_execl", "", NULL ); // OK


}

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid passing dynamically created strings into exec [SECURITY-18-2]


DESCRIPTION
Avoid passing dynamically created strings into exec.
Rule checks if string variables, parameters, or values
are not passed to exec() method.
See also: SECURITY-17

BENEFITS
Prevents running native applications. Having string variables passed into
an exec() method could provide system access to an outside program.
Server applications should never access native applications.

EXAMPLE
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#include <string.h>
#define _execl execl
#else
#include <process.h>
#endif
class MyClass {
public:
char* text( );
};
void foo( char* prog ) {
MyClass *v1 = 0;
char * v4=v1->text();
prog = strcat( "c:\\", "command.com" );
_execl( prog, "", "_execl", "", NULL );
// Violation
_execl( v1->text(), "", "_execl", "", NULL );// Violation
_execl( v4, "", "_execl", "", NULL );
// Violation
}

REPAIR
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#define _execl execl
#else
#include <process.h>
#endif
void foo( char* prog ) {
_execl( "C:\\command.com", "", "_execl", "", NULL );
}

// OK

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Usage of functions prone to race is not allowed [SECURITY-19-2]


DESCRIPTION
A "race condition" can be defined as "Anomalous behavior due to unexpected
critical dependence on the relative timing of events".
Race conditions generally involve one or more processes accessing
a shared resource (such a file or variable),
where this multiple access has not been properly controlled.
Rule checks if the following functions are used:
access, creat, pathconf, opendir, dirname, scandir,
fopen, lstat, stat, open, rename, remove, lexecve,
execl, execlp, execle, execv, execvp, freopen, mktemp,
link, unlink

BENEFITS
Rule prevents anomalous behavior of race conditions functions.

EXAMPLE
#ifdef __GNUC__
#include <unistd.h>
#include <stdlib.h>
#else
#include <io.h>
#endif
void foo( ) {
access( "path", 0 );
unlink( "/pathname" );
mktemp( "template" );
}

// Violation
// Violation
// Violation

REPAIR
Remove usage of prone to race functions.

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoidrace.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid passing user input into methods as parameters [SECURITY-20-2]


DESCRIPTION
Avoid passing user input into methods as parameters.

BENEFITS
Using direct user input in the application can open doors
to buffer overflow and SQL injection attacks.
User input must be validated before being processed by the application.

EXAMPLE
#include <iostream>
#include <stdio.h>
using namespace std;
void function( int param );
void foo( int param ) {
int var1;
int var2=0;
cin >> var1;
function( var1 );// Violation
scanf( "%d", &var2 );
function( var2 );// Violation
}

REPAIR
#include <iostream>
#include <stdio.h>
using namespace std;
void function( int param );
void foo( ) {
int var1 = 0;
int var2 = 0;
cin >> var1;
// part of code manipulating var1 without using function with var1 as
parameter

scanf( "%d", &var2 );


// part of code manipulating var2 without using function with var2 as
parameter
}

REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Do not use 'syslog' function for logging purposes [SECURITY-21-2]


DESCRIPTION
Method 'syslog' should not be used for logging purposes.
This function does not check the validity of
file system environment variable.

BENEFITS
Rule prevents using insecure 'syslog' function.

EXAMPLE
#include <syslog.h>
int main()
{
syslog(LOG_INFO, "Some info"); // Violation
}

REPAIR
Do not use 'syslog' function in your code.

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Do not use mbstowcs() function [SECURITY-22-2]


DESCRIPTION
Function mbstowcs() should not be used.
Internal stack allocated buffer can be overflown in some versions.

BENEFITS
Rule prevents using unsafe mbstowcs() function.

EXAMPLE
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
int i;
char
*pmbhello = (char *)malloc( MB_CUR_MAX );
wchar_t *pwc
= (wchar_t *)malloc( sizeof( wchar_t ));
i = mbstowcs( pwc, pmbhello, MB_CUR_MAX );

// Violation

REPAIR
Do not use mbstowcs().

REFERENCES
1. https://buildsecurityin.uscert.gov/portal/article/knowledge/coding_rules/RULE_0072.xml
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Beware of functions which may return the current directory or the windows directory
[SECURITY-23-2]
DESCRIPTION
The rule reports a violation if in code is used the function
GetTempPath().
"GetTempPath() returns the file path to the temporary directory.
GetTempPath() raises two concerns. First, a buffer overflow condition
could
exist if the path to the temporary directory is longer than the buffer
allocated to store this information. Second, a path to an insecure
directory
could be returned. Also, Windows does not guarantee that the returned
paths
are valid or useable (e.g. writable) for temporary files."

BENEFITS
"An attacker could take advantage of either weakness in the functionality
of GetTempPath(). First, if Windows returns a path to which the attacker
can read or write (e.g. c:\temp), he or she will be able to read or alter
any data in the temporary files. This would result in a breach
of confidentiality and integrity, respectively.
The second attack vector is to implement a buffer overflow attack.
There is no indication that the value in any of the environment
variables (TMP, TEMP) is truncated to MAX_PATH. Therefore, an attacker
could specify an environment variable whose length is longer than that
of the path buffer if the buffer's length is not set properly. When the
program was run in this environment, the path buffer would be overflowed."
The rule prevents such attacks.

EXAMPLE
#include <afx.h>
const char * virus_temp_sig = "XXX";
char * get_temp_file()
{
char wintemp_path[1024];

char *temp_path=new char[1024];


GetTempPath(1024,wintemp_path);
//
Violation
GetTempFileName(wintemp_path,virus_temp_sig,1234,temp_path);
return temp_path;
}

REPAIR
Do not use the GetTempPath() functions or at least be careful what you
place
in locations returned by them.

REFERENCES
1. https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/758BSI.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid using InitializeCriticalSection [SECURITY-24-2]


DESCRIPTION
InitializeCriticalSection method should not be used in the code exceptions
can be thrown in low-memory situations.
InitializeCriticalSectionAndSpinCount should be used instead.
When 'InitializeCriticalSectionAndSpinCount' method is used the calling
thread
avoids the wait operation when the critical section becomes free during
the
spin operation.

BENEFITS
Rule improve the performance by choosing a small spin count for a critical
section of short duration.

EXAMPLE
#define _WIN32_WINNT 0x0501
#include <afx.h>
class Queue {
public:
Queue(int limit)
{
InitializeCriticalSection(&lock);
}
~Queue()
{
::DeleteCriticalSection(&lock);
}
void AddTail()
{
::EnterCriticalSection(&lock);
::LeaveCriticalSection(&lock);
}
protected:

// Violation

CRITICAL_SECTION lock;
};

REPAIR
#define _WIN32_WINNT 0x0501
#include <afx.h>
class Queue1 {
public:
Queue1(int limit)
{
if (!InitializeCriticalSectionAndSpinCount(&lock, 0x80000400) )
OK
{
exit(0);
}
}
~Queue1()
{
::DeleteCriticalSection(&lock);
}
void AddTail()
{
::EnterCriticalSection(&lock);
::LeaveCriticalSection(&lock);
}
protected:
CRITICAL_SECTION lock;
};

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

//

Avoid using thread-unsafe functions [SECURITY-25-2]


DESCRIPTION
Thread-unsafe functions should not be used in the code.
Functions from thread-safe libraries should be used instead of e.g:
char *ttyname(int fildes);
int ttyname_r(int fildes, char *name, size_t namesize);
'ttyname_r' is safe thread and should be preferred.

NOTES
This rule is dedicated to the UNIX-like systems.

BENEFITS
Rule prevents using thread-unsafe functions which may
behave incorrectly when used in multi-threading programs.

EXAMPLE
#include <unistd.h>
void foo()
{
char *name = ttyname(1);
}

// Violation

REPAIR
#include <unistd.h>
void foo1()
{
char name[100];
int status = ttyname_r(1,name,100);
}

// OK

REFERENCES
1. http://docs.sun.com/app/docs/doc/816-5137/6mba5vpk6?a=view
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Do not use 'setuid' in source code [SECURITY-26-2]


DESCRIPTION
'setuid' method should not be used in source code.
If uid is to be changed, 'seteuid' should be rather used than 'setuid'.
As a backup 'setreuid' function should be used.
Thanks to it we may revert back to either the real uid
or previous saved one.

BENEFITS
Rule prevents using insecure 'setuid' function.

EXAMPLE
#include <sys/types.h>
#include <unistd.h>
int main()
{
setuid(34);
}

// Violation

REPAIR
#include <sys/types.h>
#include <unistd.h>
int main()
{
seteuid(34);
}

// OK

REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoidsetuid.html

2. PCI Data Security Standard (PCI DSS) Version 1.2


Requirement 6: Develop and maintain secure systems and applications

Don't use chmod(), chown(), chgrp() [SECURITY-27-2]


DESCRIPTION
Don't use chmod(), chown(), chgrp().
Use fchmod(), fchown() instead.
fchmod() is more efficient because it does not have to do
a separate look-up of the name, whereas chmod() must do so.

BENEFITS
Rule prevents using unsafe chmod(), chown(), chgrp() functions.

EXAMPLE
#include <sys/stat.h>
#include <sys/types.h>
void foo(const char* path)
{
chmod(path, S_IRWXU);
// Violation
}

REPAIR
#include <sys/stat.h>
#include <sys/types.h>
void goo(int fildes)
{
fchmod(fildes, S_IRWXU);
}

// OK

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Standard random number generators should not be used to generate randomness for security
reasons [SECURITY-28-2]
DESCRIPTION
Standard random number generators should not be used to
generate randomness for security reasons.
For security sensitive randomness a cryptographic randomness generator
that provides sufficient entropy should be used.
Rule detects usage of the following functions:
drand48, erand48, initstate, jrand48, cong48, lrand48, mrand48,
nrand48, seed48, setstate, srand48, strfry, memfrob, crypt, srandom

BENEFITS
Rule prevents using unsecured random number generators.

EXAMPLE
#include <stdlib.h>
void goo()
{
double rnumber = drand48(); // Violation
}

REPAIR
Do not use standard random number generators.

REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-327

http://cwe.mitre.org/top25/#CWE-327

Do not use obsolete C routine ulimit() [SECURITY-29-2]


DESCRIPTION
C routine ulimit() is considered obsolete.
Use getrlimit(), setrlimit(), or sysconf() instead.

BENEFITS
Rule prevents using unsafe, obsolete C routine.

EXAMPLE
#include <ulimit.h>
void foo(int cmd, long newlimit)
{
ulimit(cmd, newlimit); // Violation
}

REPAIR
#include <sys/types.h>
#include <sys/resource.h>
#include <unistd.h>
void foo(int who, struct rlimit *rlim)
{
getrlimit(who, rlim); // OK
}

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid using 'getpw' function in program code [SECURITY-30-2]


DESCRIPTION
Function 'getpw' is unsecured.
It may overflow the provided buffer.

BENEFITS
Rule prevents using insecure function 'getpw'.

EXAMPLE
#include <pwd.h>
#include <sys/types.h>
int main()
{
char* buf;
getpw(0,buf);
return 0;
}

// Violation

REPAIR
#include <pwd.h>
#include <sys/types.h>
int main()
{
char* buf;
struct passwd * ps = getpwuid(0); // OK
return 0;
}

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

2. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676


http://cwe.mitre.org/top25/#CWE-676

Do not use 'cuserid' function [SECURITY-31-2]


DESCRIPTION
Method 'cuserid' should not be used for logging purposes.
This function is poorly defined e.g.
different parameters are used under different systems.
It is not portable.
'curseid' may cause buffer overflow when the buffer is too small.
It is recommended to use 'getpwuid(geteuid())' instead.

BENEFITS
Rule prevents using insecure 'cuserid' function.

EXAMPLE
#include <unistd.h>
#include <stdio.h>
void foo( ) {
char * w = cuserid( "userName" );
}

// Violation

REPAIR
#include <sys/types.h>
#include <pwd.h>
void foo( ) {
struct passwd * t =
}

getpwuid( 12 );

// OK

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
2. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676

Avoid using obsolete C routine 'usleep' [SECURITY-32-2]


DESCRIPTION
The
The
and
and
Use

C routine 'usleep()' is considered to be obsolete.


interaction of this function with SIGALARM
other timer functions such as sleep(), alarm(), setitimer(),
nanosleep() is unspecified.
'nanosleep()' or 'setitimer()' instead.

BENEFITS
Rule prevents unspecified behaviour of obsolete 'usleep()' C routine.

EXAMPLE
#include <unistd.h>
int main()
{
usleep(7);
return 0;
}

// Violation

REPAIR
#include <time.h>
void foo(timespec *req, timespec *rem)
{
nanosleep(req, rem);
// OK
}

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Usage of functions which do not properly handle non-NULL terminated strings is not allowed
[SECURITY-33-2]
DESCRIPTION
"The strlen() function can be associated with problems if a string is not
null
terminated or if it is used in a way that causes a null terminator to be
lost.
The use of strlen() can easily cause off-by-one errors, since copying a
string
of length strlen(buf) actually requires copying strlen(buf)+1 characters
(including the null terminator). The resulting unterminated strings can
cause
subsequent problems when functions such as strlen() are run on them."
The rule reports violations if the following functions are used:
strlen, lstrlen, _tcslen, _mbslen, and wcslen.

BENEFITS
The rule prevents using functions that can cause buffer overflows
and security problems.

EXAMPLE
#include <string.h>
void foo()
{
char buffer[61] = "string example";
unsigned int len;
len = strlen(buffer);
// Violation
}

REPAIR
Do not use strlen, lstrlen, _tcslen, _mbslen, and wcslen functions.

REFERENCES

1. https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/852BSI.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Avoid using environment variables [SECURITY-34-2]


DESCRIPTION
Environment variables are highly untrusted input.
They may be of any length, and contain any data.
If it is possible avoid using them.
Rule detects usage of NLSPATH, LC_ALL, LC_MESSAGES,
and IFS environment variables.

BENEFITS
Rule prevents using NLSPATH, LC_ALL, LC_MESSAGES,
and IFS environment variables.

EXAMPLE
#include <locale.h>
void foo()
{
setlocale(LC_ALL,""); // Violation
}

REPAIR
Do not use described environment variables.

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Don't trust any value of command line if attacker can set them [SECURITY-35-2]
DESCRIPTION
Don't trust any value of command line if attacker can set them.

BENEFITS
Rule prevents using command line values which may be set by an attacker.

EXAMPLE
int main(int argc, char **argv)
{
int local = 0;
local += argc;
// Violation
return 1;
}

REPAIR
int main()
{
}

// OK

REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/commandline.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Never use unfiltered data from an untrusted user as the format parameter [SECURITY-36-2]
DESCRIPTION
Never use unfiltered data from an untrusted user as
a format parameter. Failing this guideline usually results
in a format string vulnerability. A particularly nasty case
is printf's %n conversion specification, which writes
the number of characters written so far into the pointer
argument; using this, an attacker can overwrite a value
that was intended for printing.
Rule checks if format parameter is used.

BENEFITS
Rule prevents attempts of overwriting a value that
was intended for printing.

EXAMPLE
#include <stdio.h>
void foo( char* stringFromUntrustedUser ) {
printf( stringFromUntrustedUser );
printf( "stringFromUntrustedUser" );
}

// Violation
// Violation

REPAIR
#include <stdio.h>
void foo( char* stringFromUntrustedUser ) {
const char *format = "%s";
printf( "%s",stringFromUntrustedUser );
printf( format, stringFromUntrustedUser );

// OK
// OK

REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),

http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

Do not use weak encryption functions [SECURITY-37-2]


DESCRIPTION
Rule reports a violation message when crypt() function is used or an
encrypt()
function is called with second parameter (edflag) equal '0'. If edflag is
0,
block passed as first parameter is encoded. In this encryption the
password
is cryptographically weak and can be deciphered. Also crypt() is
cryptographically weak and stronger alternatives should be preferred for
the
hashing of passwords.

SINCE
v7.2

BENEFITS
Rule detects weak encryption functions.

EXAMPLE
#include <unistd.h>
void myCrypt(const char* key, const char *salt)
{
char *hash = crypt(key, salt);
// Violation
/* ... */
}

REPAIR
Calls to crypt() and encrypt() should be replaced with a more secure
version.
The following libraries provide good choices:

*
*
*
*

OpenSSL (e.g. SHA1 function)


Crypto++
BSAFE - RSA Security's widely deployed commercial library
Cryptlib (Peter Gutmann)

REFERENCES
1. https://buildsecurityin.us-cert.gov/daisy/bsi-rules/home/g1/728.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-327
http://cwe.mitre.org/top25/#CWE-327

Untrusted data is used as a loop boundary [SECURITY-38-2]


DESCRIPTION
Rule reports a violation message if user input is directly used
as a loop boundary. Use of user input for a loop condition can
lead to a denial of service condition.
The following functions and objects are considered to return
untrusted user data:
extern istream cin;
int scanf(const char *format, ...);
int fscanf( FILE *stream, ...);
int fwscanf( FILE *stream, ...);
The rule does not report violation message if:
* the user input is used indirectly (e.g., num value from below
example is assigned to limit variable and the limit variable is
used for a loop condition)
/* ... */
scanf("%u",&num);
limit = num;
for (i = 0; i < limit; i++)
{

// user input is not directly used

}
* the user input is passed to function as pointer or reference
or it's value is changed in assignment statement

bool validateData(int, float, char*);


void example()
{
int n, i; float x; char name[50];
n = scanf("%d%f%s", &i, &x, name);
validateData(i, x, name)
validateData as pointer
while(name[param]);
while(name[i]);

// user input
// 'name' passed to
// OK
// Violation 'i'

x = 10;
while(name[x]);
value

// OK - user input x with new

}
See also: SECURITY-20.

SINCE
v7.2

BENEFITS
Rule prevents potential buffer overflow and SQL injection attacks.

EXAMPLE
#include <stdio.h>
void foo();
void iterateFoo()
{
unsigned num;
int i;
scanf("%u",&num);
for (i = 0; i < num; i++){
foo();
}
}

REPAIR
#include <stdio.h>
void foo();

// Violation

bool validate(unsigned int param);


void iterateFoo()
{
unsigned int num;
int i, limit;
scanf("%u",&num);
if(validate(num))
{
limit = num;
}else{
limit = 0;
}
for (i = 0; i < limit; i++){
foo();
}

// OK

REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications

STL
STL Best Practices
RULES
Instead of trying to write the container-independent code use class
encapsulation [STL-01-5]
To make copying efficient, correct, and immune to the slicing problem
create containers of pointers instead of containers of objects [STL-02-3]
Call empty instead of checking size() against zero [STL-03-3]
Avoid using iterative calls to insert in an explicit loop [STL-04-3]
Almost all uses of copy where the destination range is specified using an
insert iterator should be replaced with calls to range member functions
[STL-05-3]
Instead of anonymous istream_iterator objects use istream_iterator names
when used as function parameters [STL-06-3]
When using containers of newed pointers, remember to delete the pointers
before the container is destroyed [STL-07-3]
Never create containers of auto_ptrs [STL-08-3]
Avoid using remove algorithm with list and standard associative containers
[STL-09-3]
Prefer vector and string to dynamically allocated arrays [STL-10-3]
Consider using vector<char> instead of string [STL-11-4]
Use reserve to avoid unnecessary reallocations [STL-12-3]
Each vector and string should be checked if it is not empty before it is
passed to C function [STL-13-3]
Avoid using vector<bool> [STL-14-3]
Specify comparison types for associative containers of pointers [STL-15-3]
For associative containers never use comparison function returning true
for equal values [STL-16-3]
For associative containers never use comparison function returning true
for equal values [STL-17-3]
Prefer iterator to const iterator, reverse_iterator, and
const_reverse_iterator [STL-18-3]
Use distance and advance to convert a container's const_iterators to
iterators [STL-19-3]
It is necessary to be careful when using reverse_iterator's base iterator
for erasure purposes [STL-20-4]
Consider istreambuf_iterators for character-by-character input [STL-21-4]
Make sure destination ranges are big enough [STL-22-3]
Follow remove-like algorithms by erase if you really want to remove
something [STL-23-3]
Avoid using remove and similar algorithms (i.e., remove_if and unique) on
containers of dynamically allocated pointers [STL-24-3]
If you pass a sorted range to an algorithm that also takes a comparison
function, be sure that the comparison function you pass behaves the same

as the one you used to sort the range [STL-25-4]


Proper implementation of copy_if should not be based on returning the
remove_copy_if with a not1 in front of the predicate [STL-26-3]
If accumulate() is used on a container of floating point values, use
floating point value as initial one [STL-27-3]
Design functor classes for pass-by-value [STL-28-3]
Make predicates const pure functions [STL-29-3]
Each functor class should has only one operator() function, and it's
parameter and return types should be passed to unary_function or
binary_function [STL-30-3]
You must employ ptr_fun, mem_fun, or mem_fun_ref whenever you pass a
function to an STL component [STL-31-3]
Make sure less<T> means operator< [STL-32-3]
Prefer algorithm calls to hand-written loops [STL-33-3]
Prefer member functions to algorithms with the same names [STL-34-3]
Do not rely on the conversion of count()'s nonzero values to true and zero
to false [STL-35-3]
Do not use an iterator range that isn't really a range [STL-36-3]
Use vector and string instead of arrays [STL-37-3]
Use != instead of < to compare iterators [STL-38-3]
Use traits classes in conjunction with overloading [STL-39-3]
When calling swap, employ a using declaration for std::swap, then call
swap without namespace qualification [STL-40-3]
Do not declare the non-member to be an overloading of std::swap [STL-41-3]
Member version of swap should never throw exceptions [STL-42-3]

Instead of trying to write the container-independent code use class encapsulation [STL-01-5]
DESCRIPTION
"Given the inevitability of having to change container types from time to
time,
you can facilitate such changes in the usual manner: by encapsulating,
encapsulating, encapsulating. One of the easiest ways to do this is
through the
liberal use of typedefs for container and iterator types.(...) A typedef
is
just a synonym for some other type, so the encapsulation it affords is
purely
lexical. A typedef doesn't prevent a client from doing (or depending on)
anything they couldn't already do (or depend on). You need bigger
ammunition
if you want to limit client exposure to the container choices you've made.
You need classes. To limit the code that may require modification if you
replace one container type with another, hide the container in a class,
and
limit the amount of container-specific information visible through the
class
interface. For example, if you need to create a customer list, don't use a
list directly. Instead, create a CustomerList class, and hide a list in
its
private section"

SINCE
v7.0

BENEFITS
"When you consider this kind of change, you still have to check every
CustomerList member function and every friend to see how they'll be
affected
(in terms of performance and iterator/pointer/reference invalidation,
etc.),
but if you've done a good job of encapsulating CustomerList's
implementation
details, the impact on CustomerList clients should be small. You can't

write
container-independent code, but they might be able to."

EXAMPLE
#include <list>
using namespace std;
class Customer{};
list<Customer> customers1;
typedef list<int> CustomersContainer;
CustomersContainer customers2;

// Violation
// Violation

REPAIR
#include <list>
using namespace std;
class Customer{};
class CustomerList {
private:
typedef list<Customer> CustomerContainer;
typedef CustomerContainer::iterator CCIterator;
CustomerContainer customers;
public:
// limit the amount
// information visible
};
// in this interface

// OK

REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 1, item 2

To make copying efficient, correct, and immune to the slicing problem create containers of
pointers instead of containers of objects [STL-02-3]
DESCRIPTION
"Containers hold objects, but not the ones you give them. Furthermore,
when you
get an object from a container, the object you get is not the one that was
in
the container. Instead, when you add an object to a container (via. e.g..
insert or push_back. etc.), what goes into the container is a copy of the
object you specify. When you get an object from a container (via. e.g..
front
or back), what you set is a copy of what was contained. Copy in, copy out.
That's the STL way.
An easy way to make copying efficient, correct, and immune to the slicing
problem is to create containers of pointers or smart pointers instead of
containers of objects."

SINCE
v7.0

BENEFITS
"Copying pointers is fast, it always does exactly what you expect (it
copies
the bits making up the pointer), and nothing gets sliced when a pointer is
copied."

EXAMPLE
#include <list>
#include <map>
using namespace std;
class example {
};
void foo()

{
list<example> cont1;
map<int,example> cont2;
};

// Violation
// Violation

REPAIR
#include <list>
#include <map>
using namespace std;
class example {
};
void foo() {
list<example*> cont1;
map<int,example*> cont2;
};

// OK
// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Call empty instead of checking size() against zero [STL-03-3]


DESCRIPTION
"Call empty instead of checking size() against zero. You should prefer
the construct using empty, and the reason is simple: empty is a constanttime
operation for all standard containers, but for some list implementations,
size takes linear time."

SINCE
v7.0

BENEFITS
Rule improves efficiency of code.

EXAMPLE
#include <vector>
int foo()
{
std::vector<char> vVector;
if(vVector.size() == 0) // Violation
return 1;
if(vVector.size())
return 1;
return 0;
}

REPAIR
#include <vector>
int foo()

// Violation

{
std::vector<char> vVector;
if(vVector.empty() == 0) // OK
return 1;
if(vVector.empty())
return 1;

// OK

return 0;
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 4
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid using iterative calls to insert in an explicit loop [STL-04-3]


DESCRIPTION
"Using iterative calls to insert in an explicit loop, it would probably
look
more or less like this:
vector<int>::iterator insertLoc(v.begin());
for (int i = 0; i < numValues; ++i) {
insertLoc = v.insert(insertLoc, data[i]);
}
Notice how we have to be careful to save the return value of insert for
the next
loop iteration. If we didn't update insertLoc after each insertion, we'd
have
two problems. First, all loop iterations after the first would yield
undefined
behavior, because each insert call would invalidate insertLoc. Second,
even if
insertLoc remained valid, we'd always insert at the front of the vector
(i.e., at v.begin()), and the result would be that the ints copied into v
would
end up in reverse order. If we follow the lead of Item 43 and replace the
loop with a call to copy, we get something like this:
copy(data. data + numValues, inserter(v, v.begin()));
By the time the copy template has been instantiated, the code based on
copy and
the code using the explicit loop will be almost identical, so for purposes
of
an efficiency analysis, we'll focus on the explicit loop, keeping in mind
that
the analysis is equally valid for the code employing copy. Looking at the
explicit loop just makes it easier to understand where the efficiency hits
come
from. Yes, that's "hits." plural, because the code using the singleelement
version of insert levies up to three different performance taxes on you,
none
of which you pay if you use the range version of insert.(...)"
See also: STL-05

SINCE
v7.0

BENEFITS
Rule improves performance and protects from undefined behavior in case of
improper updating of insert location.

EXAMPLE
#include <vector>
#include <iostream>
using namespace std;
void foo()
{
vector<int> v;
const int numValues = 10;
int data[numValues]={0,1,2,3,4,5,6,7,8,9};
vector<int>::iterator insertLoc(v.begin());
for (int i = 0; i < numValues; i++)
{
insertLoc = v.insert(insertLoc, data[i]);
}
}

REPAIR
#include <vector>
#include <iostream>
using namespace std;
void foo()
{

// Violation

vector<int> v;
const int numValues = 10;
int data[numValues]={0,1,2,3,4,5,6,7,8,9};
v.insert(v.begin(),data,data+numValues);

// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Almost all uses of copy where the destination range is specified using an insert iterator
should be replaced with calls to range member functions [STL-05-3]
DESCRIPTION
"(...) almost all uses of copy where the destination range is specified
using
an insert iterator (i.e.. via inserter, back_inserter. or front_inserter)
can
be should be replaced with calls to range member functions. Too many
STL
programmers overuse copy, so the advice I just gave bears repeating:
Almost all
uses of copy where the destination range is specified using an insert
iterator
should be replaced with calls to range member functions."
See also: STL-04

SINCE
v7.0

BENEFITS
"In short, range member functions yield code that is easier to write and
easier to understand. (...) It would be helpful to have a more universally
agreed-upon criterion for establishing the superiority of range member
functions to their single-element counterparts. For the standard sequence
containers, we have one: efficiency. When dealing with the standard
sequence
containers, application of single-element member functions makes more
demands
on memory allocators, copies objects more frequently, and/or performs
redundant
operations compared to range member functions that achieve the same end."

EXAMPLE
#include <vector>
#include <algorithm>
using namespace std;

class Widget{};
void myFunction()
{
vector<Widget> v1, v2;
v1.clear();
copy(v2.begin() + v2.size() / 2, v2.end(), back_inserter(v1 )); //
Violation
}

REPAIR
#include <vector>
#include <algorithm>
using namespace std;
class Widget{};
void myFunction()
{
vector<Widget> v1, v2;
v1.clear();
v1 .insert(v1 .end(), v2.begin() + v2.size() / 2, v2.end());
}

// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Instead of anonymous istream_iterator objects use istream_iterator names when used as


function parameters [STL-06-3]
DESCRIPTION
"Be alert for C++'s most vexing parse."
Instead of anonymous istream_iterator objects use istream_iterator names
when used as function parameters. A universal rule in C++, says that
pretty much anything that can be parsed as a function declaration will be.
To prevent ambiguous code the best solution is to step back from the
trendy use of anonymous istream_iterator objects in data's declaration
and simply give those iterators names.

SINCE
v7.0

BENEFITS
Rule improves maintainability and prevents writing ambiguous code.

EXAMPLE
#include <list>
#include <iterator>
#include <fstream>
using namespace std;
void foo()
{
ifstream dataFile("ints.dat");
list<int> data2(istream_iterator<int>(dataFile),
istream_iterator<int>());
}

REPAIR
#include <list>

// Violation

#include <iterator>
#include <fstream>
using namespace std;
void foo()
{
ifstream dataFile(" ints.dat");
istream_iterator<int> dataBegin(dataFile);
istream_iterator<int> dataEnd;
list<int> data(dataBegin,dataEnd);

// OK

REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 1, item 6

When using containers of newed pointers, remember to delete the pointers before the
container is destroyed [STL-07-3]
DESCRIPTION
"All you really need to remember is that STL containers are smart, but
they're
not smart enough to know whether to delete the pointers they contain. To
avoid
resource leaks when you have containers of pointers that should be
deleted,
you must either replace the pointers with smart reference-counting pointer
objects (such as Boost's shared_ptr) or you must manually delete each
pointer
in the container before the container is destroyed."
Rule enforces replacing the pointers with smart reference-counting pointer
objects (such as Boost's shared_ptr) as it is exception-safe solution.

SINCE
v7.0

BENEFITS
Rule helps writing exception-safe code and prevents resource leaks.

EXAMPLE
#include <vector>
#include <boost/shared_ptr.hpp>
#define NUMBER 10
using namespace std;
class Widget
{
public:
Widget(){}
~Widget(){}

};
void foo()
{
vector<Widget*> vwp;
for (int i = 0; i < NUMBER; ++i)
vwp.push_back(new Widget);
}

// Violation

REPAIR
#include <vector>
#include <boost/shared_ptr.hpp>
#define NUMBER 10
using namespace std;
class Widget
{
public:
Widget(){}
~Widget(){}
};
void foo()
{
typedef boost::shared_ptr<Widget> WidgetPtr;
vector<WidgetPtr> vwp;
for (int i = 0; i < NUMBER; ++i)
vwp.push_back(WidgetPtr(new Widget));
}

// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 7
2. General Principles of Software Validation;

Final Guidance for Industry and FDA Staff


Document issued on: January 11, 2002

Never create containers of auto_ptrs [STL-08-3]


DESCRIPTION
"Never create containers of auto_ptrs. Alas, many programmers use STL
platforms that fail to reject COAPs (container of auto_ptrs). Alas even
more,
many programmers see in COAPs the chimera of a simple, straightforward,
efficient solution to the resource leaks that often accompany containers
of
pointers. As a result, many programmers are tempted to use COAPs, even
though
it's not supposed to be possible to create them."

SINCE
v7.0

BENEFITS
Rule improves efficiency, correctness and maintainability of code.

EXAMPLE
#include <vector>
#include <boost/shared_ptr.hpp>
using namespace std;
void foo( ) {
typedef auto_ptr<int> q;
vector<q> v;
}

REPAIR

// Violation

#include <vector>
#include <boost/shared_ptr.hpp>
using namespace std;

void foo( ) {
typedef boost::shared_ptr<int> w;
vector<w> v;
// OK
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 8
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid using remove algorithm with list and standard associative containers [STL-09-3]
DESCRIPTION
"Choose carefully among erasing options.
If you have a contiguous-memory container (vector, deque, or string),
the best approach is the erase-remove idiom:
c.erase( remove(c.begin(), c.end(), 1963), c.end());
This approach works for lists, too, but the list member function remove is
more
efficient:
c. remove(1963);
When c is a standard associative container (i.e.. a set. multiset, map.
or multimap), the use of anything named remove is completely wrong.
Such containers have no member function named remove, and using the remove
algorithm might overwrite container values, potentially corrupting the
container." Rule disallows usage of remove algorithm with list and
standard
associative containers.

SINCE
v7.0

BENEFITS
Rule improves efficiency of code amd prevents possibility of data
corruption.

EXAMPLE
#include <algorithm>
#include <list>
using namespace std;
bool goo( int x );

void foo( ) {
list<int> list_int;
list_int.erase( remove( list_int.begin( ),
//
Violation
list_int.end( ), 1963 ), list_int.end( ) );
list_int.erase( remove_if( list_int.begin( ),
//
Violation
list_int.end( ), goo ), list_int.end( ) );
}

REPAIR
#include <algorithm>
#include <list>
using namespace std;
bool goo( int x );
void foo( ) {
list<int> list_int;
list_int.remove( 1963 );
list_int.remove_if( goo );

// OK
// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 09
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer vector and string to dynamically allocated arrays [STL-10-3]


DESCRIPTION
"The minute you decide to use new for a dynamic allocation, you adopt
the following responsibilities:
1. You must make sure that somebody will later delete the allocation.
2. You must ensure that the correct form of delete is used. For
an allocation of a single object, "delete" must be used.
For an array allocation, "delete []" is required.
3. You must make sure that delete is used exactly once.
Any time you find yourself getting ready to dynamically allocate an array,
you should consider using a vector or a string instead.(...) vector and
string
eliminate the burdens above, because they manage their own memory. Their
memory grows as elements are added to these containers, and when a vector
or
string is destroyed, its destructor automatically destroys the elements in
the
container and deallocates the memory holding those elements."
See also: STL-11

SINCE
v7.0

BENEFITS
Rule helps writing safer and more scalable code.

EXAMPLE
#include <vector>
using namespace std;
class A{};
void foo()
{
A *p;
p = new A[10]; // Violation
}

REPAIR
#include <vector>
using namespace std;
class A{};
void foo()
{
A obj;
vector <A> vectorA; // OK
vectorA.push_back(obj);
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 2, item 13
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Consider using vector<char> instead of string [STL-11-4]


DESCRIPTION
"Consider using vector<char> instead of string. vector implementations are
not
allowed to be reference counted, so hidden multithreading performance
issues
fail to arise."
See also: STL-10

SINCE
v7.0

BENEFITS
Rule helps writing safer and more scalable code.

EXAMPLE
#include <string>
using namespace std;
void foo( ) {
string sName;
}

// Violation

REPAIR
#include <vector>
using namespace std;
void foo( ) {
vector <char> sName; // OK
}

REFERENCES

Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 2, item 13

Use reserve to avoid unnecessary reallocations [STL-12-3]


DESCRIPTION
"Use reserve to avoid unnecessary reallocations. The reserve member
function
allows you to minimize the number of reallocations that must be performed,
thus avoiding the costs of real location and 50 iterator/pointer/reference
invalidation."

SINCE
v7.0

BENEFITS
Rule improves efficiency, correctness and maintainability of code.

EXAMPLE
#include <vector>
using namespace std;
void foo()
{
vector<int> v;
for (int i = 1; i <= 1000; ++i) v.push_back(i); // Violation
}

REPAIR
#include <vector>
using namespace std;
void foo()
{
vector<int> v;
v.reserve(1000);

for (int i = 1; i <= 1000; ++i) v.push_back(i); // OK


}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 2, item 14
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Each vector and string should be checked if it is not empty before it is passed to C function
[STL-13-3]
DESCRIPTION
"(...) Still, obstacles remain, and one of the most common is the
existence of
legacy C APIs that traffic in arrays and char* pointers instead of vector
and
string objects. Such APIs will exist for a long time, so we must make
peace
with them if we are to use the STL effectively. Fortunately, it's easy. If
you have a vector v and you need to get a pointer to the data in v that
can be
viewed as an array, just use &v[0]. The only sticking point is if v is
empty.
If it is, v.size() is zero, and &v[0] attempts to produce a pointer to
something that does not exist."
Rule enforces checking if vector/string is not empty before it is passed
to C
function.

SINCE
v7.0

BENEFITS
Rule prevents undefined results.

EXAMPLE
// file.c
#include <stddef.h>
void doSomething( const int* pInts, size_t numlnts ) {
/*...*/
}
// file.cpp
#include "file.c"
#include <vector>

using namespace std;


void foo( ) {
vector<int> v;
doSomething( &v[ 0 ], v.size( ) ); // Violation
}

REPAIR
// file.c
#include <stddef.h>
void doSomething( const int* pInts, size_t numlnts ) {
/*...*/
}
// file.cpp
#include "file.c"
#include <vector>
using namespace std;
void foo( ) {
vector<int> v;
if (!v.empty( )) {
doSomething( &v[ 0 ], v.size( ) ); // OK
}
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 2, item 16
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid using vector<bool> [STL-14-3]


DESCRIPTION
"Avoid using vector<bool>. As an STL container, there are really only
two things wrong with vector<bool>. First, it's not an STL container.
Second, it doesn't hold bools."

SINCE
v7.0

BENEFITS
Rule helps writing safer and more scalable code.

EXAMPLE
#include <vector>
using namespace std;
void foo(vector<bool> bParam)
// Violation
{
vector<bool> sName;
// Violation
vector<bool> *psName;
// Violation
}
vector<bool> vec_fun();

// Violation

REPAIR
#include <vector>
using namespace std;
void foo(vector<int> bParam)
{
vector<int> sName;
// OK
vector<int> *psName;
// OK
}

// OK

vector<int> vec_fun();

// OK

REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 2, item 18

Specify comparison types for associative containers of pointers [STL-15-3]


DESCRIPTION
"Specify comparison types for associative containers of pointers. (...)
anytime
you create a standard associative container of pointers, you must bear in
mind
that the container will be sorted by the values of the pointers. Only
rarely
will this be what you want, so you'll almost always want to create your
own
functor class to serve as a comparison type."

SINCE
v7.0

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
#include <set>
#include <string>
#include <iostream>
using namespace std;
void myFunction()
{
set<string*> ssp;
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));

// Violation

set<string*>::const_iterator i;
for (i = ssp.begin(); i != ssp.end();++i)
cout << *i << endl;

REPAIR
#include <set>
#include <string>
#include <iostream>
using namespace std;
struct StringPtrLess:
public binary_function<const string*, const string*,bool>
{
bool operator()(const string *ps1, const string *ps2) const
{
return *ps1 < *ps2;
}
};
void myFunction2()
{
set<string*, StringPtrLess> ssp;
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));

// OK

set<string*, StringPtrLess>::const_iterator i;
for (i = ssp.begin(); i != ssp.end();++i)
cout << **i << endl;
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 3, item 20
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

For associative containers never use comparison function returning true for equal values
[STL-16-3]
DESCRIPTION
"Create a set where less_equal is the comparison type, then insert 10 into
the
set:
set<int, less_equal<int> > s;
s.insert(10);
s.insert(10); // Now try inserting 10 again:
For this call to insert, the set has to figure out whether 10 is already
present. To make it easier to understand what happens when the set does
this,
we'll call the 10 that was initially inserted 10A and the 10 that we're
trying
to insert 10B. The set runs through its internal data structures looking
for
the place to insert 10B. It ultimately has to check 10B to see if it's the
same
as 10A. The definition of "the same" for associative containers is
equivalence,
so the set tests to see whether 10B is equivalent to 10A. When performing
this
test, it naturally uses the set's comparison function. In this example,
that's
operator<=, because we specified less_equal as the set's comparison
function,
and less_equal means operators. The set thus checks to see whether this
expression is true:
!(10A<= 10B)&&!(10B<= 10A) // test 10A and 10B for equivalence
Well, 10A and 10B are both 10, so it's clearly true that 10A <= 10B.
Equally
clearly, 10B <= 10A. The above expression thus simplifies to
!(true)&&!(true)
and that simplifies to false && false which is simply false. That is, the
set
concludes that 10A and 10B are not equivalent, hence not the same, and it
thus
goes about inserting 10B into the container alongside 10A. Technically,
this

action yields undefined behavior, but the nearly universal outcome is that
the
set ends up with two copies of the value 10, and that means it's not a set
any
longer."
See also: STL-17

SINCE
v7.0

BENEFITS
"By using less_equal as our comparison type, we've corrupted the
container!
Furthermore, any comparison function where equal values return true will
do
the same thing. Equal values are, by definition, not equivalent!"

EXAMPLE
#include <set>
#include <functional>
using namespace std;
void myFunction()
{
set< int, less_equal<int> > setInt;
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);
}

REPAIR
#include <set>
#include <functional>
using namespace std;
void myFunction()

// Violation

{
set< int, less<int> > setInt;
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);

// OK

REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 3, item 21

For associative containers never use comparison function returning true for equal values
[STL-17-3]
DESCRIPTION
"(...) suppose you're in need of a comparison function for a container of
string* pointers that sorts in descending order. The natural thing to do
is to
grab the existing code and modify it. If you're not careful, you might
come up
with this (...):
struct StringPtrGreater:
// this code is
flawed!
public binary_function<const string*, const string*, bool>
{
bool operator()(const string *ps1, const string *ps2) const
{
return !(*ps1 <*ps2); //just negate the old test;
}
// this is incorrect!
};
The idea here is to reverse the sort order by negating the test inside the
comparison function. Unfortunately, negating "<" doesn't give you ">"
(which
is what you want), it gives you ">=". And you now understand that ">=",
because
it will return true for equal values, is an invalid comparison function
for
associative containers. To avoid falling into this trap, all you need to
remember is that the return value of a comparison function indicates
whether
one value precedes another in the sort order defined by that function.
Equal
values never precede one another, so comparison functions should always
return
false for equal values."
See also: STL-16

SINCE
v7.0

BENEFITS
"Unless your comparison functions always return false for equal values,
you
break all standard associative containers, regardless of whether they are
allowed to store duplicates."
EXAMPLE
#include <set>
using namespace std;
struct IntGreater:
public binary_function<const int,const int, bool> {
bool operator()(const int ps1, const int ps2) const
{
return !(ps1 < ps2);
}
};
void myFunction()
{
set< int, IntGreater> setInt; // Violation
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);
}

REPAIR
#include <set>
using namespace std;
struct IntGreater:
public binary_function<const int,const int, bool> {
bool operator()(const int ps1, const int ps2) const
{
return (ps1 > ps2);
}
};
void myFunction()

{
set< int, IntGreater> setInt; // OK
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 3, item 21
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer iterator to const iterator, reverse_iterator, and const_reverse_iterator [STL-18-3]


DESCRIPTION
"Prefer iterator to const iterator, reverse_iterator, and
const_reverse_iterator. Why it often makes sense to prefer iterators to
const
and reverse iterators:
- Some versions of insert and erase require iterators. If you want to call
those functions, you're going to have to produce iterators, const and
reverse
iterators won't do.
- It's not possible to implicitly convert a const iterator to an iterator
- Conversion from a reverse_iterator to an iterator may require iterator
adjustment after the conversion.
All these things conspire to make working with containers easiest, most
efficient, and least likely to harbor subtle bugs if you prefer iterators
to
their const and reverse colleagues.
From the perspective of const correctness (a worthy perspective, to be
sure),
staying away from const_iterators simply to avoid potential implementation
shortcomings (all of which have workarounds) seems unjustified, but in
conjunction with the anointed status of iterators in some container member
functions, it's hard to avoid the practical conclusion that
const_iterators
arc not only less useful than iterators, sometimes they're just not worth
the
trouble."

SINCE
v7.0

EXCEPTIONS
Const containers.

BENEFITS
Rule improves efficiency and portability of code.

EXAMPLE
#include <vector>
using namespace std;
void sampleFunction(const std::vector<int> &o)
{
vector<int> v;
typedef vector<int>::const_iterator ConstIter;
typedef vector<int>::iterator Iter;
ConstIter c_it;
c_it= v.begin();
c_it = o.begin();

// Violation

REPAIR
#include <vector>
using namespace std;
void sampleFunction(const std::vector<int> &o)
{
vector<int> v;
typedef vector<int>::const_iterator ConstIter;
typedef vector<int>::iterator Iter;
ConstIter c_it;
Iter it = v.begin();
c_it = o.begin();
}

// OK
// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 4, item 26
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Use distance and advance to convert a container's const_iterators to iterators [STL-19-3]


DESCRIPTION
"Casting const iterators to iterators is ill-advised even for vector
and string, because its portability is doubtful. Use distance() and
advance() to convert a container's const_iterators to iterators."

SINCE
v7.0

BENEFITS
Rule improves portability of code.

EXAMPLE
// Compiles with vc++ 6.0
#include <algorithm>
#include <vector>
using namespace std;
void foo( ) {
typedef vector<int> IntVector;
typedef vector<int>::iterator Iter;
typedef vector<int>::const_iterator ConstIter;
ConstIter citer;
Iter iter = const_cast<Iter>( citer );
}

REPAIR
#include <algorithm>
#include <vector>

// Violation

using namespace std;


void goo( ) {
typedef vector<int> IntVector;
typedef vector<int>::iterator Iter;
typedef vector<int>::const_iterator ConstIter;
IntVector v;
ConstIter citer;
Iter iter( v.begin( ) );
advance( iter, distance<ConstIter>( iter, citer ) ); // OK
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 4, item 27
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

It is necessary to be careful when using reverse_iterator's base iterator for erasure purposes
[STL-20-4]
DESCRIPTION
"Understand how to use a reverse_iterator's base iterator.
(...) it's not accurate to say that a reverse_iterator's base member
function returns the "corresponding" iterator. For insertion purposes, it
does, but for erasure purposes, it does not. When converting
reverse_iterators
to iterators, it's important that you know what you plan to do with the
resulting iterator, because only then can you determine whether the
iterator
you have is the one you need.
To emulate erasure at a position specified by a reverse_iterator ri, erase
at
the position preceding ri.base() instead. For purposes of erasure, ri
and ri.base() are nor equivalent, and ri.base() is nor the iterator
corresponding to ri."
Rule reports warning message when the usage of base iterator within
erase call is found and no increment/decrement operators are performed for
base
iterator.

SINCE
v7.0

BENEFITS
Rule prevents undefined results.

EXAMPLE
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
void foo()

{
vector<int> v;
list<int> li;
vector<int>::reverse_iterator ri = find(v.rbegin(), v.rend(), 3);
list<int>::reverse_iterator ri2 = find(li.rbegin(), li.rend(), 3);
v.reserve(5);
for(int i = 1;i <= 5;++i){
v.push_back(i);
li.push_back(i);
}
v.erase(ri.base());
li.erase(ri2.base());
}

// Violation
// Violation

REPAIR
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
void foo()
{
vector<int> v;
list<int> li;
vector<int>::reverse_iterator ri = find(v.rbegin(), v.rend(), 3);
list<int>::reverse_iterator ri2 = find(li.rbegin(), li.rend(), 3);
v.reserve(5);
for(int i = 1;i <= 5;++i){
v.push_back(i);
li.push_back(i);
}
v.erase((--ri).base()); // OK
li.erase(--ri2.base()); // OK
}

REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 4, item 28

Consider istreambuf_iterators for character-by-character input [STL-21-4]


DESCRIPTION
"If you need to read the characters in a stream one by one, you don't need
the
power of formatted input, and you care about how long it takes to read the
stream, typing three extra characters per iterator is a small price to pay
for
what is often a significant increase in performance. For unformatted
character
by - character input, you should always consider istreambuf_iterators."

SINCE
v7.0

BENEFITS
Rule improves performance and efficiency of code.

EXAMPLE
#include <list>
#include <fstream>
#include <iterator>
using namespace std;
void myFunction()
{
ifstream dataFile("some_file.dat");
istream_iterator<char> dataBegin(dataFile); // Violation
istream_iterator<char> dataEnd;
// Violation
list<char> data(dataBegin, dataEnd);
}

REPAIR

#include <list>
#include <fstream>
#include <iterator>
using namespace std;
void myFunction()
{
ifstream dataFile("some_file.dat");
istreambuf_iterator<char> dataBegin(dataFile); // OK
istreambuf_iterator<char> dataEnd;
// OK
list<char> data(dataBegin, dataEnd);
}

REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 4, item 29

Make sure destination ranges are big enough [STL-22-3]


DESCRIPTION
"The problems arise when programmers think about inserting objects into
containers, but don't tell the STL what they're thinking. Here's a common
way
this can manifest itself:
vector<int> values;
vector<int> results;
transform( values.begin(), values.end(), results.end(), transmogrify);
In this example, transform is told that the beginning of its destination
range
is results.end(), so that's where it starts writing the results of
invoking
transmogrify on every element of values. Like every algorithm that uses a
destination range, transform writes its results by making assignments to
the
elements in the destination range, transform will thus apply transmogrify
to
values[0] and assign the result to *results.end(). It will then apply
transmogrify to values[1] and assign the result to *(results.end()+1). The
call
to transform is wrong, because it's asking for assignments to be made to
objects that don't exist. (...) the way to say "please put transform's
results
at the end of the container called results" is to call back_inserter to
generate the iterator specifying the beginning of the destination range."

SINCE
v7.0

BENEFITS
"This can lead only to disaster, because there is no object at
*results.end(),
much less at *(results.end()+1)! The call to transform is wrong, because
it's
asking for assignments to be made to objects that don't exist."

EXAMPLE
#include <vector>
#include <algorithm>
using namespace std;
int transmogrify(int x);
void myFunction()
{
vector<int> values;
vector<int> results;
// put values to vector
transform(values.begin(), values.end(),
results.end(), transmogrify);
}

// Violation

REPAIR
#include <vector>
#include <algorithm>
using namespace std;
int transmogrify(int x);
void myFunction()
{
vector<int> values;
vector<int> results;
// put values to vector
transform(values.begin(), values.end(),
back_inserter(results), transmogrify);
}

// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 30

2. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Follow remove-like algorithms by erase if you really want to remove something [STL-23-3]
DESCRIPTION
"Follow remove-like algorithms by erase if you really want to remove
something.
The only way to eliminate an element from a container is to invoke a
member
function on that container, and because remove cannot know the container
holding the elements on which it is operating, it is not possible for
remove to
eliminate elements from a container."

EXCEPTIONS
"In fact, remove and erase are so closely allied, the two are merged in
the
list member function remove. This is the only function in the STL named
remove
that eliminates elements from a container"

BENEFITS
Rule improves efficiency and prevents memory leaks.

EXAMPLE
#include <vector>
#include <algorithm>
using namespace std;
void foo( ) {
vector<int> coll;
for ( int i=0; i < 10; i++ ) {
coll.push_back( i + 65 );
}
vector<int>::iterator pos;
pos = remove( coll.begin( ), coll.end( ), 5 ); // Violation no erase
call
}

REPAIR
#include <vector>
#include <algorithm>
using namespace std;
void foo( ) {
vector<int> coll;
for ( int i=0; i < 10; i++ ) {
coll.push_back( i + 65 );
}
vector<int>::iterator pos;
pos = remove( coll.begin( ), coll.end( ), 5 );

// OK

coll.erase( pos, coll.end( ) );


}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 32
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Containers", Rule 82
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Avoid using remove and similar algorithms (i.e., remove_if and unique) on containers of
dynamically allocated pointers [STL-24-3]
DESCRIPTION
"Be wary of remove-like algorithms on containers of pointers. This makes
the
resource leak especially obvious, and it should now be clear why you
should
try to avoid using remove and similar algorithms (i.e., remove_if and
unique)
on containers of dynamically allocated pointers. In many cases, you'll
find
that the partition algorithm is a reasonable alternative. If you can't
avoid
using remove on such containers, one way to eliminate this problem
is to delete the pointers and set them to null prior to applying the
eraseremove idiom, then eliminate all the null pointers in the container. If
you're
willing to replace the container of pointers with a container of smart
pointers
that perform reference counting, the remove-related difficulties wash
away, and
you can use the erase-remove idiom directly."

SINCE
v7.0

BENEFITS
"Be wary of remove-like algorithms on containers of pointers. Failure to
heed
this advice is just asking for resource leaks."

EXAMPLE
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;


class Widget{
public:
bool isCertified();
};
void myFunction()
{
vector<Widget*> v;
v.push_back(new Widget);
v.erase( remove_if(v.begin(), v.end(),
//
Violation
not1(mem_fun(&Widget::isCertified))),v.end());
}

REPAIR
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class Widget{
public:
bool isCertified();
};
void delAndNullifyUncertified(Widget*& pWidget)
{
if (!pWidget->isCertified()) { // delete the pointer
delete pWidget;
// and set it to null pWidget
pWidget = 0;
}
}
void myFunction()
{
vector<Widget*> v;
v.push_back(new Widget);
for_each(v.begin(), v.end(), delAndNullifyUncertified);

v.erase( remove(v.begin(), v.end(), static_cast<Widget*>(0)), v.end());


// OK
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 33
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

If you pass a sorted range to an algorithm that also takes a comparison function, be sure that
the comparison function you pass behaves the same as the one you used to sort the range
[STL-25-4]
DESCRIPTION
"(...) the most common is that some algorithms require ranges of sorted
values.
It's important that you adhere to this requirement whenever it applies,
because violating it leads not to compiler diagnostics, but to undefined
runtime behavior. (...) list of the algorithms that require the data on
which
they operate to be sorted:
binary_search, lower_bound, upper_bound, equal_range, set_union,
set_intersection, set_difference, set_symmetric_difference,
merge inplace_merge, includes
With so many different ways to sort things, it's critical that you give
the STL
consistent sorting related information to work with. If you pass a sorted
range
to an algorithm that also takes a comparison function, be sure that the
comparison function you pass behaves the same as the one you used to sort
the
range."

SINCE
v7.0

BENEFITS
"The eleven algorithms that require sorted ranges do so in order to offer
greater efficiency than would otherwise be possible. As long as you
remember
to pass them only sorted ranges, and as long as you make sure that the
comparison function used by the algorithms is consistent with the one used
to
do the sorting, you'll revel in trouble-free search, set, and merge
operations,
plus you'll find that unique and unique_copy eliminate all duplicate
values,

as you almost certainly want them to."

EXAMPLE
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
void myFunction()
{
vector<int> v;
sort(v.begin(), v.end(), greater<int>());
bool a3exists = binary_search(v.begin(),v.end(),3);
Violation
}

//

REPAIR
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
void myFunction()
{
vector<int> v;
sort(v.begin(), v.end(), greater<int>());
bool a3exists = binary_search(v.begin(),v.end(),3, greater<int>()); //
OK
}

REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 5, item 34

Proper implementation of copy_if should not be based on returning the remove_copy_if with a
not1 in front of the predicate [STL-26-3]
DESCRIPTION
"One of the more interesting aspects of the STL is that although there are
11
algorithms with "copy" in their names, none of them is copy_if. To
implement
copy_if, then, it seems that all we need to do is throw a not1 in front of
the
predicate we'd like to pass to copy_if, then pass the resulting predicate
to
remove_copy_if. The result is the code below.
// a not-quite-right implementation of copy_if
template< typename Inputlterator, typename Outputlterator, typename
Predicate>
Outputlterator copy_if( InputIterator begin, Inputlterator end,
Outputlterator destBegin, Predicate p)
{
return remove_copy_if(begin, end, destBegin, not1(p));
}
If the above reasoning were valid, we could write out our defective
Widgets
this way:
// well-intentioned code that will not compile
copy_if( widgets.begin(), widgets.end(), ostream_iterator<Widget>(cerr,
"\n"),
isDefective);
Your STL platforms will take a jaundiced view of this code, because it
tries to
apply not1 to isDefective. not1 can't be applied directly to a function
pointer: the function pointer must first be passed through ptr_fun. To
call this
implementation of copy_if, you must pass not just a function object, but
an
adaptable function object. That's easy enough to do, but clients of a
would-be
STL algorithm shouldn't have to. Standard STL algorithms never require
that

their functors be adaptable, and neither should copy_if."


Rule reports a violation if implementation of copy_if is based on
returning the
remove_copy_if with a not1 in front of the predicate.

SINCE
v7.0

BENEFITS
"Given how useful copy_if is, plus the fact that new STL programmers tend
to
expect it to exist anyway, there's a good case to be made for putting
copy_if
the correct one!"

EXAMPLE
#include
#include
#include
#include
#include

<vector>
<algorithm>
<iostream>
<iterator>
<functional>

using namespace std;


template <typename Inputlterator,typename Outputlterator, typename
Predicate>
Outputlterator copy_if( Inputlterator begin, Inputlterator end,
Outputlterator destBegin, Predicate p ) {
return remove_copy_if( begin, end, destBegin,
// Violation
not1( ptr_fun( p ) ) );
}
template <class T> bool is_not_3( T val ) {
return val != 3;
}
void foo( ) {
vector<int> v;

v.push_back( 1 );
v.push_back( 2 );
v.push_back( 3 );
copy_if( v.begin( ), v.end( ), ostream_iterator<int>( cout, " " ),
is_not_3<int> );
}

REPAIR
#include
#include
#include
#include

<vector>
<algorithm>
<iostream>
<iterator>

using namespace std;


template <typename Inputlterator, typename Outputlterator, typename
Predicate>
Outputlterator copy_if( Inputlterator begin, Inputlterator end,
Outputlterator destBegin, Predicate p ) {
while (begin != end) {
// OK
if (p(*begin))
*destBegin++ = *begin;
++begin;
}
return destBegin;
}
template <class T> bool is_not_3( T val ) {
return val != 3;
}
void foo( ) {
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
v.push_back( 3 );
copy_if( v.begin( ), v.end( ), ostream_iterator<int>( cout, " " ),
is_not_3<int> );
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, Item 36
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

If accumulate() is used on a container of floating point values, use floating point value as
initial one [STL-27-3]
DESCRIPTION
If accumulate is performed for i.e. list of doubles and the initial value
would be the int 0, the accumulate would internally use an int to store
the
value it was computing. "That int would ultimately become accumulate's
return
value, and it would be used to initialize the variable sum. The code would
compile and run, but sum's value would be incorrect. Instead of holding
the
true sum of a list of doubles, it would hold the result of adding all the
doubles together, but converting the result to an int after each
addition."

SINCE
v7.0

BENEFITS
Rule prevents loss of data.

EXAMPLE
#include <list>
#include <numeric>
using namespace std;
void foo()
{
list<double> li;
double sum = accumulate(li.begin(), li.end(), 0);
}

REPAIR
#include <list>

// Violation

#include <numeric>
using namespace std;
void foo()
{
list<double> li;
double sum = accumulate(li.begin(), li.end(), 0.0);
}

// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 37
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Design functor classes for pass-by-value [STL-28-3]


DESCRIPTION
"Because function objects are passed and returned by value, the onus is on
you
to make sure that your function objects behave well when passed that way
(i.e., copied). This implies two things. First, your function objects need
to
be small. Otherwise they will be too expensive to copy. Second, your
function
objects must be monomorphic (i.e., not polymorphic) they must not use
virtual functions. That's because derived class objects passed by value
into
parameters of base class type suffer from the slicing problem: during the
copy,
their derived parts are removed. The prohibition on polymorphic functors
is
equally unrealistic. Surely there's a way to let function objects be big
and/or polymorphic, yet still allow them to mesh with the pass-functorsbyvalue convention that pervades the STL. There is. Take the data and/or the
polymorphism you'd like to put in your functor class, and move it into a
different class. Then give your functor class a pointer to this new
class."

SINCE
v7.0

NOTES
By small class functor rule means the one with the number of non-static
members not exceeding 5.

BENEFITS
Rule prevents the slicing problem and expensive copying.

EXAMPLE
// compiles with msvc 6.0, 7.1
#include <functional>
using namespace std;
class Widget;
template<typename T>
class BPFC: public unary_function<T, void>
{
private:
Widget w;
int x;
int y;
void someFunction();
bool checkWidget(Widget &);

// Violation

public:
virtual void operator()(const T& val) const; // Violation
};

REPAIR
#include <functional>
using namespace std;
class Widget;
template <typename T> class BPFC{};
template<typename T>
class BPFCImpl
{
private:
Widget w;
int x;
virtual ~BPFCImpl();
virtual void operator()(const T& val) const;
friend class BPFC<T>;
};

template<typename T>
class BPFC2: public unary_function<T, void>
{
private:
BPFCImpl<T> *pImpl;
public:
void operator()(const T& val) const
{
pImpl->operator() (val );
}
};

// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 38
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Make predicates const pure functions [STL-29-3]


DESCRIPTION
"A predicate is a function that returns bool (or something that can be
implicitly converted to bool). A pure function is a function whose return
value depends only on its parameters. If f is a pure function and x and y
are
objects, the return value of f(x, y) can change only if the value of x or
y
changes. Declaring operator() const in predicate classes is necessary for
correct behavior, but it's not sufficient. A well-behaved operator() is
certainly const, but it's more than that. It's also a pure function."

BENEFITS
Rule prevents disabling the compiler from detecting an error if you try to
change any data members that the predicate type may have.

EXAMPLE
#include <functional>
#include <algorithm>
#include <list>
using namespace std;
int global;
class Widget{};
class MeetsThreshold: public std::unary_function<Widget, bool> {
public:
bool operator( ) ( const Widget& ) {
// Violation
return ++global == 0;
}
private:
size_t current, n_;
};

REPAIR

#include <functional>
#include <algorithm>
#include <list>
using namespace std;
class SampleVol: public std::unary_function<int, bool> {
bool operator( ) ( const int& b ) const {
// OK
int a = 0;
return a == b;
}
public:
size_t current, n_;
};

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 39
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Algorithms", Rule 87
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Each functor class should has only one operator() function, and it's parameter and return
types should be passed to unary_function or binary_function [STL-30-3]
DESCRIPTION
"(...) unary_function and binary_function are templates, so you can't
inherit
from them directly. Instead, you must inherit from structs they generate,
and
that requires that you specify some type arguments. For unary_function,
you
must specify the type of parameter taken by your functor class's
operator(),
as well as its return type. For binary_function, you specify three types:
the
types of your operator's first and second parameters, and your operator's
return type. Let's not forget the fundamental reason for all this
unary_function and binary_function base class gobbledegook. These classes
supply typedefs that are required by function object adapters, so
inheritance
from those classes yields adaptable function objects."
STL function objects are modeled on C++ functions, and a C++ function has
only
one set of parameter types and one return type. As a result, the STL
implicitly assumes that each functor class has only one operator()
function,
and it's the parameter and return types for this function that should be
passed
to unary_function or binary_function. This means that, tempting though it
might
be, you shouldn't try to combine the functionality of WidgetNameCompare
and
PtrWidgetNameCompare by creating a single struct with two operator()
functions.
If you did, the functor would be adaptable with respect to at most one of
its
calling forms, and a functor that's adaptable only half the time might
just as
well not be adaptable at all."

SINCE

v7.0

BENEFITS
"Adaptability is important, and you should strive to facilitate it each
time
you write a functor class."

EXAMPLE
#include <functional>
using namespace std;
class Widget{};
template<typename T>
class MeetsThreshold2: public std::unary_function<Widget, int>
Violation
{
private:
const T threshold;
public:
MeetsThreshold2(const T& threshold);
bool operator()(const Widget&) const;
};

//

struct WidgetNameCompare:std::binary_function<Widget, Widget, int>


Violation
{
bool operator()(const Widget& lhs, const Widget& rhs) const;
bool operator()(const Widget& lhs) const;
};

REPAIR
#include <functional>
using namespace std;
class Widget{};

//

template<typename T>
class MeetsThreshold: public std::unary_function<Widget, bool>
{
private:
const T threshold;
public:
MeetsThreshold(const T& threshold);
bool operator()(const Widget&) const;
};

struct WidgetNameCompare:
OK
std::binary_function<Widget, Widget, bool>{
bool operator()(const Widget& lhs, const Widget& rhs) const;
};

// OK

//

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 40
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

You must employ ptr_fun, mem_fun, or mem_fun_ref whenever you pass a function to an STL
component [STL-31-3]
DESCRIPTION
"If you get confused about when to use ptr_fun and when not to, consider
using
it every time you pass a function to an STL component. You must employ
them
(mem_fun and mem_fun_ref) whenever you pass a member function to an STL
component, because, in addition to adding typedefs (which may or may not
be
necessary), they adapt the calling syntaxes from the ones normally used
with
member functions to the one used even-where in the STL. If you don't use
them
when passing member function pointers, your code will never compile."

SINCE
v7.0

BENEFITS
"The objects produced by mem_fun and mem_fun_ref do more than allow STL
components to assume that all functions are called using a single syntax.
They
also provide important typedefs, just like the objects produced by
ptr_fun."

EXAMPLE
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
class Widget {
};
int test(Widget& x) { return 0; };

void myFunction()
{
vector<Widget> WidgetVector;
for_each(WidgetVector.begin(),WidgetVector.end(), test);
Violation
};

//

REPAIR
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
class Widget {
};
int test(Widget& x) { return 0; };
void myFunction()
{
vector<Widget> WidgetVector;
for_each(WidgetVector.begin(), WidgetVector.end(), ptr_fun(test));
OK
};

//

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 41
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Make sure less<T> means operator< [STL-32-3]


DESCRIPTION
"C++ programmers can be forgiven certain assumptions. (...) they assume
that
using less is tantamount to using operator<. operator< is more than just
the
default way to implement less, it's what programmers expect less to do.
Having
less do something other than call operator< is a gratuitous violation of
programmers' expectations. You shouldn't do it. If you use less
(explicitly
or implicitly), make sure it means operator<. If you want to sort objects
using
some other criterion, create a special functor class that's not called
less."

SINCE
v7.0

BENEFITS
"Having less do something other than call operator< is a gratuitous
violation
of programmers' expectations. It runs contrary to what has been called
"the
principle of least astonishment." It's callous. It's mean. It's bad.(...)
Don't mislead all those programmers by playing games with the definition
of
less."

EXAMPLE
#include <functional>
using namespace std;
class Widget {
public:

size_t weight() const;


size_t maxSpeed() const;
};
bool operator<(const Widget& lhs, const Widget& rhs)
{
return lhs.weight() < rhs.weight();
}
template<>
struct std::less<Widget>:
// Violation
public
std::binary_function< Widget, Widget, bool>
{
bool operator()(const Widget& lhs, const Widget& rhs) const
{
return lhs.maxSpeed() < rhs.maxSpeed();
}
};

REPAIR
#include <functional>
using namespace std;
class Widget {
public:
size_t weight() const;
size_t maxSpeed() const;
};
bool operator<(const Widget& lhs, const Widget& rhs)
{
return lhs.weight() < rhs.weight();
}
struct maxSpeedCompare:
// OK
public binary_function<Widget, Widget, bool> {
bool operator()(const Widget& lhs, const Widget& rhs) const
{
return lhs.maxSpeed() < rhs.maxSpeed();
}

};

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 42
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer algorithm calls to hand-written loops [STL-33-3]


DESCRIPTION
"Prefer algorithm calls to hand-written loops.
For many C++ programmers, writing the loop is more natural than
calling the algorithm, and reading the loop is more comfortable (...).
Yet this Item argues that the algorithm call is preferable.
In fact, this Item argues that calling an algorithm is usually
preferable to any hand-written loop. Why?
There are three reasons:
- Efficiency: Algorithms are
programmers produce.
- Correctness: Writing loops
algorithms.
- Maintainability: Algorithm
and more straightforward than

often more efficient than the loops


is more subject to errors than is calling
calls often yield code that is clearer
the corresponding explicit loops."

SINCE
v7.0

BENEFITS
Rule improves efficiency, correctness and maintainability of code.

EXAMPLE
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void foo()
{
const int VECTOR_SIZE = 8 ;
vector<int> Numbers(VECTOR_SIZE) ;
vector<int>::iterator start, end, it ;
start = Numbers.begin() ;

end = Numbers.end() ;
for(it = start; it != end; it++)
cout << *it;

// Violation

REPAIR
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(int n)
{
cout << n;
}
void foo()
{
const int VECTOR_SIZE = 8 ;
vector<int> Numbers(VECTOR_SIZE) ;
vector<int>::iterator start, end, it ;
start = Numbers.begin() ;
end = Numbers.end() ;
for_each(start, end, print) ;

// OK

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 7, item 43
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Prefer member functions to algorithms with the same names [STL-34-3]


DESCRIPTION
"Some containers have member functions with the same names as STL
algorithms.
The associative containers offer count, find, lower_bound. upper_bound,
and
equal_range, while list offers remove, remove_if, unique, sort, merge, and
reverse. Most of the time, you'll want to use the member functions instead
of
the algorithms. There are two reasons for this. First, the member
functions are
faster. Second, they integrate better with the containers (especially the
associative containers) than do the algorithms. That's because algorithms
and
member functions that share the same name typically do not do exactly the
same
thing.(...)"

SINCE
v7.0

BENEFITS
Rule improves efficiency and stability.

EXAMPLE
#include <list>
#include <set>
#include <algorithm>
using namespace std;
void myFunction( ) {
set<int> s;
list<int> l;
list<int>::iterator begin = l.begin();
list<int>::iterator end = l.end();
set<int>::iterator i = find(s.begin(), s.end(), 727);

// Violation

reverse(begin,end);
reverse(l.begin(),l.end());

// Violation
// Violation

REPAIR
#include <list>
#include <set>
#include <algorithm>
using namespace std;
void myFunction( ) {
set<int> s;
list<int> l;
set<int>::iterator i = s.find(727); // OK
l.reverse();
// OK
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 7, item 44
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not rely on the conversion of count()'s nonzero values to true and zero to false [STL-35-3]
DESCRIPTION
"Using count as an existence test, count returns either zero or a positive
number, so we rely on the conversion of nonzero values to true and zero to
false. It would arguably be clearer to be more explicit about what we
are doing."

SINCE
v7.0

BENEFITS
Rule improves readability and maintainability of code.

EXAMPLE
#include <list>
#include <algorithm>
using namespace std;
void foo()
{
list<int> lw;
int w;
if(count(lw.begin(), lw.end(), w))
{
/*...*/
}
}

REPAIR
#include <list>
#include <algorithm>

// Violation

using namespace std;


void foo()
{
list<int> lw;
int w;
if(count(lw.begin(), lw.end(), w) == 0) // OK
{
/*...*/
}
}

REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 7, item 45
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not use an iterator range that isn't really a range [STL-36-3]


DESCRIPTION
Do not use an iterator range that isn't really a range.
There are two common ways to use an iterator range that isn't really a
range:
"The first way arises when two iterators that delimit the range point into
the same container, but the first iterator doesn't actually precede the
second.
The second common case arises when the iterators point into different
containers."

BENEFITS
Rule improves efficiency and prevents memory leaks.

EXAMPLE
#include <algorithm>
#include <vector>
using namespace std;
void setElem( int elem ) {
elem = 1;
}
void foo( ) {
vector<int> coll;
vector<int> moll;
for_each( coll.begin( ), moll.end( ), setElem );
for_each( moll.begin( ), coll.end( ), setElem );
for_each( coll.end( ), coll.begin( ), setElem );
}

REPAIR
#include <algorithm>
#include <vector>

// Violation
// Violation
// Violation

using namespace std;


void setElem( int elem ) {
elem = 1;
}
void foo( ) {
vector<int> coll;
for_each( coll.begin( ), coll.end( ), setElem );
}

// OK

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Algorithms", Rule 83
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Use vector and string instead of arrays [STL-37-3]


DESCRIPTION
"Avoid implementing array abstractions with C-style arrays, pointer
arithmetic,
and memory management primitives." Using vector or string helps you write
safer
and more scalable software.

BENEFITS
Rule helps writing safer and more scalable code.

EXAMPLE
class A{};
void foo( ) {
A arrayA[10]; // Violation
}

REPAIR
#include <vector>
using namespace std;
class A{};
void foo( ) {
A obj;
vector <A> vectorA; // OK
vectorA.push_back(obj);
}

REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Containers", Rule 77

Use != instead of < to compare iterators [STL-38-3]


DESCRIPTION
"Use the most generic and abstract means to implement a piece of
functionality: Use != instead of < to compare iterators.
Using != is more general and so applies to a larger class of objects;
using < asks for ordering."

BENEFITS
Rule improves efficiency and prevents memory leaks.

EXAMPLE
#include <vector>
using namespace std;
void foo( ) {
vector<int> coll;
vector<int> moll;
vector<int>::iterator c_pos = coll.begin( );
vector<int>::iterator m_pos = moll.begin( );
if (c_pos < m_pos) {}
// Violation
}

REPAIR
#include <vector>
using namespace std;
void foo( ) {
vector<int> coll;
vector<int> moll;
vector<int>::iterator c_pos = coll.begin( );
vector<int>::iterator m_pos = moll.begin( );
if (c_pos != m_pos) {}
// OK
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Templates and Genericity", Rule 67
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Use traits classes in conjunction with overloading [STL-39-3]


DESCRIPTION
"What we really want is a conditional construct (i.e., an if...else
statement)
for types that is evaluated during compilation. As it happens, C++ already
has
a way to get that behavior. It's called overloading."
Note: Source example is for "VC++.NET2003" compiler only.

SINCE
v7.0

BENEFITS
"Traits classes make information about types available during compilation.
They're implemented using templates and template specialization.
In conjunction with overloading, traits classes make it possible to
perform
compile-time if...else on types."

EXAMPLE
#if _MSC_VER == 1310
#include <typeinfo>
template <typename IterT, typename DistT>
void advancedd( IterT& iter, DistT d ) {
//**** construction if-else
if (typeid( typename std::iterator_traits<IterT>
Violation
::iterator_category ) ==
typeid( std::random_access_iterator_tag )) {
iter += d;
} else {
if (d >= 0) { while (d--) ++iter; }
else { while (d++) --iter; }
}
}

//

#include <vector>
void example( std::vector<int>::iterator iterator, int distant ){
advancedd<std::vector<int>::iterator, int>( iterator, distant );
}
#endif

REPAIR
#if _MSC_VER == 1310
//**** overloading
template<typename IterT, typename DistT>
// use this impl for
void doAdvance( IterT& iter, DistT d,
// random access
std::random_access_iterator_tag ) { // iterators
iter += d;
}
template<typename IterT, typename DistT>
// use this impl for
void doAdvance( IterT& iter, DistT d,
// bidirectional
std::bidirectional_iterator_tag ) { // iterators
if (d >= 0) { while (d--) ++iter; }
else { while (d++) --iter; }
}
template<typename IterT, typename DistT>
// use this impl for
void doAdvance( IterT& iter, DistT d,
// input iterators
std::input_iterator_tag ) {
if (d < 0 ) {
throw std::out_of_range("Negative distance");
}
while (d--) ++iter;
}
template<typename IterT, typename DistT>
void advancett( IterT& iter, DistT d ) {
doAdvance(
// call the version of doAdvance
that
iter, d,
// is appropriate for iter's
iterator
typename
std::iterator_traits<IterT>::iterator_category( ) // OK
);

}
#include <vector>
void repair( std::vector<int>::iterator iterator, int distant ) {
advancett<std::vector<int>::iterator, int>( iterator, distant );
}
#endif

REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 47-48

When calling swap, employ a using declaration for std::swap, then call swap without
namespace qualification [STL-40-3]
DESCRIPTION
"When calling swap, employ a using declaration for std::swap,
then call swap without namespace qualification."
See also: STL-41, STL-42

SINCE
v7.0

BENEFITS
"When compilers see the call to swap, they search for the right swap to
invoke. C++'s name lookup rules ensure that this will find any T-specific
swap
at global scope or in the same namespace as the type T. If no T-specific
swap
exists,compilers will use swap in std, thanks to the using declaration
that
makes std::swap visible in this function. Even then, however, compilers
will
prefer a T-specific specialization of std::swap over the general template,
so
if std::swap has been specialized for T, the specialized version will be
used.
The one thing you want to be careful of is to not qualify the call,
because
that will affect how C++ determines the function to invoke. For example,
if
you were to write the call to swap this way,
std::swap(obj1, obj2); // the wrong way to call swap
you'd force compilers to consider only the swap in std, thus eliminating
the possibility of getting a more appropriate T-specific version defined
elsewhere."

EXAMPLE
#include <vector>
using namespace std;
template<typename T>
void doSomething( T& obj1, T& obj2 ) {
std::swap( obj1, obj2 );
}

// Violation

void foo( int a, int b ) {


doSomething<int>( a, b );
}

REPAIR
#include <vector>
using namespace std;
template<typename T>
void doSomething( T& obj1, T& obj2 ) {
using std::swap;
swap( obj1, obj2 );
}

// OK

void foo( int a, int b ) {


doSomething<int>( a, b );
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 25
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not declare the non-member to be an overloading of std::swap [STL-41-3]


DESCRIPTION
"In general, overloading function templates is fine, but std is a special
namespace, and the rules governing it are special, too. It's okay to
totally
specialize templates in std, but it's not okay to add new templates to
std.
So what to do? We still need a way to let other people call swap and get
our
more efficient template-specific version. The answer is simple. We still
declare a non-member swap that calls the member swap, we just don't
declare
the non-member to be a specialization or overloading of std::swap."
See also: STL-40, STL-42

SINCE
v7.0

NOTES
Rule detects attempt of std::swap overloading.

BENEFITS
"Programs that cross this line will almost certainly compile and run, but
their behavior is undefined. If you want your software to have predictable
behavior, you'll not add new things to std."

EXAMPLE
template<typename T>
class WidgetImpl {};
template<typename T>
class Widget {
public:
void swap( Widget<T>& other ) {

using std::swap;
swap(pImpl, other.pImpl );
}
private:
WidgetImpl<T> *pImpl;
};
namespace std {
template<typename T>
void swap( Widget<T>& a, Widget<T>& b ) {
a.swap( b );
}
}

// Violation

REPAIR
namespace WidgetStuff {
template<typename T>
class WidgetImpl {};
template<typename T>
class Widget {
public:
void swap( Widget<T>& other ) {
using std::swap;
swap( pImpl, other.pImpl );
}
private:
WidgetImpl<T> *pImpl;
};
template<typename T>
void swap( Widget<T>& a, Widget<T>& b ) {
a.swap( b );
}

// OK

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 25

2. General Principles of Software Validation;


Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Member version of swap should never throw exceptions [STL-42-3]


DESCRIPTION
"The only loose end is my admonition to have the member version of swap
never
throw exceptions. That's because one of the most useful applications of
swap
is to help classes (and class templates) offer the strong exception-safety
guarantee. (...) the technique is predicated on the assumption that the
member version of swap never throws."
See also: STL-40, STL-41

SINCE
v7.0

BENEFITS
"That's because one of the most useful applications of swap is to help
classes
(and class templates) offer the strong exception-safety guarantee."

EXAMPLE
#include <iostream>
class WidgetImpl {};
class Widget {
public:
void swap( Widget& other ) {
try {
using std::swap;
swap( pImpl, other.pImpl );
} catch(...) {
throw;
}
}
private:
WidgetImpl *pImpl;
};

// Violation

REPAIR
#include <iostream>
class WidgetImpl {};
class Widget {
public:
void swap( Widget& other ) {
// OK
try {
using std::swap;
swap( pImpl, other.pImpl );
} catch(...) {
// something else than "throw;"
}
}
private:
WidgetImpl *pImpl;
};

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 25
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

TEMPL
Template
RULES
Factor parameter-independent code out of templates [TEMPL-01-3]
Define non-member functions inside templates when type conversions are
desired [TEMPL-02-3]
Do not overload functions within a template class [TEMPL-03-3]
In template global functions use 'typename' to identify nested dependent
type names [TEMPL-04-3]
In template classes use 'typename' to identify nested dependent type names
[TEMPL-05-3]
Don't change default arguments of virtual functions in template classes
[TEMPL-06-3]
A copy constructor shall be declared when there is a template constructor
with a single parameter that is a generic parameter [TEMPL-07-3]
The viable function set for a function call should either contain no
function specializations, or only contain function specializations [TEMPL08-3]
Overloaded function templates shall not be explicitly specialized [TEMPL09-3]
All partial and explicit specializations for a template shall be declared
in the same file as the declaration of their primary template [TEMPL-10-3]
A copy assignment operator shall be declared when there is a template
assignment operator with a parameter that is a generic parameter [TEMPL11-3]
In a class template with a dependent base, any name that may be found in
that dependent base shall be referred to using a qualified-id or this->
[TEMPL-12-3]

Factor parameter-independent code out of templates [TEMPL-01-3]


DESCRIPTION
"When you're writing a function and you realize that some part of the
function's implementation is essentially the same as another function's
implementation, do you just replicate the code? Of course not. You factor
the
common code out of the two functions, put it into a third function, and
have
both of the other functions call the new one. When writing templates, you
do
the same analysis, and you avoid replication in the same ways, but there's
a twist. In non-template code, replication is explicit: you can see that
there's duplication between two functions or two classes. In template
code,
replication is implicit: there's only one copy of the template source
code, so
you have to train yourself to sense the replication that may take place
when
a template is instantiated multiple times. If you have class with non-type
template parameter, consider creating base class with the same functions,
but
taking as a additional parameter non-type template parameter from
inherited
class."

SINCE
v7.0

BENEFITS
Rule prevents possible implicit replication of code.

EXAMPLE
#include <iostream>
template<typename T>
class SquareMatrixBase {
protected:

void invert( std::size_t matrixSize );


};
template< typename T, std::size_t n>
class SquareMatrix: private SquareMatrixBase<T> { // Violation (no foo()
// in SquareMatrixBase)
public:
void foo( );
};
template< typename T, std::size_t n>
class SquareMatrix2 {
class)
public:
void foo( );
void invert( );
};

// Violation (no base

REPAIR
#include <iostream>
template<typename T>
class SquareMatrixBase {
protected:
void invert( std::size_t matrixSize );
};
template< typename T, std::size_t n>
class SquareMatrix: private SquareMatrixBase<T> {
private:
using SquareMatrixBase<T>::invert;
public:
void invert( ) { this->invert(n); }
// OK
};

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 44
2. General Principles of Software Validation;

Final Guidance for Industry and FDA Staff


Document issued on: January 11, 2002

Define non-member functions inside templates when type conversions are desired [TEMPL02-3]
DESCRIPTION
"Define non-member functions inside templates when type conversions are
desired. When writing a class template that offers functions related to
the
template that support implicit type conversions on all parameters, define
those
functions as friends inside the class template."

SINCE
v7.0

BENEFITS
"Defining functions related to the template that support implicit type
conversions on all parameters as friend prevent from improper using of
those
functions."

EXAMPLE
template<typename T>
class Rational {
public:
Rational( const T& );
};
template<typename T>
const Rational<T> operator*( // Violation
const Rational<T>& lhs, const Rational<T>& rhs )
{ /* ... */ }

REPAIR
template<typename T>
class Rational {

public:
Rational( const T& );
friend
const Rational<T> operator*( // OK
const Rational<T>& lhs, const Rational<T>& rhs )
{ /* ... */ }
};

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 46
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Do not overload functions within a template class [TEMPL-03-3]


DESCRIPTION
Overloading functions within a template class can lead to problems
if the element type appears explicitly in one of them.

BENEFITS
This rule detects if you overload functions within a template class.
Overloading functions may indicate a design flaw in the template class.

EXAMPLE
template <class T> class A
{
public:
int foo( T );
int foo( int );
// Violation
};

REPAIR
template <class T> class A
{
public:
int foo( T );
// OK
};

REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

In template global functions use 'typename' to identify nested dependent type names [TEMPL04-3]
DESCRIPTION
In template global functions use typename to identify
nested dependent type names.
See also: TEMPL-05

SINCE
v7.0

BENEFITS
"Nested dependent names can lead to parsing difficulties. (...) if the
parser
encounters a nested dependent name in a template, it assumes that the name
is
not a type unless you tell it otherwise. By default, nested dependent
names are
not types. The general rule is simple: anytime you refer to a nested
dependent
type name in a template, you must immediately precede it by the word
typename."

EXAMPLE
#include <vector>
#include <iostream>
using namespace std;
template<typename T>
void print2nd( const T& container ) {
if (container.size( ) >= 2) {
T::const_iterator iter( container.begin( ) );
++iter;
int value = *iter;
cout << value;
}
}

// Violation

void test( ) {
typedef vector<int> int_v;
int_v container( 10 );
print2nd<int_v>( container );
}

REPAIR
#include <vector>
#include <iostream>
using namespace std;
template<typename T>
void print2nd( const T& container ) {
if (container.size( ) >= 2) {
typename T::const_iterator iter( container.begin( ) );
++iter;
int value = *iter;
cout << value;
}
}
void test( ) {
typedef vector<int> int_v;
int_v container( 10 );
print2nd<int_v>( container );
}

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 42
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

// OK

In template classes use 'typename' to identify nested dependent type names [TEMPL-05-3]
DESCRIPTION
"Use typename to identify nested dependent type names, except in base
class
lists or as a base class identifier in a member initialization list."
See also: TEMPL-04

SINCE
v7.0

BENEFITS
"Nested dependent names can lead to parsing difficulties. (...) if the
parser
encounters a nested dependent name in a template, it assumes that the name
is
not a type unless you tell it otherwise. By default, nested dependent
names are
not types. The general rule is simple: anytime you refer to a nested
dependent
type name in a template, you must immediately precede it by the word
typename."

EXAMPLE
#include <vector>
using namespace std;
template<class T>
class Base {
public:
class Nested {
public:
Nested( int a );
Nested( );
void foo( );
};
};

template<typename T>
class Derived2: public Base<T>::Nested {
public:
explicit Derived2( int x ): Base<T>::Nested( x ) {
Base<T>::Nested temp;
// Violation
temp.foo( );
}
void goo(Base<T>::Nested temp){}
// Violation
};
void test( ) {
Derived2<int> obj(1);
}

REPAIR
#include <vector>
using namespace std;
template<class T>
class Base {
public:
class Nested {
public:
Nested( int a );
Nested( );
void foo( );
};
};
template<typename T>
class Derived2: public Base<T>::Nested {
public:
explicit Derived2( int x ): Base<T>::Nested( x ) {
typename Base<T>::Nested temp;
// OK
temp.foo( );
}
void goo( typename Base<T>::Nested temp ){}
// OK
};
void test( ) {
Derived2<int> obj(1);

REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 42
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Don't change default arguments of virtual functions in template classes [TEMPL-06-3]


DESCRIPTION
"When overriding a virtual function, preserve substitutability;in
particular,
observe the function's pre- and post-conditions in the base class.
Don't change default arguments of virtual functions. Prefer explicitly
redeclaring overrides as virtual. Beware of hiding overloads in the base
class."
See also: OOP-15, OOP-17

BENEFITS
This rule prevents misinterpretation which value is passed as default.

EXAMPLE
template<class T> class Base {
public:
virtual void foo( T i = 1 ) { }
};
template<class T> class Derived: public Base<T> {
public:
virtual void foo( T i = 0 ) { }
// Violation
};
void foo( ) {
Base<int>
b;
Derived<int> d;
d.foo( );
b.foo( );
}

REPAIR
template<class T> class Base {
public:
virtual void foo( T i = 1 ) { }
};

template<class T> class Derived: public Base<T> {


public:
virtual void foo( T i = 1 ) { }
// OK
};
void foo( ) {
Base<int>
b;
Derived<int> d;
d.foo( );
b.foo( );
}

REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A copy constructor shall be declared when there is a template constructor with a single
parameter that is a generic parameter [TEMPL-07-3]
DESCRIPTION
"Contrary to possible developer expectations, a template constructor
will not suppress the compiler generated copy constructor."

SINCE
v7.2

NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].

BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.

EXAMPLE
typedef signed int int32_t;
class A
{
public:
A ( );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};

// Violation

REPAIR
typedef signed int int32_t;
class A
{
public:
A ( );
A ( A const & rhs );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};

// OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

The viable function set for a function call should either contain no function specializations, or
only contain function specializations [TEMPL-08-3]
DESCRIPTION
"The viable function set for a function call should either contain no
function
specializations, or only contain function specializations. If a function
and a specialization of a function template are deemed equivalent after
overload resolution, the non-specialized function will be chosen over the
function specialization"

SINCE
v7.2

EXCEPTIONS
"Rule does not apply to copy constructors or copy assignment operators."

BENEFITS
Rule prevents writing of code that may be inconsistent
with developer expectations.

EXAMPLE
void f ( short b){}
template <typename T> void f ( T ){}

// Example 1
// Example 2

void b ( short s )
{
f ( s );
// Violation - Calls Example 1
f ( s + 1 ); // Violation - Calls Example 2
}

REPAIR
void f ( short b){}

// Example 1

template <typename T> void f ( T ){}

// Example 2

void b ( short s )
{
f<> ( s );
// OK - Calls Example 2
f<> ( s + 1 ); // OK - Calls Example 2
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

Overloaded function templates shall not be explicitly specialized [TEMPL-09-3]


DESCRIPTION
"Overloaded function templates shall not be explicitly specialized.
Explicit specializations will be considered only after overload resolution
has chosen a best match from the set of primary function templates."

SINCE
v7.2

BENEFITS
"Where a template is not overloaded with other templates, or is overloaded
with non-template functions then it can be explicitly specialized, as it
is
consistent with developer expectation that the explicit specializations
will only be considered if that primary template is chosen."

EXAMPLE
template <typename T> void f ( T );
template <typename T> void f ( T* );
template <> void f<int*> ( int* ); // Violation

REPAIR
template <typename T> void f ( T );
template <> void f<int*> ( int* ); // OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff

Document issued on: January 11, 2002

All partial and explicit specializations for a template shall be declared in the same file as the
declaration of their primary template [TEMPL-10-3]
DESCRIPTION
"It is undefined behaviour if, for a set of template-arguments, an
implicit
instantiation is generated by the compiler, and a partial or explicit
specialization is declared or defined elsewhere in the program that would
match the set of template-arguments."

SINCE
v7.2

BENEFITS
Rule prevents undefined behaviour.

EXAMPLE
// file.h
template <typename T> void foo () {}
// file.cpp
#include "file.h"
template <> void foo<int> () {} // Violation

REPAIR
// file.h
template <typename T> void foo () {}
template <> void foo<int> () {} // OK

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-7-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

A copy assignment operator shall be declared when there is a template assignment operator
with a parameter that is a generic parameter [TEMPL-11-3]
DESCRIPTION
"Contrary to possible developer expectations, a template assignment
operator will not suppress the compiler generated copy assignment
operator."

SINCE
v7.2

NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.

BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.

EXAMPLE
typedef signed int int32_t;
class A
// Violation
{
public:
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;

}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}

REPAIR
typedef signed int int32_t;
class A
// OK
{
public:
A & operator= ( A const & rhs )
{
i = rhs.i;
return *this;
}
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;
}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems

Chapter 6, Section 14, Rule 14-5-3


2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002

In a class template with a dependent base, any name that may be found in that dependent
base shall be referred to using a qualified-id or this-> [TEMPL-12-3]
DESCRIPTION
"In a class template with a dependent base, any name that may be found in
that
dependent base shall be referred to using a qualified-id or this->"

SINCE
v7.2

BENEFITS
"Using a qualified-id or prefixing the identifier with this-> ensures that
the entity chosen is consistent with developer expectations."

EXAMPLE
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
TYPE t = 0; // Violation
g ( );
// Violation
i++;
// Violation
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );

int i;
};
template class A<int>;

REPAIR
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
::TYPE t1 = 0; // OK ::g ( );
// OK ::i++;
// OK typename B<T>::TYPE t2
this->g ( );
this->i;
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );
int i;
};
template class A<int>;

explicit use
explicit use
explicit use
= 0; // OK // OK // OK -

global TYPE
global func
global var
explicit use base TYPE
explicit use base "g"
explicit use base "i"

REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-6-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff

Document issued on: January 11, 2002

También podría gustarte