You are on page 1of 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.

List parameters' indexes separated by comma or use '*' to specify that all parameters are affected. scanf("%d".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. &i). but it can also increase the number of false alarms. BENEFITS N/A DRAWBACKS N/A EXAMPLE Here is an example that will trigger a violation: #include <stdio. 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 -. "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.h> int example(int array[100]) { int i.* The 'Numbers of the parameters that are validated (1-based)' column is used to specify that the function cleans some of its parameters. return array[i]. // VIOLATION ("i" is an unknown value possibly < 0 or >= 100) } .

h> int example(int array[100]) { int i.org/top25/#CWE-131 .php/Buffer_Overflow (security relevance) CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131 http://cwe.owasp. // wrong input } return array[i].org/index. // NO VIOLATION } REFERENCES http://www. if (i < 0 || i >= 100) { return -1. &i). scanf("%d".REPAIR The following code will not trigger a violation: #include <stdio.mitre.

In a loop condition (overflow may lead to an infinite loop and thus to denial of service) . Since overflow may be expected in many cases. For details. 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. see the PARAMETERS section. 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: .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.As a memory buffer size in a memory allocation operation (overflow may cause allocation of a huge memory chunk and possibly denial of service) . SINCE .In pointer arithmetic (may cause accessing memory at illegal address and thus undefined behavior.

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. POSIX) Console Environment variables rule can be parameterized with a list of validating functions. making this-object benign.v7. Validation functions allow this data to be safely passed to dangerous functions. CArchive and CFile from MFC) Low-level input (Windows API. and/or. and/or. * 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.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. validating function can be defined as: returning benign data. making its parameter(s) benign. 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. Use '*' if you want to describe a function declared in any type or .

* 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. or a global function declared outside of any type or namespace. * The 'Function name' column should contain name of the described function.namespace. "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. * The 'Numbers of the parameters that are validated (1-based)' column is used to specify that the function cleans some of its parameters. * The 'returns validated data' column is used to specify that the function cleans its return value. Note that this applies to both instance and non-instance functions. BENEFITS N/A DRAWBACKS N/A EXAMPLE Here is an example that will trigger violations: . List parameters' indexes separated by a comma or use '*' to specify that all parameters are affected. 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.

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

header_len.h> <sys/types. total_len. . total_len = header_len. msg_len = atol(buffer). recv(socket. char* header. char* msg.h> #define BUFFER_SIZE 64 char buffer[BUFFER_SIZE]. } char* readMessage(int socket. } msg = (char*)malloc(total_len).REPAIR The following code will not trigger a violation: #include #include #include #include #include <stdio. header). if ((total_len < 0) || (total_len > MAX_LEN)) { /* check that total_len is within an acceptable range */ return 0. buffer.h> <string. #define MAX_LEN 1000000L char decode(char c) { /* Decode character */ return c.h> <stdlib. total_len += msg_len. BUFFER_SIZE. int len) { int i. MSG_NOSIGNAL).h> <sys/socket. header_len = strlen(header). /* NO VIOLATION */ if (!msg) { return 0. long msg_len. } strcpy(msg.

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

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. For details.. 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. If an application has a vulnerability of this kind. see the PARAMETERS section. SINCE v7. user input) that can return malicious data. it can be exploited to execute arbitrary code and gain full control over the application.1 NOTES N/A SECURITY RELEVANCE The possibility of buffer overflow is a severe security threat. Specifically. but is not checked for being non-negative (applicable to signed types) and not greater than the size of the corresponding buffer. POSIX) . a violation is reported if a 'size' value passed to a function reading from a buffer comes from a tainting function (e. CArchive and CFile from MFC) Low-level input (Windows API.g. 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.

. * 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. 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. making its parameter(s) benign. and/or. Validation functions allow this data to be safely passed to dangerous functions. making this-object benign. * The 'Function name' column should contain name of the described function. validating function can be defined as: returning benign data. Use '*' if you want to describe a function declared in any type or namespace. Note that this applies to both instance and non-instance functions.* Console * Environment variables The Any * * * rule can be parameterized with a list of validating functions. and/or. or a global function declared outside of any type or namespace. 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.

h> void example(int src[100]. size). memcpy(dest. int dest[100]) .h> void example(int src[100]. "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. src. List parameters' indexes separated by a comma or use '*' to specify that all parameters are affected.* The 'returns validated data' column is used to specify that the function cleans its return value.h> #include <string.h> #include <string. int dest[100]) { int size. &size). * The 'Numbers of the parameters that are validated (1-based)' column is used to specify that the function cleans some of its parameters. scanf("%d". BENEFITS N/A DRAWBACKS N/A EXAMPLE Here is an example that will trigger a violation: #include <stdio. // VIOLATION ("size" is an arbitrary value possibly < 0 or > 100) } REPAIR The following code will not trigger a violation: #include <stdio.

scanf("%d".{ int size.org/top25/#CWE-131 .owasp.php/Buffer_Overflow (security relevance) CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131 http://cwe.org/index. src. size).mitre. // NO VIOLATION } } REFERENCES http://www. if (size >= 0 && size <= 100) { memcpy(dest. &size).

a violation is reported if a 'size' value passed to a function writing to a buffer comes from a tainting function (e. 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. SINCE v7. it can be exploited to execute arbitrary code and gain full control over the application. user input) that can return malicious data. CArchive and CFile from MFC) Low-level input (Windows API. For details.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. 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. If an application has a vulnerability of this kind. see the PARAMETERS section. POSIX) ..g.1 NOTES N/A SECURITY RELEVANCE Possible buffer overflow is a severe security threat.

. * 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. * The 'Function name' column should contain name of the described function. 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. making this-object benign. making its parameter(s) benign. validating function can be defined as: returning benign data. Validation functions allow this data to be safely passed to dangerous functions. and/or. and/or. * 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.* Console * Environment variables The Any * * * rule can be parameterized with a list of validating 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. Note that this applies to both instance and non-instance functions. Use '*' if you want to describe function declared in any type or namespace. or a global function declared outside of any type or namespace.

List parameters' indexes separated by a comma or use '*' to specify that all parameters are affected.h> void example(int src[100].h> #include <string. src.h> void example(int src[100].h> #include <string. "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.* The 'returns validated data' column is used to specify that the function cleans its return value. &size). size). int dest[100]) { int size. // VIOLATION ("size" is an arbitrary value possibly < 0 or > 100) } REPAIR The following code will not trigger a violation: #include <stdio. BENEFITS N/A DRAWBACKS N/A EXAMPLE Here is an example that will trigger a violation: #include <stdio. memcpy(dest. * The 'Numbers of the parameters that are validated (1-based)' column is used to specify that the function cleans some of its parameters. int dest[100]) . scanf("%d".

if (size >= 0 && size <= 100) { memcpy(dest. // NO VIOLATION } } REFERENCES http://www.org/top25/#CWE-120 .{ int size.php/Buffer_Overflow (security relevance) CWE/SANS Top 25 Most Dangerous Software Errors: CWE-120 http://cwe.mitre. size). &size).owasp. src.org/index. scanf("%d".

#2 from the OWASP Top 10 2007 list.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. 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. If some tainted data will appear in an executed file name without verification. 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.2 NOTES N/A SECURITY RELEVANCE Enforces 'A2 . 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 . For details.Injection Flaws'. see the PARAMETERS section. SINCE v7. it may allow the execution of custom malicious code which could damage the system. to form the name of the file to be executed).

Note that this applies to both instance and non-instance 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. and/or. 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 . and/or. making its parameter(s) benign. POSIX) Console Environment variables rule can be parameterized with a list of validating functions. making this-object benign. * The 'Function name' column should contain name of the described function. or a global function declared outside of any type or namespace. CArchive and CFile from MFC) Low-level input (Windows API. Use '*' if you want to describe function declared in any type or namespace. Validation functions allow this data to be safely passed to dangerous functions. * 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. validating function can be defined as: returning benign data. * 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.* * * * * The Any * * * Pipes Stream-oriented APIs (std::istream.

users might be able to run custom code on the server with application privileges. 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. * The 'returns validated data' column is used to specify that the function cleans its return value. For example. "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. placing unverified user data into an execution request can have some dangerous consequences. For instance. List parameters' indexes separated by a comma or use '*' to specify that all parameters are affected.function cleans the object on which it is called. 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.h> . there is an option that determines whether numerical data should be considered tainted. Also. * The 'Numbers of the parameters that are validated (1-based)' column is used to specify that the function cleans some of its parameters. In such situations.

h> <sys/socket. 200. // 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. 200. "process_data -params "). 0).#include #include #include #include <stdlib.h> <string.h> <sys/types. strcat(command.php/Top_10_2007 . params. protected from command injection provided that validate() is implemented properly */ } REFERENCES OWASP Top 10 2007 (A2 . strcat(command. /* Receiving command parameters from a socket */ strcpy(command.owasp. /* properly implement validation function */ void commandInjection(int socket) { char params[200]. params.Injection Flaws): http://www. 0).org/index. /* OK. system(command).h> <string. validate(params)). command[250].h> char* validate(char*). command[250].h> <sys/socket. system(command).h> <sys/types. params). recv(socket. /* Receiving command parameters from a socket */ strcpy(command. "process_data -params "). recv(socket.h> <stdlib.h> void commandInjection(int socket) { char params[200].

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

SINCE v7.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. POSIX) . 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. providing specially-prepared malicious data. CArchive and CFile from MFC) Low-level input (Windows API. The rule supports file manipulation functions from the standard C and C++ libraries as well as those defined by POSIX. see the PARAMETERS section. which could cause a file name injection. 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.2 NOTES N/A SECURITY RELEVANCE If unverified data appears in file names.Malicious File Execution". then an attacker could potentially gain access to any file on the system. Enforcing this rule will help to protect against the OWASP 2007 Top 10 application vulnerability "A3 .

* Console * Environment variables The Any * * * rule can be parameterized with a list of validating functions. or a global function declared outside of any type or namespace. 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. Use '*' if you want to describe function declared in any type or namespace. . * The 'Function name' column should contain name of the described function. validating function can be defined as: returning benign data. Note that this applies to both instance and non-instance 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. and/or. making its parameter(s) benign. and/or. * 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. * 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. Validation functions allow this data to be safely passed to dangerous functions. making this-object benign.

List parameters' indexes separated by a comma or use '*' to specify that all parameters are affected.* The 'returns validated data' column is used to specify that the function cleans its return value. The following code may be used to create a specific file and add the story contents: #include <stdio. "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. * The 'Numbers of the parameters that are validated (1-based)' column is used to specify that the function cleans some of its parameters. char storyContent[200]. /* Receive story from socket */ . there is an option that determines whether numerical data should be considered tainted. Also.h> #include <sys/socket. a library with user stories) using the story name given by the user as the file name.h> void saveStory(int socket) { char storyName[50]. BENEFITS N/A DRAWBACKS N/A EXAMPLE Consider an application that stores some user-specific data in files on a server (for instance.h> #include <sys/types.

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

.

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. ADO.2 NOTES N/A SECURITY RELEVANCE Enforces 'A2 . #2 from the OWASP Top 10 2007 list. For details. The rule supports the following database APIs: ODBC. OLE DB. retrieve connections. If data can appear in an SQL query without being validated. it is possible for an attacker to alter the SQL statements in a way that the developer did not intend. SINCE v7. PARAMETERS This rule can be parameterized so that data from the following data sources are considered tainted . 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. see the PARAMETERS section.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. the attacker can take total control of the database or even execute commands on the system. etc. As a result. a malicious user could take control of the database.Injection Flaws'.

CArchive and CFile from MFC) Low-level input (Windows API. * The 'Function name' column should contain name of the described function. 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. Note that this applies to both instance and non-instance functions. Use '*' if you want to describe function declared in any type or namespace. making this-object benign. making its parameter(s) benign. and/or.(in addition to those previously listed in the DESCRIPTION section): * * * * * * The Any * * * Files Pipes Stream-oriented APIs (std::istream. Other columns allow to describe which of the data are affected by a given . Validation functions allow this data to be safely passed to dangerous functions. * 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. POSIX) Console Environment variables rule can be parameterized with a list of validating functions. * 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. validating function can be defined as: returning benign data. or a global function declared outside of any type or namespace. and/or.

rights FROM . * The 'Numbers of the parameters that are validated (1-based)' column is used to specify that the function cleans some of its parameters. user_class.function: * The '"this" object is validated' column is used to specify that the function cleans the object on which it is called. there is an option that determines whether numerical data should be considered tainted. List parameters' indexes separated by a comma or use '*' to specify that all parameters are affected. The code supporting this might look as follows: #include <sql.h> #include <stdio. Also.h> const int BUFFER_SIZE = 1000. for authentication purposes. const char* requestBeginning = "SELECT user_id. * The 'returns validated data' column is used to specify that the function cleans its return value. tries to find that user information in a database. "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.

request. strlen(request)). strcat(request. file). const char* requestEnding = "'". requestEnding). rights FROM users WHERE user_name = '' or ''='' and password = '' or ''='' This will get all users' information. const char* requestPassword = "' and password = '". SQLCHAR request[BUFFER_SIZE]. strcpy(request. extern char* extractUsername(const char*). extractPassword(parametersString)). void handleRequest(FILE* file) { char parametersString[BUFFER_SIZE]. BUFFER_SIZE. strcat(request.even though he did not provide the necessary authorization information. user_class.users WHERE user_name = '". requestPassword). SQLExecDirect(statementHandle. so the attacker will be authenticated as the first user in the users table -. extern char* extractPassword(const char*). 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: . strcat(request. extern SQLHSTMT statementHandle. extractUsername(parametersString)). strcat(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. 1. requestBeginning). fread(parametersString.

extern char* extractUsername(const char*).h> <sqlext. 0. 0. 1.shtml CWE/SANS Top 25 Most Dangerous Software Errors: CWE-89 . SQLBindParameter(statementHandle. fread(parametersString.Injection Flaws): http://www. requestString. &nameLen). name.org/projects/threat/classes/sql_injection.#include #include #include #include <sql. 0. SQL_CHAR. SQLBindParameter(statementHandle. extern SQLHSTMT statementHandle. passLen = SQL_NTS. SQL_C_CHAR.org/index.h> const int BUFFER_SIZE = 1000. SQL_C_CHAR.h> <stdio. SQLINTEGER nameLen = SQL_NTS. 20. 0. SQL_NTS). SQL_PARAM_INPUT.h> <sqltypes. BUFFER_SIZE. 20. SQLPrepare(statementHandle. char* pass = extractPassword(parametersString).webappsec. void handleRequest(FILE* file) { char parametersString[BUFFER_SIZE]. pass. user_class.owasp.php/Top_10_2007 Web Application Security Consortium: http://www. const char* requestString = "SELECT user_id. rights FROM users WHERE user_name = '?' and password = '?'". char* name = extractUsername(parametersString). SQL_PARAM_INPUT. 2. 1. file). SQLExecute(statementHandle). &passLen). extern char* extractPassword(const char*). SQL_CHAR. } REFERENCES OWASP Top 10 2007 (A2 .

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

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] .

it also possible to specify multithreading functions from any third-party API by providing specification of relevant functions. 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. To view the list of all the supported APIs. it is not allowed for regular locks and may cause deadlocks.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). . SINCE v9. please visit the "Multithreading" sub-tab on the "BugDetective options" tab for your test configuration. BENEFITS Prevents application deadlocks. While this is legal for the so-called recursive mutexes. "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.Avoid double locking [BD-TRS-DLOCK-1] DESCRIPTION This rule detects cases where a lock is acquired twice without intermediate releasing.

pthread_mutex_init(mutex. exclusivelyCompute(). (const pthread_mutexattr_t*)0).h> pthread_mutex_t* mutex. bool preconditionHolds(). } void run() { mutex = new pthread_mutex_t.DRAWBACKS N/A EXAMPLE Here is an example that will trigger a violation: #include <pthread. void exclusivelyCompute() { pthread_mutex_lock(mutex). } 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. static void nonexclusivelyCompute() { if (preconditionHolds()) { .h> pthread_mutex_t* mutex. bool preconditionHolds(). if (preconditionHolds()) { /* perform some computations */ exclusivelyCompute(). // VIOLATION: recursive call will cause double locking } pthread_mutex_unlock(mutex).

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

SINCE v7. You can view the list of all the supported APIs. which could cause an application deadlock. 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. 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. This practice is required by MISRA C/C++ & JSF standards. You can also specify multithreading functions from any third-party API by providing a specification of the relevant functions.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). configure the APIs that the rule will check. Lower numbers are recommended to enforce the best practice that locking and unlocking occur at the same nesting level. 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 .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.

then cases where custom wrapping APIs are used to lock a mutex but not unlock it will be detected automatically-. 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.unlocking functions. To demonstrate this. it is recommended to define them as separate multithreading APIs in the Test Configurations> Static> BugDetective Options> Multithreading tab. When such wrappers are involved. This is why the parameter of the value is set to 2 by default. it will report a violation which is in fact a false positive because mutex_lock is not meant to .even without extending BugDetective's multithreading API knowledge base with the custom API. However. // do something else } void mutex_unlock() { pthread_mutext_unlock(mutex). 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. // do something else } With the value of parameter set to 0. let's assume the following wrapper functions: void mutex_lock() { pthread_mutex_lock(mutex). Consequently. 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.

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".call unlocking function by design and pthread_mutex_unlock is called from the other wrapper function named "mutex_unlock". To properly analyze the following example. BENEFITS Prevents application deadlocks. bool preconditionHolds(). the parameter "Locked object may be unlocked from callers up to specified level" should be set to "3" or more. #include <pthread. Here is an example that will trigger a violation: #include <pthread. DRAWBACKS N/A EXAMPLE Example 1. } } Example 2. "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. if (preconditionHolds()) { /* perform some computations */ pthread_mutex_unlock(mutex). void exclusivelyCompute() { pthread_mutex_lock(mutex).h> pthread_mutex_t* mutex.h> .

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

} { unlockLevel1().pthread_mutex_t mutex. } lockLevel2(). } lockLevel1(). } REFERENCES N/A . void exclusivelyCompute() { lockLevel3(). void void void void void void lockLevel1() { unlockLevel1() lockLevel2() { unlockLevel2() lockLevel3() { unlockLevel3() pthread_mutex_lock(&mutex). if (preconditionHolds()) { /* perform some computations */ } unlockLevel3(). } { pthread_mutex_unlock(&mutex). } bool preconditionHolds(). } { unlockLevel2().

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).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. please visit "Multithreading" sub-tab on the "BugDetective options" tab for your test configuration. . To view the list of all the supported APIs. BENEFITS Helps prevent unnecessary resource contention between threads as well as thread starvation. it also possible to specify multithreading functions from any third-party API by providing specification of relevant functions. 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. "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. SINCE v7.

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

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] .

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). EXAMPLE // --. SINCE v9.h" .h" // --.h" /* Violation: "header1.2 BENEFITS Rule improves readability and maintainability.h" #include "header2. Simplifies the code and decreases preprocessing time.h --#include "header2./header1.h> is different than "header1.h" /* OK: ".h" */ #include ".h" is different than "header1.Avoid duplication of #include directives [CDD-001-4] DESCRIPTION Rule checks if there are duplicated #include directives.header1.h" #include HEADER /* OK: we don't do macro replacement */ #include HEADER /* Violation: HEADER was included previously */ #include <header1. 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).file.h" was included previously */ #define HEADER "header1.h> /* OK: <header1.h" */ #if 0 #include "header1.h" /* Violation: "header1.h" was included in outer conditional inclusion scope */ #include "header3./header1.h" /* OK: not checked against includes in other files */ #include "header1.cpp --#include "header1.

REFERENCES Recommended by Parasoft .previous inclusion was inside other conditional inclusion scope*/ REPAIR Remove duplicated #include directives if they are not needed.h" /* OK .#else #include "header3.h" /* OK .previous inclusion was inside other conditional inclusion scope*/ #endif #include "header3.

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

For example: if (param1 == 0) { return a... function names. Copying and pasting code will increase the cost of code maintenance because each time a modification is required..This rule can be parameterized to achieve best results. Reducing or eliminating the amount of duplicated code can prevent this problem. keywords. minimum duplicated tokens size ." 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. string and numeric literals.) (default is off) Turn it on to ignore identifiers differences BENEFITS Rule improves readability and maintainability. operators are count as one token. multiple instance of the same code will need to be identified and then modified. Simplifies and reduce code size. * Minimum duplicate tokens size (default value is 80) This parameter value defines minimum size of code fragment which may be reported by this rule.. } // 7 tokens // 3 tokens // 1 token "Ignore . Variable names. . EXAMPLE Parameters: Ignore identifiers turned on.

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

if (v) { result = foo(p. } // use foo function here . } else { result = p + q. } return result. q).

Avoid string literal duplication [CDD-003-2] DESCRIPTION This rule identifies code with duplicated string literals. it should be stored in a constant.2 PARAMETERS This rule can be parameterized to achieve best results. int b) { if (a > 0) { return "pass". The rule finds duplicated string literals across all tested code. If a string literal is used repeatedly. * 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. // duplicated string } if (b > 0) { . 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. A violation is reported for each occurrence. EXAMPLE const char* foo(int a. SINCE v9. whether or not the duplicated literals appear in the same file.

} if (a + b > 0) { return "pass". } return "fail". } if (a < b) { return pass. int b) { const char* pass = "pass". } return "fail".return "pass". } if (a == b) { return pass. } if (b > 0) { return pass. // duplicated string // duplicated string // duplicated string // duplicated string } REPAIR const char* foo(int a. } if (a == b) { return "pass". } . } if (a < b) { return "pass". if (a > 0) { return pass. } if (a + b > 0) { return pass.

operators are count as one token...) (default is off) Turn it on to ignore identifiers differences . string and numeric literals. Variable names. whether or not the duplicated code appears in the same file." 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.Avoid function duplication [CDD-004-2] DESCRIPTION This rule identifies duplicated implementations of functions. For example: if (param1 == 0) { return a. * Minimum duplicate tokens size (default value is 80) This parameter value defines minimum size of function which may be reported by this rule.2 PARAMETERS This rule can be parameterized to achieve best results. The rule finds duplicated implementations across all tested code... . function names. A violation is reported for each occurrence. See also: CDD-002 SINCE v9. } // 7 tokens // 3 tokens // 1 token "Ignore . keywords.

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

.

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] . 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. #define FALSE should be 0 [CODSTA-24-5] If FALSE is to be defined.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.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. use 0 instead [CODSTA-17-3] Prefer while statements over do statements [CODSTA-18-5] Use the ctype. and is not already defined. 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.

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 <%. 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- ."#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 -. %>. :>. 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. %:%: [CODSTA48-3] Null initialize or increment expressions in for loops will not be used. <:. and is not already defined. %:. and is not already defined.in the conditional expression of if. #define TRUE should be 1 [CODSTA-42-5] If TRUE is to be defined.

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. != and the unary & operator [CODSTA-69-3] Expressions with type enum shall not be used as operands to built-in operators other than [ ]. ==. 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 ("==". >. >=. !=. 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. 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] . 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 =. <=. =. "!=") [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.

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] .

(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 !=).CODSTA-CPP Coding Conventions for C++ RULES Prefer iostream.h [CODSTA-CPP-01-5] Have assignment operator returns a reference to *this. comparison operators. 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. make assignment operator's return type a non-const reference to it's class' type [CODSTACPP-02-3] Bitwise operators. logical operators. use the :: operator [CODSTACPP-23-5] . 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. || or .h to stdio. enumerated types. 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 &&.

* . Member Functions.Avoid making any assignment operator virtual. global functions. 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. << ). / . Enumerations and others [CODSTA-CPP-45-3] Order of scopes in class: public before all others [CODSTA-CPP-46-3] . 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 Operator Function. . 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 ( + . ^ .. >> . Do not return const T& from assignment operator [CODSTA-CPP-24-3] Consider making virtual functions nonpublic.

Member Functions. 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 -. structure. Member Functions. Destructor. 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. 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.or ++. <. within condition. 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. > or >= [CODSTACPP-70-3] . Member Operator Function. Destructor.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. the loop-counter shall only be used as an operand to <=. then.

otherwise if it can be made const then it shall be made const [CODSTA-CPP78-3] . ++.The loop-counter shall be modified by one of: --. 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. -=n.

Chapter: "Shifting from C to C++". "Hello World"). Item 2 2. Second Edition.h functions (such as operator>> and operator<< ). BENEFITS Prevents using instances of stdio. General Principles of Software Validation.h functions (such as scanf/printf).h functions (such as scanf/printf) and suggests changing them to iostream.h [CODSTA-CPP-01-5] DESCRIPTION This rule finds instances of stdio. EXAMPLE #include <stdio. } REFERENCES 1.. int main( ) { cout<<"Hello World"<<endl.Prefer iostream. 2002 . Addison-Wesley. Scott Meyers.h> int main( ) { printf("%s\n". // OK return 0. Final Guidance for Industry and FDA Staff Document issued on: January 11. Inc. (C) 2005 Pearson Education. // Violation return 0. } REPAIR #include <iostream> using namespace std.h to stdio. "Effective C++: 50 Specific Ways to Improve Your Programs and Design".

.

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. which is safer than just declaring it to be a reference. } }. which is safer than just declaring it to be a reference. MRM-40. See also: CODSTA-CPP-21. *this.Have assignment operator returns a reference to *this. OOP-30. class C { public: C( ) { } C operator=( C& c ) { C *cp. CODSTA-CPP-24. MRM-47. OOP-27. 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. return *cp. MRM-04. MRM-37. 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. } // Violation // Violation . EXAMPLE class A { public: A( ) { } void operator=( A& a ) { return.

} }. and Assignment Operators".. JOINT STRIKE FIGHTER.10 Classes. REPAIR class A { public: A( ) { } A& operator=( A& a ) { return *this. Chapter 3.}. Scott Meyers. Addison-Wesley. class C { public: C( ) { } C& operator=( C& c ) { return *this. Inc. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". Chapter: "Constructors. AV Rule 82 4. Destructors. General Principles of Software Validation. AIR VEHICLE. (C) 2005 Pearson Education. } }. Item 15 3. Scott Meyers. Second Edition. Third Edition.. 2002 . Final Guidance for Industry and FDA Staff Document issued on: January 11. Item 15 2. // OK // OK REFERENCES 1. Inc. (C) 2005 Pearson Education. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". C++ CODING STANDARDS Chapter 4. Addison-Wesley.

"|"." presumes that they do not change the internals of the object they are called on. logical operators. "!". comparison operators. it is a good practice to declare them const. The semantics of operators "&". A& operator==( int x ) const. CODSTA-CPP-43. comma operator should be const [CODSTA-CPP-03-3] DESCRIPTION Bitwise operators. "||" . EXAMPLE class A { public: A& operator^( int x ). to provide additional checks on the correct behavior of the code. OPT-21 BENEFITS C++ powerful const property should be enforced as appropriate. A& operator&&( int x ). A& operator.( int x ). "!=". A& operator&&( int x ) const. "==". // // // // Violation Violation Violation Violation REPAIR class A { public: A& operator^( int x ) const. MISRA2004-16_7. See also: CODSTA-CPP-38. CODSTA-CPP-44.( int x ) const.and ". "&&". }. comparison operators. A& operator. comma operator should be const.Bitwise operators. // // // // OK OK OK OK . "~". logical operators. A& operator==( int x ). MISRA-104. "<". "<=". "^". ">". }. ">=". Therefore.

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

problems that could be detected at compile time are pushed to run-time testing. } REPAIR /* One argument constructors that are not meant for type conversion should be declared explicit.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. Conversions should be performed by conversion functions rather than relying on implicit constructor calls. See also: CODSTA-CPP-05 BENEFITS Generally improves runtime performance and predictability of program behavior. */ . May detect severe coding defects masked by the compiler. affecting runtime. EXAMPLE class A { public: A( int i ) : _i( i ) {} virtual ~A( ) {} private: int _i. and in the worst. }. allow the most meaningless code to compile. Such calls may in the best case result in creating and destroying temporary objects. Constructors with one argument can be implicitly used by the compiler to perform type conversions. // Violation int main( ) { return 0. In the latter case.

Rule 40 . // OK int main( ) { return 0. Scott Meyers. Chapter: "Class Design and Inheritance". Addison-Wesley. (C) 2005 Pearson Education. "C++ Coding Standards. Item 5 2. Inc. "More Effective C++: 35 New Ways to Improve Your Programs and Designs".class A { public: explicit A( int i ) : _i( i ) {} virtual ~A( ) {} private: int _i. Chapter: "Operators". Copyright 1996. } REFERENCES 1. Andrei Alexandrescu." AddisonWesley. Herb Sutter. }.

EXAMPLE class A { public: operator const char*( ) const. // implicit conversion } REPAIR class A { public: const char* asPointerToConstChar( ) const.Do not use user-defined conversion functions [CODSTA-CPP-05-1] DESCRIPTION Be wary of user-defined conversion functions. In the latter case. problems that could be detected at compile time are pushed to run-time testing. This rule warns you when it finds user-defined conversion functions. affecting runtime. and in the worst. allow the most meaningless code to compile. const char* ch_ptr = a. . }. May detect severe coding defects masked by the compiler. See also: CODSTA-CPP-04 BENEFITS Generally improves runtime performance and predictability of program behavior. void foo(){ A a. Such calls may in the best case result in creating and destroying temporary objects. // Violation void foo(){ A a. // OK }.

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

pointer/reference to data allocated in constructor or deallocated in destructor Static variables are not considered class-data.pointer to member variable .2 NOTES Handle to class-data is: . and minimizes the creation of dangling handles.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. or an iterator.reference to member variable . It doesn't matter whether the member function returning the handle is itself const. OOP-36 SINCE v7. you run the risk that the handle will outlive the object it refers to. EXAMPLE class Test { public: . All that matters is that a handle is being returned. See also: CODSTA-CPP-77. BENEFITS The rule increases encapsulation. helps const member functions act const. It doesn't matter whether the handle is a pointer." The rule reports a violation if a member function returns reference or pointer to class-data. a reference. OOP-12. It doesn't matter whether it's qualified with const. because once that's being done.

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

2002 . REFERENCES 1. "C++ Coding Standards. Third Edition.. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". (C) 2005 Pearson Education. Chapter 5. General Principles of Software Validation.GetI1(). Andrei Alexandrescu. Item 28 3. Scott Meyers. Addison-Wesley. Chapter: "Class Design and Inheritance".{ Child c. "i2" and "i3" are dangling pointers/references } REPAIR Avoid returning handles to class-data. Inc. (C) 2005 Pearson Education. Inc. Inc. (C) 2005 Pearson Education.GetI2()." AddisonWesley.. i1 = c. Chapter: "Classes and Functions: Implementation". Rule 42 2. Item 29 4. Herb Sutter. Scott Meyers. // Reference to internal object saved // Now "ptr". Final Guidance for Industry and FDA Staff Document issued on: January 11. Second Edition. // Pointer to internal object saved } int & i2 = Child(). "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Addison-Wesley.

you have no such guarantee. In particular. You then need only maintain the prefix versions. Let us make one more observation about the prefix and postfix increment operators. That principle is that postfix increment and decrement should be implemented in terms of their prefix counterparts. they do the same thing: they increment a value. EXAMPLE class A { public: explicit A( int i = 0 ) : _i( i ) {} ~A( ) {} .0 BENEFITS This rule prevents errorneous code and increase power and flexibility of code. possibly as a result of different programmers maintaining and enhancing them? Unless you've followed the design principle embodied by the code below. 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. Except for their return values. they're supposed to do the same thing. because the postfix versions will automatically behave in a consistent fashion. postfix forms return a const object." SINCE v7.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. That is. prefix forms return a reference.

Item 6 . Chapter: "Operators". "More Effective C++: 35 New Ways to Improve Your Programs and Designs". Copyright 1996. Scott Meyers. ++(*this). return temp. ++(*this).return type is non REPAIR class A { public: explicit A( int i = 0 ) : _i( i ) {} ~A( ) {} A& operator++( ) { // OK ++_i. Prefix increment operator Postfix increment operator REFERENCES 1. }. return *this. }. } const A operator++( int ) { // OK A temp = *this. Addison-Wesley. } private: int _i. // Violation . } private: int _i.A operator++( ) reference { ++_i. return temp.return type is not // Violation . } A operator++( int ) const { A temp = *this. return *this.

2002 . Final Guidance for Industry and FDA Staff Document issued on: January 11.2. General Principles of Software Validation.

" This rule detects when you overload operator &&. || or .(comma). || or . REFERENCES 1. they become ordinary functions with very different semantics. }. EXAMPLE class A { public: A( int i ) : _i( i ) {} ~A( ).value( ) && rhs. BENEFITS Overloading these operators changes the way the compiler reads the semantics of an expression.value( ). || or. . and this is a sure way to introduce subtle bugs and fragilities. (comma) enjoy special treatment from the compiler. resulting in unpredictable program behavior.(comma). int value( ) { return _i. Herb Sutter. If you overload them. || or . Andrei Alexandrescu. "C++ Coding Standards. (comma) [CODSTA-CPP-08-3] DESCRIPTION "The built-in &&. } private: int _i.Avoid overloading &&. A& rhs ) { return lhs. } // Violation REPAIR Do not overload operator &&." AddisonWesley. int operator&&( A& lhs.

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

which may dramatically affect the safety and reliability of code. B *b = static_cast<B*>( pv ). } // Violation REPAIR class A{}. EXAMPLE class A{}. and reinterpret_cast isn't even guaranteed to do that or anything else in particular. That's the opposite of maintaining type safety. class B{}. } // OK . void *pv = a.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." BENEFITS Prevents assumptions how data is represented. void foo( ) { A *a. B *b = reinterpret_cast<B*>( a ). void foo( ) { A *a. class B{}.

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

REFERENCES // OK Recommended by ParaSoft . }. BENEFITS Readability.Do not define structs that contain member functions [CODSTA-CPP-10-3] DESCRIPTION Member functions should be contained in classes. }. It is generally expected that types with member functions are classes. Structs are also often entirely public: whereas the default access level for members and base classes of a class is private. // Violation REPAIR class A { public: int foo( ). EXAMPLE struct A { public: int foo( ). because classes support both multiple instances and encapsulation. not structs. This rule detects if you define structs that contain member functions. and many programmers still think of structs in terms of their original meaning in C.

.

Prefer C++-style casts [CODSTA-CPP-11-3] DESCRIPTION This rule detects C-style casts in your code." BENEFITS "Programs that use the new casts are easier to parse (both for humans and for tools). C++ introduces several new-style casts (const_cast. reinterpret_cast. Next. }. and static_cast) that address these problems. void foo2(){ Base* b. d = (Derived*)b. "Traditional C-style casts raise several concerns. First. Thus. they enable most any type to be converted to most any other type without any indication of the reason for the conversion. dynamic_cast. j. } // Violation class Base { Base( ). double d = (double)i/j. // Violation . class Derived : public Base {}. and they allow compilers to diagnose casting errors that would otherwise go undetected. both the location of conversion expressions as well as the subsequent analysis of the conversion rationale proves difficult for C-style casts. virtual ~Base( ). Derived* d. Not only are these casts easy to identify." EXAMPLE void foo1(){ int i. Consequently. but they also communicate more precisely the developer’s intent for applying a cast. the C-style cast syntax: '(type) expression' is difficult to identify for both reviewers and tools.

AIR VEHICLE. Inc." AddisonWesley. double d = static_cast<double>(i)/j.23 Type Conversions. JOINT STRIKE FIGHTER. virtual ~Base( ). } // OK class Base { Base( ). "C++ Coding Standards. Derived* d. Rule 95 3. class Derived : public Base {}. } // OK REFERENCES 1. Copyright 1996. }. void foo2(){ Base* b. C++ CODING STANDARDS Chapter 4. d = dynamic_cast<Derived*>(b). Herb Sutter.} REPAIR void foo1(){ int i. Chapter: "Basics". Chapter: "Type Safety". Item 2 2. Addison-Wesley. AV Rule 185 . "More Effective C++: 35 New Ways to Improve Your Programs and Designs". Andrei Alexandrescu. Scott Meyers. j. (C) 2005 Pearson Education.

class B : public A { A* a. See also: CODSTA-CPP-15. // OK // OK REFERENCES Ellemtel Coding Standards http://www. CODSTA-CPP-14.classes that are used as base classes.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). .Rule 8 . // source. EXAMPLE class A {}. they must be included as separate include files: .org/resources/cstyle/Ellemtel-rules-mm. }. }.4 Include Files .html From: 4 Source Code in Files .classes that are used as member variables.h class A {}.h" class B : public A { A* a.cpp #include "header.chris-lott.4. // Violation // Violation REPAIR // header. CODSTA-CPP-13 BENEFITS Rule improves readability and maintainability.

.

EXAMPLE class A {}.classes that appear as return types See also: CODSTA-CPP-15.chris-lott. class B { A* foo( ).Rule 8 . }.h class A {}.org/resources/cstyle/Ellemtel-rules-mm.h" A* moo( ).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).4.4 Include Files . they must be included as separate include files: .cpp #include "header. // OK // OK REFERENCES Ellemtel Coding Standards http://www. A* moo( ). class B { A* foo( ). // Violation // Violation REPAIR // header. // source. }.html From: 4 Source Code in Files . CODSTA-CPP-12 BENEFITS Rule improves readability and maintainability. CODSTA-CPP-14.

.

void moo( A* a ). CODSTA-CPP-13. }.chris-lott. class B { void foo( A* a ). // source. class B { void foo( A* a ). // Violation // Violation REPAIR // header.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).cpp #include "header.html . // OK // OK REFERENCES Ellemtel Coding Standards http://www. See also: CODSTA-CPP-15. they must be included as separate include files: . }.h class A {}.org/resources/cstyle/Ellemtel-rules-mm. CODSTA-CPP-12 BENEFITS Rule improves readability and maintainability. EXAMPLE class A {}.h" void moo( A* a ).classes that appear as argument types in function/member function prototypes.

4 Include Files .Rule 8 .4.From: 4 Source Code in Files .

// Violation REPAIR // header. EXAMPLE void moo( ). // OK .h void moo( ).h" class A { inline void foo( ) { moo( ). CODSTA-CPP-13." See also: CODSTA-CPP-14. } }. CODSTA-CPP-12 BENEFITS Rule improves readability and maintainability.function prototypes for function/member function used in inline member function are defined in the file.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).cpp #include "header. class A { inline void foo( ) { moo( ). they must be included as separate include files: . // source. } }.

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

'<' operator without '>' operator . it also expects to be able to apply the negation of that operator against a class. 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. its semantic opposite is the operator!=. bool operator>=( C& c ). }. REPAIR class C { // OK public: bool operator<=( C& c ).'==' operator without '!=' operator . which should also be defined if operator== was defined.'<<' operator without '>>' operator . A good example is the operator==." Rule prevents using: .When two operators are opposites (such as == and !=).'+' operator without '-' operator .'++' operator without '--' operator . EXAMPLE class C { // Violation public: bool operator<=( C& c ). }. .'<=' operator without '>=' operator .'&&' operator without '||' operator BENEFITS Rule improves readability and maintainability of code and prevents misunderstanding the meaning of an overloaded operator.

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

This rule applies only to the C++ programming language. Final Guidance for Industry and FDA Staff Document issued on: January 11. 2002 . Position_t Pos. EXAMPLE struct Position_t {}. // OK REFERENCES 1. struct Position_t Pos. BENEFITS Not using the struct keyword to declare a variable improves code readability. General Principles of Software Validation.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. // Violation REPAIR struct Position_t {}.

AV Rule 207 3. enumerated data types. Ellemtel Coding Standards http://www. General Principles of Software Validation. 19 2. // Violation // Violation // Violation REPAIR class A { public: enum Days {yesterday}. Static variables in a class should be used instead of global variables and constants.chris-lott.html from: 5 Assigning Names ." BENEFITS Rule improves readability and maintainability of code. and typedefs.Encapsulate global variables and constants.org/resources/cstyle/Ellemtel-rules-mm. myint glob. enumerated types. }. EXAMPLE enum Days {yesterday}. JOINT STRIKE FIGHTER. AIR VEHICLE.Rec. typedef int myint. Final Guidance for Industry and FDA Staff . typedef int MyInt. C++ CODING STANDARDS Chapter 4. static MyInt glob.26 Memory Allocation. // OK // OK // OK REFERENCES 1. and typedefs in a class [CODSTA-CPP-18-5] DESCRIPTION "Encapsulate global variables and constants. and typedefs in a class. enumerated types.

4 .Document issued on: January 11. ISO/DIS 26262 point 8.4. 2002 4.

See also: MRM-05. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". If you follow this rule. OOP-34 BENEFITS Readability. OOP-30. Addison-Wesley. especially pointer members. // OK REFERENCES Scott Meyers. Inc. OOP-27.. This rule detects if you do not declare at least one constructor. // Violation REPAIR class A { A(){} }. Third Edition. Item 5 . EXAMPLE class A { }. (C) 2005 Pearson Education. MRM-38. you will make class initialization explicit and prevent the compiler from initializing members improperly. Chapter 1.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. MRM-48. the compiler will write a public constructor for you by default. MRM-40.

multiplication. earlier we were concerned about implicit type conversions. // Violation . Here the goal is a natural calling syntax. If f is operator>> or operator<<. }. You know you'd like to support arithmetic operations like addition. make f a non-member function. class A{ public: A(int x=0). a non-member function.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. operator>> and operator<< are never members. etc. EXAMPLE #include <iostream> using namespace std. class B{ public: istream& operator>>(istream& input). subtraction. If class contains a conversion operators or constructors allowing implicit conversion you should define operators global because it makes operations commutative.. BENEFITS Differentiating among functions leads to more object-oriented code with behavior that is more intuitive to use and maintain. A& operator+(A& a). // Violation // should be global ostream& operator<<(ostream& output) { as = "aaaa". but you're unsure whether you should implement them via a member function. // Violation (could be global) }.

Item 19 2. Chapter: "Classes and Functions: Design and Declaration". }. (C) 2005 Pearson Education. Scott Meyers. // OK class B{ public: friend ostream& operator<<(ostream& output.. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". B& out) { out. A& operator+(A& a. Second Edition. // OK // OK REFERENCES 1. General Principles of Software Validation. B& out).as = "aaaa". private: char* as. return output. }.const B& in). ostream& operator<<(ostream& output. Final Guidance for Industry and FDA Staff Document issued on: January 11. Inc. A& b). 2002 . REPAIR class A{ public: A(int x=0). Addison-Wesley. istream& operator>>(istream& input. }. }.// should be friend private: char* as.

}. Chapter: "Construction. EXAMPLE class MyClass { public: void operator=( const MyClass& ).Assignment operator must return const reference [CODSTA-CPP-21-5] DESCRIPTION "An assignment operator ought to return a const reference to the assigning object." Addison-Wesley. // Violation REPAIR class MyClass { public: const MyClass& operator=( const MyClass& ). CODSTA-CPP-24. // OK }.Andrei Alexandrescu. and Copying". OOP-27. MRM-40. MRM-37. Inc. (C) 2005 Pearson Education. Destruction. Rule 55 ) which is implemented in CODSTA-CPP-24 BENEFITS Rule improves readability and maintainability. REFERENCES Ellemtel Coding Standards . "C++ Coding Standards. MRM-47." See also: CODSTA-CPP-02. OOP-30. MRM-04. OOP-34 NOTES The rule became obsolete because of new standard (Herb Sutter.

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

the choice isn't between member and non-member functions. The member function actually yields less encapsulation than the nonmember.0 BENEFITS Rule ensures greater flexibility and safety of code. Friends have the same access to a class's private members that member functions have. yields fewer compilation dependencies and an increase extensibility. in turn. hence the same impact on encapsulation. Furthermore. From an encapsulation point of view. }. SINCE v7. EXAMPLE class WebBrowser { public: void clearCache()." Rule reports violation on the member functions which call public functions and don't have the access to private and protected members. void WebBrowser::clearEverything() { // Violation . void clearEverything(). void clearHistory(). related functionality. and that. it's between member functions and non-member non-friend functions. void removeCookies(). offering the non-member function allows for greater packaging flexibility.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.

void clearHistory(). "Effective C++: 55 Specific Ways to Improve Your Programs and Design". wb.clearHistory(). Third Edition. Addison-Wesley.clearCache(). Inc. void removeCookies().removeCookies(). 2002 . Item 23 2.. Scott Meyers. clearHistory(). General Principles of Software Validation. removeCookies(). (C) 2005 Pearson Education. Final Guidance for Industry and FDA Staff Document issued on: January 11. }. wb. void clearEverything(WebBrowser& wb) { wb. } // OK REFERENCES 1. } REPAIR class WebBrowser { public: void clearCache().clearCache(). Chapter 4.

Using the :: operator in these situations will make it easier to determine which variable is being used. } void globalFoo1( ) { } void globalFoo2( ) { globalFoo1( ). } // Violation // Violation REPAIR namespace N { void globalFoo1( ). Using the :: operator helps the maintainer of code clearly identify used function. BENEFITS Readability and maintainability. use the :: operator.Whenever a global function is referenced. This rule detects if you do not use the :: operator whenever a global function is used. } void globalFoo1( ) { } void globalFoo2( ) { ::globalFoo1( ). // OK . EXAMPLE namespace N { void globalFoo1( ). use the :: operator [CODSTA-CPP-23-5] DESCRIPTION Whenever a global function is used. N::globalFoo1( ).

// OK } REFERENCES Recommended by ParaSoft .::N::globalFoo1( ).

// Violation const A& operator=(const A&). CODSTA-CPP-21. // Violation // Violation template<class T> class C { public: const C<T>& operator=(const C<T>&). . MRM-40. Do not return const T& from assignment operator [CODSTA-CPP-24-3] DESCRIPTION "Avoid making any assignment operator virtual. MRM-47. // Violation }. OOP-34 BENEFITS Rule prevents lack of error safety and improves good programming style. template<class T> class B { public: virtual T& operator=(const T&). it has the drawback that you wouldn't be able to put T objects into standard library containers. Although this has the benefit of preventing odd code like (a=b)=c.g. OOP-30. MRM-37. "Don't return const T&. virtual void Assign(const &T)). MRM-04. }. const B<T>& operator=(B<T>&). EXAMPLE class A { public: virtual int& operator=(const int&).Avoid making any assignment operator virtual." See also: CODSTA-CPP-02." If you need virtual assignment. OOP-27. the containers require that assignment return plain T&. prefer to provide a named function instead (e. // Violation }. // Violation virtual T& operator=(T&).

// OK // OK // OK // OK // OK // OK REFERENCES 1. General Principles of Software Validation. template<class T> class B { public: T& operator=(const T&). Destruction. Herb Sutter. }. Andrei Alexandrescu. Rule 55 2. "C++ Coding Standards. (C) 2005 Pearson Education. and Copying". B<T>& operator=(B<T>&). Inc. A& operator=(const A&). T& operator=(T&)." AddisonWesley. 2002 . }.REPAIR class A { public: const int& operator=(const int&). Final Guidance for Industry and FDA Staff Document issued on: January 11. }. template<class T> class C { public: C<T>& operator=(const C<T>&). Chapter: "Construction.

EXAMPLE class A{ public: virtual void foo(). makes the base class robust in the face of change. and public functions nonvirtual [CODSTA-CPP25-3] DESCRIPTION "Prefer to make public functions nonvirtual." BENEFITS Rule helps keeping good class encapsulation." EXCEPTIONS "Rule doesn't apply to destructors because of their special order of execution. // OK }. // Violation void goo(). . Prefer to make virtual functions private. REPAIR class B{ public: void goo(). private: virtual void foo(). }. allows each interface to take its natural shape. or protected if derived classes need to be able to call the base versions.Consider making virtual functions nonpublic.

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

void foo01( ). Don't do that." SINCE v7. where ADL pulled in names from other namespaces inappropriately just because types from those namespaces were being used nearby. It can and does happen in C++ with the use of any type that is defined in the same namespace as functions . // Violation .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 especially never ever put templated functions or operators into the same namespace as a user-defined type. 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. This problem is not unique to uses of the standard library. and most especially operators that aren't specifically related to that type. mainly when the standard library is used. and the odds are decent that the mystery culprit was some form of the aforementioned problem. EXAMPLE namespace NS1 { class Class {}.0 BENEFITS This rule prevents from mysterious and incomprehensible compiler errors.especially templated functions.

Rule 58 . // OK void foo04( Class* x ). void foo02( int x ). } namespace NS2 { void foo01( ). "C++ Coding Standards. // OK } REPAIR namespace NS1 { class Class {}. void foo03( Class x ). } // OK // OK // OK // OK REFERENCES Herb Sutter.void foo02( int x )." Addison-Wesley. Andrei Alexandrescu. void foo04( Class* x ). Chapter: "Namespaces and Modules". (C) 2005 Pearson Education. // Violation void foo03( Class x ). Inc.

" Addison-Wesley." BENEFITS Rule improves efficiency and readability of code. }. Andrei Alexandrescu. Chapter: "Namespaces and Modules". const N::X&).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. Rule 57 . }. EXAMPLE namespace N{ class X{ public: void foo(). (C) 2005 Pearson Education. // Violation REPAIR namespace N{ class X{ public: void foo(). "C++ Coding Standards. X operator+(const X&). } N::X operator+(const N::X&. Inc. } // OK REFERENCES Herb Sutter.

.

. | . & . Herb Sutter." Addison- .When binary arithmetic operators are defined ( + . ^ . B operator+=( B& a ). This rule warns you whenever it finds binary operator without canonical assignment version.. }. A operator+( A& a. / . % . . // OK A operator+=( A& a. // OK class B{ B operator+( B& a ). << ). A& b ). assignment versions should be provided too [CODSTA-CPP-28-3] DESCRIPTION When binary arithmetic operators are defined ( + . "C++ Coding Standards. See also: CODSTA-CPP-29 BENEFITS Assignment versions of operator are more efficient than standalone versions. class B{ B operator+( B& a ). & . EXAMPLE class A{}. | . A operator+( A& a. A& b ). . * . * . A& b ). // OK // OK REFERENCES 1. ^ . }. assignment versions should be provided too. Andrei Alexandrescu. >> . // Violation operator+ without operator+= // Violation operator+ without operator+= REPAIR class A{}. / . >> . % . << ).

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

The canonical way of achieving this goal is to define @ in terms of @=. Also it is desired to have operator@ accepting its first parameter by value and returning a const value. it will have the desirable property of accepting the same implicit conversions on its left-hand side and right-hand side parameters. return temp @= rhs. See also: CODSTA-CPP-28. and this can give the compiler more leeway in applying optimizations. << ) in terms of its assignment version @= so a@=b and a=a@b have the same meaning. . / . | . } T operator@( const T& lhs. * . % . } Where possible make operator @= a nonmember function. as follows: T& T::operator@=(const T&){ // implementation return *this. you arrange for compiler itself to perform the copy for you implicitly. & .. ^ .Prefer the canonical forms of arithmetic and assignment operators [CODSTA-CPP-29-3] DESCRIPTION Define binary operator @ (where @ is + . 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 . CODSTA-CPP-52 BENEFITS If operator@ is made a nonmember function. @= adhere to presented above conventions. >> . By having operator@ accepting its first parameter by value. const T& rhs){ T templ(lhs). Rule checks if declared binary operators @.

in one shot. d) .Declare and initialize temporary // local variable by first parameter }.Operator method should be // Violation .Incorrect operation name . c.No return statement.The function's return type // // be a reference to class .// . A operator*( A& a. and assigns the final result t a.potentially useful constructs such as a = (b + c). concatenates strings b. n.replace(pos. A& b ){ example // Violation . }. A operator+( A& a. return tmp += b.The last operation of "*=" function // should be return *this }. return tmp *= b.Operator method should result // class as a direct type // . A& b ){ // Violation .Code does not match with // A tmp(a).expressive code that. return a. EXAMPLE class A{ public: A( const A& ).operator+=( a ). A operator+=( A& a ){} A operator-=( A& a ){} A& operator-( A& a ){} global A operator*=( A& a ){} should // Violation . replaces some characters. REPAIR class A{ public: code from rule description // Violation ...

A& b ){ A tmp(a). } }. Chapter: "Functions and Operators". Final Guidance for Industry and FDA Staff Document issued on: January 11. implementation . implementation . A& b ){ A tmp(a)." AddisonWesley. A operator-( A& a... return tmp += b. return *this. // OK // OK // OK A operator*( A& a.. }. Rule 27 2. } // OK // OK // OK A operator+( A& a. General Principles of Software Validation. // OK // OK // OK REFERENCES 1. (C) 2005 Pearson Education. A& b ){ A tmp(a)... return *this.. implementation . Inc. Herb Sutter. return tmp -= b... } A& operator-=( A& a ){ // OK // . "C++ Coding Standards. } A& operator*=( A& a ){ // OK // .. return *this. 2002 . }... return tmp *= b.A& operator+=( A& a ){ // OK // .. Andrei Alexandrescu.

public: complex( double r. im( i ) {} complex operator+ ( complex ).0 BENEFITS Declaration of non-member functions allows compilers to perform implicit type conversions on all arguments and supports mixed mode arithmetic. }. public: complex( double r. im. complex b ) { complex r = a. return r += b. // OK // Violation ." SINCE v7. complex operator+( complex a. double i ) : re( r ). double i ) : re( r ). }. im. complex operator+=( complex ). EXAMPLE class complex { double re.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. REPAIR class complex { double re. im( i ) {} complex& operator+=( complex a ).

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

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'. explicit A( double ) {} }. EXAMPLE class A { public: explicit A( int ). A( double ) {} }. REPAIR class A { public: A( int ). // 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. REPAIR class A { public: int foo( ). This rule detects if you define member functions in the class definition. inline int A::bar( ) { return 0. inline int bar( ). EXAMPLE class A { public: int foo( ) {}. however. // OK . }. }. // Violation inline int A::bar( ) { return 0. inline int bar( ). See also: CODSTA-CPP-33 BENEFITS This rule ensure better data hiding by separating interface and implementation. int A::foo( ) {}. defining member functions within a class definition also makes the class definition less compact and harder to read.

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

however. EXAMPLE template <class T> class A { public: void foo( ) {} }. template <class T> void A<T>::foo( ) {} REFERENCES Recommended by ParaSoft // OK . // Violation REPAIR template <class T> class A { public: void foo( ). See also: CODSTA-CPP-32 BENEFITS This rule ensure better data hiding by separating interface and implementation. }. This rule detects if you define member functions in the class definition.Member functions shall not be defined within the template class definition [CODSTA-CPP-333] DESCRIPTION Functions defined within the class definition are implicitly inline. defining member functions within a class definition also makes the class definition less compact and harder to read.

.

(C) 2005 Pearson Education. Consider replacing uses of static_cast with its more powerful relative dynamic_cast. Herb Sutter. void foo( B* pb.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. } // OK REFERENCES 1. class D : public B {}. "C++ Coding Standards. Chapter: "Type Safety". class D : public B {}." BENEFITS Rule improves safety and reliability of code. void foo( B* pb. Rule 93 . } // Violation REPAIR class B {}. D* pd ) { B* pb2 = dynamic_cast<B*>( pd ). and then you won't have to remember when static_cast is safe and when it's dangerous. D* pd ) { B* pb2 = static_cast<B*>( pd ). Inc." AddisonWesley. EXAMPLE class B {}. Andrei Alexandrescu.

2.4 . ISO/DIS 26262 point 8.4.

If you're performing a dynamic_cast on an object in a single-inheritance hierarchy four levels deep. class Window { virtual void onResize( )..Avoid dynamic_casts [CODSTA-CPP-35-3] DESCRIPTION "This example also demonstrates that if you find yourself wanting to cast. at least one common implementation is based in part on string comparisons of class names.. Avoid casts whenever practical.0 NOTES Rule disallows usage of dynamic_casts. it's a sign that you could be approaching things the wrong way. BENEFITS "(. For example." SINCE v7. especially dynamic_casts in performance-sensitive code.) Many implementations of dynamic_cast can be quite slow.hpp> using namespace std. class SpecialWindow : public Window { ." EXAMPLE #include <vector> #include <boost/tr1/memory. each dynamic_cast under such an implementation could cost you up to four calls to strcmp to compare class names. }. This is especially the case if your want is for dynamic_cast.

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

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

All data and functions in a file should be inside one or more namespaces. void foo(). EXAMPLE int var = 0. // OK void globalfoo( ) { // OK } class A { int i. classes. BENEFITS Prevents the use of global variables. and global functions outside namespaces. classes. // Violation void globalfoo( ) { // Violation } class A { int i. }.Avoid using global variables. // Violation REPAIR namespace name1 { int var = 0. global functions. and global functions outside of namespaces. and class in file outside namespaces [CODSTA-CPP-36-3] DESCRIPTION This rule detects the use of global variables. } // OK . void foo( ). }.

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

// .. then it becomes a local type.. BENEFITS If you define a struct/class in a function (as opposed to declaring it).cannot be reused by the compiler . } REFERENCES Recommended by ParaSoft .can result in non-compatible definitions for the same declared type. } REPAIR class A { // OK // .. void foo(){ // .Do not define class/struct/union inside function implementation [CODSTA-CPP-37-3] DESCRIPTION Do not define class/struct/union inside function implementation. }... which .. }... EXAMPLE void foo(){ class A { // Violation // .

EXAMPLE class A { public: A& operator()( int x ). "[]". MISRA-104. operator->. it is a good practice to declare them const. }. operator int( ) const. Therefore. MISRA2004-16_7. "->". and cast operators presumes that they do not change the internals of the object they are called on.Conversion operator. operator->. operator(). // Violation A& operator->( ). OPT-21 BENEFITS C++ powerful const property should be enforced as appropriate. operator[] should be const. // Violation }. operator[] should be const [CODSTA-CPP-38-3] DESCRIPTION Conversion operator. // Violation A& operator[]( int x ). // Violation operator int( ). A& operator[]( int x ) const. The semantics of operators "()". A& operator->( ) const. REPAIR class A { public: A& operator()( int x ) const. operator(). CODSTA-CPP-43. CODSTA-CPP-44. See also: CODSTA-CPP-03. to provide additional checks on the correct behavior of the code. REFERENCES // // // // OK OK OK OK .

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

don't write namespace-level using directives or using declarations. because headers can never know what other header #includes might appear after them.h> using namespace std. Rule also prevents messing with the meaning of code in someone else's header.h> // file. instead.cpp #include <stdio. BENEFITS Prevents writing usings directives in header files which are meant to be included in an unbounded number of implementation files. // file2. not for you to inflict on others: Never write a using declaration or a using directive before #include directive. EXAMPLE // file1. The second rule follows from the first.h> using namespace std.cpp #include "file.h> // Violation // Violation . explicitly namespace-qualify all names. In header files.h" #include <stddef.Don't write namespace usings in a header file or before an #include [CODSTA-CPP-39-3] DESCRIPTION "Namespace usings are for your convenience." EXCEPTIONS This rule doesn't apply to writing class member using declarations to bring in base class member names as needed.h #include <stdio. #include <stddef.

Herb Sutter. General Principles of Software Validation. // OK REFERENCES 1. Chapter: "Namespaces and Modules"." AddisonWesley.h> #include <stddef. (C) 2005 Pearson Education. "C++ Coding Standards. Final Guidance for Industry and FDA Staff Document issued on: January 11. Inc. Rule 59 2. 2002 .REPAIR // file. Andrei Alexandrescu.h> using namespace std.cpp #include <stdio.

// exception definition Base( ) { if (numObjects >= 1) throw X( ). // constructor stuff here ++numObjects. REPAIR class Base { // OK public: class X {}. }. } ~Base( ) { --numObjects. BENEFITS Limiting the number of objects in a class can reduce code complexity. // destructor stuff here .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. // destructor stuff here } private: static int numObjects. EXAMPLE class Base { // Violation public: class X {}. // exception definition Base( ) { // limit missing // constructor stuff here ++numObjects. } ~Base( ) { --numObjects.

} private: static int numObjects. Copyright 1996. REFERENCES Scott Meyers. Item 26 . Chapter: "Techniques". Addison-Wesley. "More Effective C++: 35 New Ways to Improve Your Programs and Designs". }.

Final Guidance for Industry and FDA Staff Document issued on: January 11. 2002 . enum Colors c.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. // OK REFERENCES 1. General Principles of Software Validation. GREEN }. 'enum' keyword is unnecessary in C++ when declaring a variable. // Violation REPAIR enum Colors { RED. This rule applies only to the C++ programming language. BENEFITS Readability. EXAMPLE enum Colors { RED. BLUE. Colors c. GREEN }. BLUE.

return month. private: mutable int month. int Date::getMonth( ) const { month++. EXAMPLE class Date{ public: int getMonth( ) const. } REPAIR Do not declare member variables with the 'mutable' keyword REFERENCES Recommended by ParaSoft .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. // Violation int year. int day. BENEFITS Prevents using the keyword `mutable'. This rule applies only to the C++ programming language. }.

x++. you should use const to protect variables from unintended modifications when the function returns.x. int Bar( Foo &f ) { return f. } // Violation int FooBar( Foo &f ) { // OK return f. } . CODSTA-CPP-44. MISRA2004-16_7.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. EXAMPLE struct Foo { int x. It also prevents future revisions from unintentional changing the caller's data. MISRA-104. OPT-21 NOTES The rule does not report violations on virtual functions. }. int y. CODSTA-CPP-38. BENEFITS Declaring parameters which are not modified as const reference instead of reference improves legibility. See also: CODSTA-CPP-03.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. } // OK REFERENCES 1.x. int Bar( const Foo &f ) { return f. General Principles of Software Validation. Final Guidance for Industry and FDA Staff Document issued on: January 11. Addison-Wesley. (C) 2005 Pearson Education. Scott Meyers. Inc. "Effective C++: 55 Specific Ways to Improve Your Programs and Design".. Chapter 1. Chapter 6. int y.REPAIR struct Foo { int x. Section 7. Item 3 2. }. Rule 7-1-2 3. Third Edition. 2002 .

MISRA-104. CODSTA-CPP-38.0 BENEFITS "Decrease compilation time. code duplication can be avoided by having the non-const version call the const version. CODSTA-CPP-43. OPT-21 SINCE v7. maintenance. MISRA2004-16_7." EXAMPLE #include <iostream> #include <string. } private: { // OK // Violation .h> using namespace std." See also: CODSTA-CPP-03.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. } char& operator[]( size_t position ) { // do bounds checking // log access data // verify data integrity return text[ position ]. class TextBlock { public: const char& operator[]( size_t position ) const // do bounds checking // log access data // verify data integrity return text[ position ]. and code-bloat headaches.

Third Edition. class TextBlock { public: const char& operator[]( size_t position ) const { // OK // some code return text[ position ]. }. REFERENCES Scott Meyers. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". (C) 2005 Pearson Education.. }. REPAIR #include <iostream> #include <string.h> using namespace std.string text. Inc. Item 3 . Chapter 1. Addison-Wesley. } private: string text. } char& operator[]( size_t position ) { // OK return const_cast<char&>( static_cast<const TextBlock&>(*this)[ position ] ).

CODSTA-CPP-49 BENEFITS Rule makes source code more readable. CODSTA-CPP-47.In the private section of a class items shall be declared in the following order: Constructors. ~A( ). See also: CODSTA-CPP-46. REFERENCES Recommended by ParaSoft . EXAMPLE class A // Violation { private: A( ). }. Member Operator Function. }. Destructor. 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. Member Functions. REPAIR class A // OK { private: A( ). CODSTA-CPP-48. int foo( ). int foo( ). ~A( ).

.

Ellemtel Coding Standards http://www. REPAIR class Test { public: void foo1( protected: void foo2( private: void foo3( }.6.Order of scopes in class: public before all others [CODSTA-CPP-46-3] DESCRIPTION Public section must be before protected and private sections.chris-lott. ). EXAMPLE class Test { protected: void foo2( private: void foo3( public: void foo1( }. CODSTA-CPP-47. // Violation ). CODSTA-CPP-48.1 Classes . See also: CODSTA-CPP-45. C++ CODING STANDARDS .Rule 20 2. ). REFERENCES 1. ). // OK ).org/resources/cstyle/Ellemtel-rules-mm. CODSTA-CPP-49 BENEFITS Readability and maintainability. JOINT STRIKE FIGHTER. ).html From: 6 Style . AIR VEHICLE.

Chapter 4.9 Style. AV Rule 57 .

EXAMPLE class Test {// Violation public: void foo1( ). CODSTA-CPP-48.1 Classes . protected: void foo2( ). }. JOINT STRIKE FIGHTER.Rule 20 2. REFERENCES 1. private: void foo3( ). REPAIR class Test {// OK public: void foo1( ).chris-lott.org/resources/cstyle/Ellemtel-rules-mm. protected: void foo2( ). CODSTA-CPP-46. AIR VEHICLE. CODSTA-CPP-49 BENEFITS Rule improves readability and maintainability. private: void foo3( ). Ellemtel Coding Standards http://www.html From: 6 Style . See also: CODSTA-CPP-45. }.6.Order of scopes in classes: protected before private [CODSTA-CPP-47-3] DESCRIPTION Protected section must be before private section. C++ CODING STANDARDS .

Chapter 4. AV Rule 57 .9 Style.

EXAMPLE class A // Violation { protected: A( ). }. Destructor. REFERENCES Recommended by ParaSoft . CODSTA-CPP-46.In the protected section of a class items shall be declared in the following order: Constructors. REPAIR class A // OK { protected: A( ). 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. int foo( ). Member Operator Function. ~A( ). }. int foo( ). ~A( ). CODSTA-CPP-47. CODSTA-CPP-49 BENEFITS Rule makes source code more readable. See also: CODSTA-CPP-45. Member Functions.

.

REFERENCES Recommended by ParaSoft . }. int foo( ). See also: CODSTA-CPP-45. CODSTA-CPP-46. CODSTA-CPP-48 BENEFITS Readability. CODSTA-CPP-47. ~A( ).In the public section of a class items shall be declared in the following order: Constructors. REPAIR class A { // OK public: A( ). }. Member Functions. Destructor. Member Operator Function. int foo( ). EXAMPLE class A { // Violation public: A( ). 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. ~A( ).

the committee does not have a mandate to remove a heavily used feature – however redundant or dangerous it may be. This program genuinely has two integers called g l o b . Thus. EXAMPLE static int glob. "By deprecating a feature." SINCE v7. // file2: static int glob .0 BENEFITS Rule prevents using deprecated language structures. the standards committee expresses the wish that the feature would go away. which usually means ‘‘statically allocated. // Violation . Use unnamed namespaces instead. Each g l o b is used exclusively by functions defined in its translation unit. a deprecation is a strong hint to the users to avoid the feature. However. Note that static keyword is perfectly legal in C files at the file scope. For example: // file1: static int glob . The use of static to indicate "local to translation unit" is deprecated in C++. The keyword s t a t i c .’’ can be used to indicate that a function or an object is local to a translation unit.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).

2002 . General Principles of Software Validation. static int b. Final Guidance for Industry and FDA Staff Document issued on: January 11. p200. // OK // OK // OK REFERENCES 1. // OK }. } S_var. namespace N { static int c. } S_var. } static struct S { int a.2. Stroustroup C++ Programming Language 3rd Edition. } // OK class A { static void foo( ). // Violation // Violation // Violation // Violation REPAIR namespace{ static int glob.static int goo( ). } class B { public: static struct S { int a. void zoo( ) { static int c. }. 2. 9. static int b.

.

// Violation // Violation int test( ) { LocalClass lc.0 EXCEPTIONS Static inline functions and inline functions defined in anonymous namespace are permitted. EXAMPLE inline int foo( ) { return 10.i files.inline functions must be defined identically in every translation unit they are used. inline functions should be defined only in the header or . } }. BENEFITS Rule helps to prevent unpredictable behaviour of program.bar(). return foo() + lc.Do not define inline functions in source files [CODSTA-CPP-51-3] DESCRIPTION Do not define inline functions in source files . } . } class LocalClass { public: int bar( ) { return 20. SINCE v7. Therefore.

General Principles of Software Validation. 9. } // OK // OK int test( ) { LocalClass lc. Stroustroup C++ Programming Language 3rd Edition. } namespace { class LocalClass { public: int bar( ) { return 20. 2.2. return foo() + lc.REPAIR static inline int foo( ) { return 10.bar(). } REFERENCES 1. Final Guidance for Industry and FDA Staff Document issued on: January 11. p199. 2002 . } }.

. const Rational operator+(const Rational& lhs. there is never a need for the stand-alone operators to be friends of the class. and operator+ calls them to provide their own functionality. }. Furthermore. operator+=) and the stand-alone version (e. With this design.g. const Rational& rhs) { return Rational(lhs) += rhs. only the assignment version of these operator need to be maintained. operators += is implemented (elsewhere) from scratch." See also: OOP-11. For example:" class Rational { public: Rational& operator+=(const Rational& rhs).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. assuming the assignment versions of the operators are in the class's public interface.g. CODSTA-CPP-29 . operator+) exists is to implement the latter in terms of the former. } SINCE v7.0 BENEFITS "In this example..

A& b ){ return A( a ) *= b. } // Violation A operator-( A& a. // OK . // Violation A operator+( A& a.EXAMPLE class A { public: A operator+=( A& b ). } // OK REPAIR class A { public: A operator+=( A& b ). A operator*=( A& b ). }. return result -= b. friend A operator*( A& a. A& b ){ return A( a ) += b. } // OK A operator*( A& a. A operator+( A& a. A& b ). } // OK A operator-( A& a. A& b ){ return A( a ).removed friend declaration }. } // Violation A operator*( A& a. A operator-=( A& b ). A& b ){ return A( a ). A operator*=( A& b ). A& b ){ // OK . A operator-=( A& b ). A& b ){ A result( a ).

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

It also prevents future revisions from unintentional changing the caller's data.const is applied to the // pointed object.0 NOTES For parameters and variables of pointer type the const qualifier should be applied to the pointer.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. and it's integrated with C++'s type system. const int* param3) // Violation // Violation // Violation . track. Immutable values are easier to understand. and reason about. EXAMPLE int foo1(int param1. int* param2. MISRA2004-16_7 SINCE v7. BENEFITS It's safe. See also: CODSTA-CPP-43.param1 is modified . // Violation return param1 + *param2 + *param3 + var1. // OK . it's checked at compile time. } int foo2(int param1. not to the pointer { int var1 = 0. so prefer constants over variables whenever it is sensible and make const your default choice when you define a value. not to the pointed object.

} REFERENCES 1.const is applied to the pointed // object and to the pointer { const int var1 = 0.int* param2. Chapter 6. const int* const param3) // OK // OK . (C) 2005 Pearson Education. int* const param2.const is applied to the pointer // OK . return var1. Chapter: "Coding Style". Section 7. // OK . Herb Sutter. Rule 15 2. } REPAIR // Fixed violations . 2002 .param3 is modified { int var1 = 0. const int* param3) // OK . param2++. param3++.param2 is modified // OK . "C++ Coding Standards." AddisonWesley.const added int foo1(const int param1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.. General Principles of Software Validation.var1 is modified param1++. Inc. Final Guidance for Industry and FDA Staff Document issued on: January 11. // OK return param1 + *param2 + *param3 + var1. Rule 7-1-1 3. var1 = param1 + *param2 + *param3. Andrei Alexandrescu.

" See also: CODSTA-CPP-78 SINCE v7. you usually gain a better understanding of the ways in which that member function might modify an object's state." EXAMPLE class A { int foo(int a) { return a.Member functions shall be declared const whenever possible [CODSTA-CPP-54-3] DESCRIPTION "Const-correctness is worthwhile. Understanding how and where a program's state changes is vital. proven. } }. // Violation REPAIR class A { int foo(int a) const { // OK . effective. If you find it impossible to make a member function const.1 BENEFITS "Writing const appropriately helps you gain a better understanding of your design and makes your code sturdier and safer. and const documents that directly in code where the compiler can help to enforce it. and highly recommended.

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

class Sample { public: .1 NOTES Rule defines an interface as a public method. the Array class should be used. Instead. REPAIR class Array { /* Array implementation*/ }. EXAMPLE class Sample { public: void foo(int a[]). BENEFITS Arrays degenerate to pointers when passed as parameters. // Violation }.Arrays shall not be used in interfaces [CODSTA-CPP-55-2] DESCRIPTION Array parameters should not be used in public methods. This "array decay" problem has long been known to be a source of errors. SINCE v7.

C++ CODING STANDARDS Chapter 4.10 Classes.void goo(Array a). // OK }. REFERENCES JOINT STRIKE FIGHTER. AV Rule 97 . AIR VEHICLE.

structure. C++ CODING STANDARDS Chapter 4. or enumeration will not be declared in the definition of its type [CODSTACPP-56-3] DESCRIPTION A class.15 Declarations and Definitions. or enumeration will not be declared in the definition of its type.A class. down } direction. SINCE v7. EXAMPLE enum { up. // Violation REPAIR enum direction_e { up. structure. AV Rule 141 . AIR VEHICLE. // OK REFERENCES JOINT STRIKE FIGHTER. direction_e direction. down }.1 BENEFITS Rule improves readability.

.

SINCE v7.1 BENEFITS Simplicity and clarity. EXAMPLE namespace A { namespace B { namespace C { namespace D // Violation { } } } } REPAIR namespace A { namespace B { namespace C // OK { } namespace D // OK .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. Deeply nested namespaces can be difficult to comprehend and use correctly.

11 Namespaces. AIR VEHICLE.{ } } } REFERENCES JOINT STRIKE FIGHTER. AV Rule 99 . C++ CODING STANDARDS Chapter 4.

" SINCE v7.2 EXCEPTIONS "The return value of a function may be discarded by use of a (void) cast. 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 ).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. // Violation } REPAIR short func ( short para1 ) { . Overloaded operators are excluded. The return value of a function shall always be used.

Rule 0-1-7 . } 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.return para1.

g.h> <wchar.h> <errno.h> <stdarg." The following standard C library headers are detected: <assert. <cstdio>) also have corresponding C versions (e. EXAMPLE #include <stdio.h> <wctype.h> <signal. This rule requires that the C++ version is used.h> <limits.h> <stdio.The C library shall not be used [CODSTA-CPP-59-3] DESCRIPTION "Some C++ libraries (e.h> <locale.h>).h> SINCE v7.h> // Violation REPAIR .h> <ctype. <stdio.h> <setjmp.h> <string.h> <float.2 BENEFITS Rule prevents undefined and implementation-defined behaviour.h> <stddef.h> <math.h> <stdlib.h> <iso646.h> <time.g.

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

\x<Hexadecimal Number>" SINCE v7. \?. \\. \t. printf("abcd\hgf"). MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. \v. \b. \'. . The defined escape sequences (ISO/IEC 14882:2003) are: \n.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. printf("\k"). \a. \". \f. \r. Rule 2-13-1 2. \<Octal Number>. Section 2. } // Violation // Violation // Violation REPAIR Do not use escape sequences not defined in the ISO/IEC 14882:2003 standard. REFERENCES 1. EXAMPLE #include <stdio.h> void foo( ) { printf("ABCD\u1111"). General Principles of Software Validation.2 BENEFITS The use of an undefined escape sequence leads to undefined behaviour.

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

// OK // OK // OK .h extern int a1. If external linkage is not required.2 EXCEPTIONS This rule does not apply to main. BENEFITS Rule reduce the visibility of objects and functions. then the object or function shall either be declared in an unnamed namespace or declared static.h" int a1 = 0. extern void fun().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. EXAMPLE // file. // file. or to members of unnamed namespaces. void fun(){} // Violation // Violation REPAIR // file." SINCE v7.cpp #include "file.cpp int a1 = 0.

Rule 3-3-1 . Section 3.void fun(){} // OK REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

// OK } REFERENCES .NULL shall not be used as an integer value [CODSTA-CPP-62-3] DESCRIPTION "In C++. and 0 for the integer zero. // Violation } REPAIR void f1( int ). void foo( ) { f1( 0 ). NULL is considered to have pointer type. To meet developer expectations." SINCE v7. NULL should be used as the null-pointer-constant.2 BENEFITS "As a result of this rule." EXAMPLE #include <cstddef> void f1( int ). void foo( ) { f1( NULL ). the literal 0 is both an integer type and the null-pointerconstant.

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

and 0 for the integer zero.2 BENEFITS "As a result of this rule. // OK } . To meet developer expectations. void foo( ) { f1( 0 )." EXAMPLE #include <cstddef> void f1( int* ). NULL should be used as the null-pointer-constant. the literal 0 is both an integer type and the null-pointerconstant.Literal zero (0) shall not be used as the null-pointer-constant [CODSTA-CPP-63-3] DESCRIPTION "In C++. void foo( ) { f1( NULL )." SINCE v7. NULL is considered to have pointer type. // Violation } REPAIR #include <cstddef> void f1( int* ).

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

if (i){} // Violation } ." BENEFITS "The condition expression shall contain an explicit test (yielding a result of type bool) in order to clarify the intentions of the developer. then its result will be implicitly converted to bool. EXCEPTIONS "A condition of the form type-specifier-seq declarator is not required to have type bool." SINCE v7." EXAMPLE void foo() { int i.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.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.

REPAIR void foo() { int i. Section 5. Rule 5-0-13 . if (i != 0){} // OK } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

then its result will be implicitly converted to bool. // OK } REFERENCES 1. int j. int j.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. int k. Section 5. Rule 5-0-14 . // Violation } REPAIR void foo(int i. If an expression with type other than bool is used as the first operand of a conditional-operator. int l) { i = j ? k : l.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. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6." SINCE v7." EXAMPLE void foo(int i. int k. int l) { i = (j != 0) ? k : l.

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

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. and functional notation casts that do not invoke a converting constructor are capable of performing casts between unrelated types. class Derived : public Base { public: Derived( ). Derived *pD2 = (Derived *) pB. ~Derived( ). virtual ~Base( ). EXAMPLE class Base { public: Base( ). }. }.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)." SINCE v7. void foo( ) { Base *pB. // Violation .

~Derived( ). }.} REPAIR class Base { public: Base( ). virtual ~Base( ). void foo( ) { Base *pB. }. Rule 5-2-4 . class Derived : public Base { public: Derived( ). Derived *pD1 = dynamic_cast<Derived*>( pB ). Section 5. } // OK REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

int d.Each operand of the ! operator. | and ~). This rule allows the detection of such uses. 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 */ . BENEFITS Rule improves readability and maintainability. 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)." SINCE v7. || and !) can be easily confused with the bitwise operators (&. int c. Rule prevents confusion between logical and bitwise operators. which often occur because the logical operators (&&.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. int b. EXAMPLE /* examples of incorrect code */ void foo(int a.

int b. Section 5. Rule 5-3-1 . 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.void foo(int a. int c.

// 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.2 BENEFITS Rule prevents undefined behaviour. Rule 5-3-3 . }. Section 5. EXAMPLE class A { public: A * operator & ( ).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.

condition or expression.an operand to a relational operator in condition. x = y++){} // Violation } REPAIR void foo3() { . int y. then a while loop is more appropriate. for (x = 0.modified in expression. If this is the desired behaviour.2 NOTES A loop-counter is a loop-control-variable that is: . x < y.Initialized in.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. and . y = 0. for-init-statement. and . EXAMPLE void foo() { int x = 0. A loop-control-variable is any variable occurring in for-init-statement. or prior to." SINCE v7. BENEFITS Rule helps to ensure deterministic loop termination.

} } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. y = 0. while(x < y) // OK { x = y++. Section 6. x = 0. int y.int x = 0. Rule 6-5-1 .

or ++." SINCE v7. .If loop-counter is not modified by -. then == and != shall not be used. for ( i = 1. which may be inconsistent with developer expectations. and . > or >= [CODSTA-CPP-70-3] DESCRIPTION "When the loop-counter is modified using an operator other than -. i != 10. condition or expression. within condition. the loop-counter shall only be used as an operand to <=. then. or prior to.or ++. i += 2 ){} // Violation } REPAIR void foo() { int i.modified in expression. as loop termination may not occur.2 NOTES A loop-counter is a loop-control-variable that is: .an operand to a relational operator in condition. EXAMPLE void foo() { int i.Initialized in. and . BENEFITS Rule helps to ensure deterministic loop termination. A loop-control-variable is any variable occurring in for-init-statement. for-init-statement. <.

i != 10. i <= 10. ++i ){} // OK } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.for ( i = 1. Section 6. i += 2 ){} // OK for ( i = 1. Rule 6-5-2 .

and . BENEFITS Rule helps to ensure deterministic loop termination. EXAMPLE void foo() { int x. for ( x = 0.The loop-counter shall be modified by one of: --.Initialized in. and . -=n.2 NOTES A loop-counter is a loop-control-variable that is: .an operand to a relational operator in condition. or prior to. where n remains constant for the duration of the loop [CODSTA-CPP-71-3] DESCRIPTION "The loop-counter shall be modified by one of: --. A loop-control-variable is any variable occurring in for-init-statement. x < 10. ++. -=n. where n remains constant for the duration of the loop" SINCE v7. ++. ++x ){} // OK . x = x + 1 ){} // Violation } REPAIR void foo() { int x.modified in expression. for ( x = 0. or +=n. x < 10. for-init-statement. or +=n. condition or expression.

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

A loop-counter is a loop-control-variable that is: . A loop-control-variable is any variable occurring in for-init-statement.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. for-init-statement. condition or expression.Initialized in. or prior to. and . flag = test(++x) ) {} } // Violation . BENEFITS Rule improves readability of code. EXAMPLE bool test(int x).an operand to a relational operator in condition.modified in expression. loop-control-variables are either the loop-counter. and ." SINCE v7. x < 10. void foo(int x. or flags used for early loop termination.2 NOTES The rule assumes that variable or parameter might be modified by passing its non-const pointer or reference to an external function. bool flag) { for ( x = 0. The code is easier to understand if these are not modified within condition or expression.

bool flag) { for ( x = 0. Section 6. x < 10.REPAIR bool test(int x). } } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. void foo(int x. Rule 6-5-5 . ++x ) // OK { flag = test(x).

2 NOTES The rule assumes that variable or parameter might be modified by passing its non-const pointer or reference to an external function. and .an operand to a relational operator in condition. condition or expression. BENEFITS Rule improves readability of code.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.modified in expression. unsigned int u8a. ( x < 10 ) && ( u8a != 3U ). ++x ) { u8a = 5. loop-control-variables are typically used to terminate a for loop early. A loop-control-variable is any variable occurring in for-init-statement. for-init-statement. bool flag) { for ( x = 0. // Violation } } . A loop-counter is a loop-control-variable that is: . and .Initialized in. EXAMPLE void foo(int x. or prior to. The code is easier to understand if this is done with the use of Boolean values" SINCE v7.

} } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. unsigned int u8a. bool flag) { for ( x = 0. Section 6. // OK flag = u8a != 3U. ( x < 10 ) && flag. Rule 6-5-6 .REPAIR void foo(int x. ++x ) { u8a = 5.

Rule 7-3-3 2. } REPAIR Do not define unnamed namespaces in header files REFERENCES 1. Section 7. Final Guidance for Industry and FDA Staff Document issued on: January 11. General Principles of Software Validation." SINCE v7. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.hpp namespace // Violation { extern int x. which may not be consistent with developer expectations. Any declarations appearing in an unnamed namespace in a header will refer to different entities in each translation unit.There shall be no unnamed namespaces in header files [CODSTA-CPP-74-3] DESCRIPTION "An unnamed namespace will be unique within each translation unit. EXAMPLE // file.2 BENEFITS Rule improves readability of code. 2002 .

.

} using namespace NS1. namespace NS1 { int32_t i1. // Violation void f () { ++j1.2 BENEFITS Rule improves readability of code. int32_t k1.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. int32_t j1. using-declarations or fully qualified names restricts the set of names considered to only the name explicitly specified. EXAMPLE typedef int int32_t. and so are safer options. } . All identifiers in these scopes become visible. increasing the possibility that the identifier found by the compiler does not meet developer expectations." SINCE v7.

Section 7. int32_t k1. } using NS1::j1. int32_t j1. // OK void f () { ++j1.REPAIR typedef int int32_t. Rule 7-3-4 . namespace NS1 { int32_t i1. } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

} // Violation .2 BENEFITS Rule prevents unexpected behaviour. } using NS::foo." SINCE v7. namespace NS { void foo( unsigned int ). EXAMPLE namespace NS { void foo( unsigned short ). which may not be consistent with developer expectations. } void some() { foo( 0U ). Any subsequent declarations will not be found through the usingdeclaration.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.

Section 7. } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. Rule 7-3-5 .REPAIR namespace NS { void foo( unsigned short ). void some() { foo( 0U ). } namespace NS { void foo( unsigned int ). } // OK using NS::foo.

OOP-12. However. The common expectation of const member functions is that the state of the object may not be modified when invoking the functions. Helps const functions act const. so they won't uncontrollably modify the state of the object.pointer to member variable/member function . returning a non-const pointer or reference to classdata from a const function allows a modification to the conceptual state of an object.reference to member variable/member function . OOP-36 NOTES Handle to class-data is: . BENEFITS Rule prevents exposing internal state of the object to clients.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. Enforces data encapsulation that is a cornerstone of Object Oriented programming. EXAMPLE class Test { public: Test(int & p) : _i(p) . only const member functions can be invoked on that object." See also: CODSTA-CPP-06. Improves code maintainability.pointer/reference to data allocated in constructor or deallocated in destructor Static variables are not considered class-data.

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

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

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

EXAMPLE class A { public: int foo1 () { return m_s.If a member function can be made static then it shall be made static. } int foo2 () { return m_i. }.can be const . static int m_s. 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. } private: int m_i. REPAIR class A { // Violation .can be static // Violation .2 BENEFITS Rule prevents unintentional modification of the data." See also: CODSTA-CPP-54 SINCE v7.

General Principles of Software Validation. Rule 9-3-3 2. } int foo2 () const { return m_i. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. } // OK // OK private: int m_i. 2002 . Final Guidance for Industry and FDA Staff Document issued on: January 11. REFERENCES 1.public: static int foo1 () { return m_s. }. Section 9. static int m_s.

// OK } REFERENCES Motorola Coding Standards R-46 . BENEFITS Array elements shall be accessed by the array operator [] rather than the dereference operator '*'. array[1] = 0.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 []. *(array+1) = 0. Access to array by the dereference operator '*' is cryptic and hides the real intention. // Violation *array = 0. // Violation } REPAIR void foo() { int array[2]. EXAMPLE void foo() { int array[2].

many popular compilers generate inefficient code for reading and writing bit members. REPAIR Do not declare bitfield. int iVar. It will report a message when a bitfield is declared. EXAMPLE struct A { int iVarBitField : 8. but must instead load and store whole words. 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. The ordering of bits in memory varies from compiler to compiler.Do not declare member variables as bit-fields [CODSTA-02-5] DESCRIPTION This rule is purely informational. In addition. REFERENCES Recommended by Parasoft // Violation . }. BENEFITS Prevents error prone code.

The preprocessor performs a textual substitution for macros in the source code which is then compiled.chris-lott. never using #define. incorrectly written. Prevents incorrectly macro writing. Scott Meyers. Inc. this expression may be evaluated differently for different instantiations. macros are. (C) 2005 Pearson Education. the name of the constant is not recognized in many debuggers.Do not define constants via #define [CODSTA-03-3] DESCRIPTION "Constants are to be defined using const or enum. CODSTA-38.. Addison-Wesley. Ellemtel Coding Standards http://www. Chapter 1. CODSTA-40 BENEFITS Code is easier to debug.Rule 36 . For example. This has a number of negative consequences. at times. In addition. Item 2 2. EXAMPLE #define PI 3." See also: MISRA2004-19_7.org/resources/cstyle/Ellemtel-rules-mm.1416. if a constant has been defined using #define. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". If the constant is represented by an expression.html From: 10 Constants . depending on the scope of the name. CODSTA-37. Third Edition. // OK REFERENCES 1.1416 // Violation REPAIR const float PI = 3. CODSTA-39.

6 Pre-Processing Directives. C++ CODING STANDARDS Chapter 4.2. AIR VEHICLE. AV Rule 30 . JOINT STRIKE FIGHTER.

EXAMPLE void Foo() { int static iVar = 9. } REFERENCES Recommended by ParaSoft . // Violation return. BENEFITS Makes code more readable. return. } REPAIR int iVar = 9.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. // OK void Foo() { iVar++.

declare a class that has a member variable of the pointer type. the probability of failure is reduced." BENEFITS Rule improves the readability of the code and encourages data abstraction.html#12 From: 12 Pointers and References . By improving the readability of code. Another example is the second argument to the main function. Ellemtel Coding Standards http://www. // Violation } REPAIR Instead." EXCEPTIONS "One exception to this rule is represented by functions which provide interfaces to other languages (such as C). in which case pointers to pointers are needed. "Pointers to pointers should whenever possible be avoided. which must have the type char*[]. EXAMPLE void foo() { int** a.Pointers to pointers should be avoided whenever possible [CODSTA-05-3] DESCRIPTION This rule detects if code uses pointers to pointers. 48 .Rec.org/resources/cstyle/Ellemtel-rules-mm.chris-lott. These are likely to only allow pre-defined data types to be used as arguments in the interface. REFERENCES 1.

4. ISO/DIS 26262 point 8. AIR VEHICLE.4 . AV Rule 169 3. JOINT STRIKE FIGHTER.22 Pointers & References. C++ CODING STANDARDS Chapter 4.2.

// Violation }. REPAIR int main( ) { if (1) return 1. EXAMPLE int main( ) { return (1 ? 1 : 0). The '?:' operator is difficult to read and leads to code obfuscation.Avoid using the '?:' operator [CODSTA-06-3] DESCRIPTION This rule detects if you use the '?:' operator. BENEFITS Readability. }. // OK REFERENCES Recommended by ParaSoft . else return 0.

Maintaining this consistency of declarations results in easier code readability. typedef void TD_void. void f1(void). // Violation REPAIR typedef void (*fpt)(). BENEFITS The rule improves readability of code. // Violation void (*fp1)(void). typedef void TD_void. void f1(){ } // OK // OK TD_void foo2(). EXAMPLE typedef void (*fpt)(void). use ( ) instead of ( void ) [CODSTA-07-3] DESCRIPTION This rule detects if you use (void) instead of () if a function has no parameters.If a function has no parameters. void f1(). NOTES The rule is enabled only for C++ language. // OK // OK . void f1(void){ } // Violation // Violation // Violation void foo2(TD_void).

void (*fp1)(). // OK REFERENCES Recommended by ParaSoft .

j++) { if (j==5) { break.Do not use break in for loops [CODSTA-08-2] DESCRIPTION This rule checks if there are breaks in for loops. BENEFITS Avoiding breaks in the for loop makes your code easier to follow. j < 10. // OK . // Violation } break. // Violation } } REPAIR void func() { for (int j = 0. j++) { while (true) { break. Breaks which are in direct context of do/while. while and switch are skipped. EXAMPLE void func() { for (int j = 0. j < 10.'break' in while context } } } REFERENCES Recommended by ParaSoft .

.

Using a pointer cast in this manner can cause problems. return.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. REFERENCES 1. } // Violation REPAIR Remove all function pointer to primitive type pointer casts. BENEFITS Casting pointer to function to pointer to primitive type can make code error prone. } void f() { void *ptrV = 0.4 . void (*funPtr) (char*) = 0. return.4. funPtr = &Foo. ISO/DIS 26262 point 8. EXAMPLE void Foo(char *ptrC) { *ptrC = 0. ptrV = (void*)funPtr.

.

not the variable. BENEFITS Improves the readability of code. // Violation REPAIR static char j. not the variable or the function [CODSTA-10-3] DESCRIPTION This rule checks whether storage type modifiers are associated with the type. EXAMPLE int static i.Storage type modifiers shall be associated with the type. // OK REFERENCES Motorola Coding Standards R-1 .

Andrei Alexandrescu. Herb Sutter. assert( i++ != 0 ). Never write expressions with side effects in assert statement. (C) 2005 Pearson Education. // Violation } REPAIR #include <assert. "C++ Coding Standards. Avoid assert(false) and prefer assert(!"informational message"). . // Violation assert(i=5). EXAMPLE #include <assert." AddisonWesley. "Use assert or an equivalent liberally to document assumptions internal to a module.h> void foo( ) { int i = 0.h> void foo( ) { int i = 0. Most compilers will helpfully emit the string in their error output. Inc." BENEFITS Rule improves efficiency and prevents error-prone code. // OK } REFERENCES 1. // Violation assert(false). // OK assert(!"informational message"). assert(i != 0).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.

AIR VEHICLE. General Principles of Software Validation. Final Guidance for Industry and FDA Staff Document issued on: January 11. 2002 .Chapter: "Error Handling and Exceptions".25 Expressions & References. AV Rule 204 3. C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER. Rule 68 2.

html#18. EXAMPLE void foo() { int c = 8 << 2.org/resources/cstyle/Ellemtel-rules-mm. "Avoid using shift operations instead of arithmetic operations.chris-lott.18.Port. 17 . REFERENCES Ellemtel Coding Standards http://www. Rec.8 Pointer Arithmetic ." BENEFITS Rule improves readability and maintainability and prevents confusion.8 From: 18 Portable Code .Avoid using shift operations instead of arithmetic operations [CODSTA-12-3] DESCRIPTION This rule detects code that uses shift operations instead of arithmetic operations. } // Violation REPAIR Avoid using shift operations.

ISO/DIS 26262 point 8.g.html#18.4 . Ellemtel Coding Standards http://www. "Avoid pointer arithmetic. Pointer arithmetic can be portable. REFERENCES 1. in comparison). while the use of the operators <. char* b. 18 2.org/resources/cstyle/Ellemtel-rules-mm. Rec.4. >. <=.18. >= are portable only if they are used between pointers which point into the same array.chris-lott.Port.8 Pointer Arithmetic . if (a == b) {}// Violation if (returnptr( ) >= b) {}// Violation if (b < returnptr( )) {}// Violation } REPAIR Do not use pointer arithmetic. The operators == and != are defined for all pointers of the same type..8 From: 18 Portable Code ." BENEFITS Prevents confusion of types (e.Avoid pointer arithmetic [CODSTA-13-3] DESCRIPTION This rule detects code that uses pointer arithmetic. void foo() { int* a. EXAMPLE int* returnptr().

.

chris-lott. EXAMPLE void foo( const int a. // Violation *y = 10. REFERENCES 1. Ellemtel Coding Standards http://www. const int* b ) { int x.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. The rule detects casts that remove a const qualification from the type addressed by a pointer or reference. int* y. "C++ Coding Standards. BENEFITS The rule prevents undefined behaviours.org/resources/cstyle/Ellemtel-rules-mm. Andrei Alexandrescu. // Violation y = (int*) b. (int&) a = x. Herb Sutter." Addison- . Besides it detects an implicit cast from a string literal to char*.Rule 46 2.html From: 13 Type Conversions . 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. } REPAIR Avoid casting away const.

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

BENEFITS Prevents potential loss of data. EXAMPLE void foo2(int ii[30]) // Violation { } void foo3(char a. Do not declare the magnitude of a single dimensional array in the argument declaration.In fact.int ii[][30][30]) { } REFERENCES Motorola Coding Standards R-7 // OK // OK . different invocations of the function may pass array arguments with different magnitudes. The 'C' language will pass an array argument as a pointer to the first element in the array.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. specifying the magnitude of an array in a function argument definition might complicate software maintenance.int ii[30][30][30]) // Violation { } REPAIR void foo1(int ii[]) { } void foo4(char a. Therefore.

.

// Violation REPAIR int tab2[]={1. changes to the number of elements in the initialization list do not require corresponding changes to the explicit array size. R-6 .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. EXAMPLE #define SIZE 4 int tab1[SIZE] = {1.2. // OK REFERENCES Motorola Coding Standards. When global arrays are initialized in the definition.3}.3}. BENEFITS Makes code easier to maintain. By allowing the magnitude of an array to be set automatically during definition. their magnitude shall be set by initialization.2.

// OK } REFERENCES 1. AIR VEHICLE. problems may arise.h> void foo( ) { int *lp = 0.Do not compare a pointer to NULL or assign NULL to a pointer. C++ CODING STANDARDS Chapter 4." BENEFITS According to the ANSI-C standard. NULL is defined either as (void*)0 or as 0. "Do not compare a pointer to NULL or assign NULL to a pointer.Rule 42 2.org/resources/cstyle/Ellemtel-rules-mm.chris-lott. use 0 instead. // Violation } REPAIR #include <stddef. EXAMPLE #include <stddef. AV Rule 175 . it cannot be assigned an arbitrary pointer without an explicit type conversion. If NULL is defined to have the type void*.html From: 12 Pointers and References .22 Pointers & References.h> void foo( ) { int *lp = NULL. JOINT STRIKE FIGHTER. use 0 instead [CODSTA-17-3] DESCRIPTION This rule detects code that compares a pointer to NULL or assigns NULL to a pointer. Ellemtel Coding Standards http://www. If this definition remains in ANSI-C++.

.

EXAMPLE void func( ) { int i = 0. } REPAIR void func( ) { int i = 0. do // Violation { i++. } } // OK REFERENCES Recommended by ParaSoft .Prefer while statements over do statements [CODSTA-18-5] DESCRIPTION This rule checks that code prefers "while" statements over "do" statements. while (i < 10) { i++. Using while statements instead of do statements can make code clearer and help prevent errors. BENEFITS Using do statements can lead to errors and confusion. } while ( i < 10).

.

The ctype.h facilities for character tests and upper-lower conversions (isalnum. ispunct. and promote international flexibility. isprint.h> void test(char c) { if(islower(c)) { } while(isupper(c)) { } } // OK // OK .h facilities for character test [CODSTA-19-3] DESCRIPTION This rule checks that code uses the ctype.h> void test(char c) { if( 'a' <= c && c <= 'z') { } // Violation while( 'A' <= c && c <= 'Z') {// Violation } } REPAIR #include <ctype. isupper. _toupper. BENEFITS Using function from ctype. other similarly named functions (such as _tolower. islower. EXAMPLE #include <ctype. tolower. iscntrl. isdigit. isspace. _isascii) are not universally portable.h facilities for character test. However. are usually very efficient. toupper) are portable across different character code sets.Use the ctype. isgraph. isxdigit.h for char testing makes code more portable across different character code sets. isalpha.

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

".h> #define EOS '\0' void foo( ) { char str[30] = "Sample text. EOS should be used to terminate a string rather than NULL. EXAMPLE #include <stddef. } REFERENCES Motorola Coding Standards G-11 // OK .".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. BENEFITS Promotes the use of defined constants rather than hard coded values. since NULL is not guaranteed to be defined as zero.h> #define EOS '\0' void foo( ) { char str[30] = "Sample text. str[7] = NULL. } // Violation REPAIR #include <stddef. str[7] = EOS.

EXAMPLE enum my_enum1 { a. the values of each member should be explicitly declared. logic analyzer or other debugging device.When using enum. REPAIR enum my_enum2 { a = 0 // OK }. BENEFITS Explicit declarations of each member’s values is valuable documentation when using an emulator. // Violation }. REFERENCES Motorola Coding Standards G-15 . the values of each member should be explicitly declared [CODSTA-21-5] DESCRIPTION When using enum.

short foo2( ) { for( int _var2 = 0. } public: int Member. return _var1. short Var3. }.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. _var2++ ) { } return Var3. NOTES Case insensitive check is performed. Names that are one character in length are skipped. // Violation } int foo1( ). int Base::foo1( ) { int _var1 = 6. float Var2. } // Violation // Violation . float Var1. BENEFITS Rule improves readability and prevents writing ambiguous code. _var2 < 10. EXAMPLE class Base { void foo( ) { float memberF.

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

return iValue. int x. } }.class A : public Base { void foo( ) { float fLocal. } REFERENCES Recommended by ParaSoft // OK // OK . int A::foo1( ) { int iValue = 6. short foo2( ) { int y. // OK } int foo1( ). // OK for( int iValue = 0. iValue < 10. iValue++ ) { } return Var3.

} if(a < b){ return b . } // Violation if(a == b) return 1.a.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. int b) { if(a > b){ // OK return a .a. EXAMPLE int foo(int a. int b) { if(a > b){ // Violation return a . } else if(a < b){ // OK return b . } } . // Violation } REPAIR int foo(int a.b. } else { return 1.b.

REFERENCES 1. Recommended by ParaSoft .

att.other than defining FALSE as 0-.com/~bs/glossary.html#Gfalse . #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-.If FALSE is to be defined.is misleading and will not be guaranteed to work predictably.research. and is not already defined. EXAMPLE #define FALSE 1 // Violation #undef FALSE #define FALSE // Violation REPAIR #define FALSE 0 // OK REFERENCES http://www.

#endif // Violation REPAIR #ifndef FALSE typedef enum { TRUE = 1.com/~bs/glossary.research. See also: CODSTA-24. EXAMPLE #ifndef FALSE typedef enum { TRUE = 1. CODSTA-43 BENEFITS Any use of FALSE-.is misleading and will not be guaranteed to work predictably. FALSE = -1 } BOOL . enum value FALSE should be 0 [CODSTA-25-5] DESCRIPTION This rule checks if FALSE is defined as 0.If FALSE is to be defined. and is not already defined. FALSE = 0 } BOOL .html#Gfalse .att.other than defining FALSE as 0-. #endif // OK REFERENCES http://www.

// Violation } REPAIR const int MAX = 8. float b ) { int e. // Violation e= 8. // Violation boo(56). We also skip usage of 0 or 1 because they are equivalent of true or false. int foo( int a[]. EXAMPLE void boo(int). int b ) { int e.Avoid magic numbers [CODSTA-26-3] DESCRIPTION Avoid spelling literal constants in code. // OK void boo(int). See also: CODSTA-29 NOTES We excluded using literal constants in initialization. int foo( float a[]. int f = 0. // OK int i = 5. They are not self-explanatory. // OK . a[5] = 56. // Violation return 8. int f = 0. BENEFITS Rule improves readability and maintainability. Use symbolic values instead.

(C) 2005 Pearson Education. Andrei Alexandrescu. e = MAX. boo(a[5]). Rule 17 2. // // // // OK OK OK OK } REFERENCES 1. Herb Sutter. Inc.a[i] = MAX. return MAX. AIR VEHICLE. Chapter: "Coding Style". JOINT STRIKE FIGHTER. "C++ Coding Standards. AV Rule 151 ." AddisonWesley.18 Constants. C++ CODING STANDARDS Chapter 4.

uiuc. EXAMPLE struct S { int a. or .a global variable.a member variable of global object.edu/manuals/html/tcharm/2_1. void foo(){ g_i++.html . or . int g_arr[10].an element of global array BENEFITS In multithread environment using global variables makes code extremely error prone.a = 10. g_struct. g_arr[3] += 2. }g_struct. REFERENCES http://charm. } // Violation // Violation // Violation REPAIR Do not modify global variables.cs. int g_i.Avoid functions that modify global variables [CODSTA-27-3] DESCRIPTION The rule reports a violation if in function is modified: .

// Violation REPAIR union KNOWN// OK { int a. EXAMPLE union UNKNOWN { }. REFERENCES Recommended by ParaSoft . BENEFITS Prevents form incomplete code. }.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.

*/ } } REPAIR #define buff 256 #define OK 1 enum color { RED = 0.*/ }.. // Violation // Violation . Using #define or enum constants rather than hard coded values promotes the maintainability of 'C' code by creating a localized area for changes. BLUE = 1. EXAMPLE void foo( ) { int tabColors[256].. GREEN = 2 /*. See also: CODSTA-26 NOTES Rule active for C code only."#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. BENEFITS Readability and maintainability. if (tabColors[2] == 1) { /*...

org/resources/cstyle/Ellemtel-rules-mm..chris-lott.. // OK if (tabColors[RED] == OK) { // OK /*.*/ } } REFERENCES Ellemtel Coding Standards http://www.void foo( ) { int tabColors[buff].html From: 10 Constants .Rule 37 .

} // OK REFERENCES Recommended by ParaSoft .Avoid returning handles to function parameters [CODSTA-30-3] DESCRIPTION A function must never return a pointer or reference to a parameter. // Violation } int& foo2( int x ){ return x. EXAMPLE int* foo1( int x ){ return &x. the memory to which it refers will already have been deallocated. BENEFITS Rule prevents non-deterministic behaviour. it could make your code non-deterministic. The compiler may or may not give a warning for this. // Violation } REPAIR int foo1( int x ){ return x. when this reference or pointer is used. } // OK int foo2( int x ){ return x. If a function returns a reference or a pointer to a parameter.

EXCEPTIONS Explicit type conversions may be used to convert a pointer to a base class to a pointer of a derived class. EXAMPLE void foo( ) { const int ci = 0. explicit type conversions are needed for reading an external representation of an object. Generally." NOTES Rule is limited to primitive types only.Never use explicit type conversions (casts) [CODSTA-31-3] DESCRIPTION "Never use explicit type conversions (casts). Explicit type conversion must be used to convert an anonymous bit-stream to an object. i = (int) ci. // Violation } REPAIR Do not use casts. // Violation i = (int) &i. BENEFITS Rule improves clarity and maintainability of code. REFERENCES . int i.

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

EXAMPLE void foo( ) { int* ptr. 55 .Rec.chris-lott. if (ptr) { // Violation } if (!ptr) { // Violation } } REPAIR void foo( ) { int* ptr. if (ptr == 0) { // OK } } REFERENCES Origin: Ellemtel Coding Standards http://www. The only reason is readability...org/resources/cstyle/Ellemtel-rules-mm.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. many programmers find it difficult to read such code.html From: 14 Flow Control Structures .) We do not recommend logical tests such as if(pointer) if pointer is a variable of pointer-type.(." BENEFITS Rule improves readability of code.

.

while or switch can make code difficult-to-read and error-prone. or switch [CODSTA-33-3] DESCRIPTION Using the operator ++ or -. } // Violation .&& iVar<10) { iVar += 10. while.in the conditional part of if. EXAMPLE int Foo (int iVar) { if (iVar-. } return iVar. } REPAIR int Foo (int iVar) { if (iVar<10) // OK { iVar += 10.in the conditional expression of if. BENEFITS Makes code more readable. } else { iVar -= 10. } else { iVar -= 10. } return iVar.Do not use operator ++ or -.

REFERENCES Recommended by ParaSoft .

JOINT STRIKE FIGHTER. the resulting code can be almost unreadable. this is avoided. Ellemtel Coding Standards http://www. If pointers to functions are used.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.Rec." EXAMPLE void (*p)()." BENEFITS "Another reason to use typedef is that the readability of the code is improved.22 Pointers & References. AV Rule 176 . 49 2. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. // OK REFERENCES 1.org/resources/cstyle/Ellemtel-rules-mm.html From: 12 Pointers and References . // Violation REPAIR typedef void (*PTF)(). By making a type declaration for the function type.chris-lott. PTF p.

break. . switch ( tag ) {// OK case 0: { break. then default can be used for error checking. } } } REPAIR void foo( ) { int tag.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. switch ( tag ) {// Violation case 0: { break. See also: MISRA2004-15_3 BENEFITS Rule prevents possibility of erroneous code. If all desired cases are handled outside of default. } case 1: { foo( ). EXAMPLE void foo( ) { int tag. } case 1: { foo( ).

} default: break. C++ CODING STANDARDS Chapter 4. AIR VEHICLE.Rule 48 2. AV Rule 194 .org/resources/cstyle/Ellemtel-rules-mm. } } REFERENCES 1. Ellemtel Coding Standards http://www.break.chris-lott.html From: 14 Flow Control Structures .24 Flow Control Structures. JOINT STRIKE FIGHTER.

} int Bar(int &i. } // OK // OK REFERENCES 1. int j) { j += i. int j) { j += i. . } int Bar(int i. BENEFITS Passing arguments of built-in types by value improves the efficiency of your code.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. EXAMPLE int Foo(int i. int j) { return i + j. return j. } // Violation // Violation REPAIR int Foo(int i. unless they should be modified by functions." AddisonWesley. Herb Sutter. Andrei Alexandrescu. int &j) { return i + j. "C++ Coding Standards. return j.

JOINT STRIKE FIGHTER.13 Functions (Value. Chapter: "Take Parameters Appropriately by Value. Pointer or Reference). C++ CODING STANDARDS Chapter 4. or Reference". AIR VEHICLE. Rule 25 2. AV Rule 116 .(C) 2005 Pearson Education. Inc. (Smart) Pointer.

CODSTA-38 NOTES Rule skips #defines which are used only in #ifs and #elifs conditions. Third Edition. Using a #define prevents the compiler from checking the type . EXAMPLE #define V1 20 #define V2 1 #if V2 #endif // Violation // OK REPAIR const int V1 = 20. Addison-Wesley. you prevent the compiler from disabling type checking. // OK #define V2 1 // OK #if V2 #endif REFERENCES Scott Meyers. CODSTA-03. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". . It means that each source and header files are parsed one by one. Rule works only within file scope. BENEFITS By following this rule. See also: MISRA2004-19_7.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.

Inc. Item 2 ..(C) 2005 Pearson Education. Chapter 1.

"Effective C++: 55 Specific Ways to Improve Your Programs and Design". // OK REFERENCES Scott Meyers.. you prevent the compiler from disabling type checking. Using a #define prevents using unchecked types. See also: MISRA2004-19_7. const int MACHINE_NAME_LEN = MAX_COMPUTERNAME_LENGTH + 2. (C) 2005 Pearson Education. Third Edition. Addison-Wesley.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. Inc. Chapter 1. CODSTA-03. CODSTA-37 BENEFITS By following this rule. EXAMPLE #define MAX_COMPUTERNAME_LENGTH 10 #define MACHINE_NAME_LEN MAX_COMPUTERNAME_LENGTH + 2 // Violation REPAIR const int MAX_COMPUTERNAME_LENGTH = 10. Item 2 .

BENEFITS Avoid unpredictable program behavior.// Violation friend = 0.// Violation class = 0.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.// Violation typename = 0.// Violation const_cast = 0.// Violation template = 0. and they can lead to unpredictable program behavior.// Violation public = 0.// Violation export = 0.// Violation typeid = 0.// Violation explicit = 0.// Violation protected = 0.// Violation false = 0.// Violation . 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 private = 0.// Violation true = 0.// Violation try = 0.// Violation dynamic_cast = 0.// Violation namespace = 0.// Violation new = 0.// Violation mutable = 0.// Violation reinterpret_cast = 0.// Violation delete = 0. Most C compilers do not detect naming conflicts.// Violation throw = 0.// Violation this = 0.// Violation catch = 0.// Violation operator = 0.// Violation static_cast = 0.

int using = 0.// Violation REPAIR // Avoid using reserved word as variable name REFERENCES Recommended by ParaSoft .// Violation int virtual = 0.// Violation int wchar_t = 0.

See also: MISRA2004-8_2_a.a function is declared or defined with an empty parameter list or . This will conflict with semantics of function implementation.there is no 'void' in return type */ foo3(void) {return. 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. /* Violation . /* OK */ . The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters. */ void foo1() {} */ /* Violation . Explicitly specifying parameter and return types as void clearly conveys the function intent.'void' should be used when a function is passed or returns no values [CODSTA-40-3] DESCRIPTION In many compiler implementations. EXAMPLE void foo1().there is no 'void' in return type */ foo2(void) {} /* Violation .there is no 'void' in parameter list /* Violation .there is no 'void' in return type */ REPAIR void foo1(void). MISRA2004-16_5 BENEFITS Rule improves readability and maintainability of code. functions which do not declare return type are automatically assigned int return type.} /* Violation . The rule reports a violation if: .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.there is no 'void' in parameter list foo2(void).

the 'return' statement with a value in function */ REFERENCES 1.} /* OK . Origin: Misra Guidelines .void foo1(void) {} /* OK */ void foo3(void) {return. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.Rule 76 .} /* OK */ foo4(void){ return 0. Section 16 2.

} } REFERENCES // OK . EXAMPLE void foo (int i) { switch(i) { case 0: break.. } else { // . default: break. Such a switch statement can be described using an if statement... See also: CODSTA-54. } } // Violation REPAIR void foo (int i) { if(i == 0) { // . MISRA2004-15_5 BENEFITS Avoids improper use of switch..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.

Recommended by ParaSoft .

and is not already defined. Any other use of TRUE is misleading and cannot be guaranteed to work predictably. #define TRUE should be 1 [CODSTA-42-5] DESCRIPTION This rule checks whether preprocessor definition of TRUE is 1.research.att. EXAMPLE #define TRUE 0 // Violation #undef TRUE #define TRUE // Violation #undef TRUE REPAIR #define TRUE 1 // OK REFERENCES http://www.html#Gtrue . See also: CODSTA-43 BENEFITS Readability and maintainability.If TRUE is to be defined.com/~bs/glossary.

Any other use of TRUE is misleading and cannot be guaranteed to work predictably.att.com/~bs/glossary. #endif // Violation REPAIR #ifndef TRUE typedef enum { FALSE = 0. enum value TRUE should be 1 [CODSTA43-5] DESCRIPTION This rule checks whether you defined const enum TRUE as 1. CODSTA-25 BENEFITS Readability and maintainability. #endif // OK REFERENCES http://www.html#Gtrue .research. TRUE = 1 } BOOL . See also: CODSTA-42. and is not already defined. EXAMPLE #ifndef TRUE typedef enum { FALSE = 0. TRUE = 3 } BOOL .If TRUE is to be defined.

var2 < 10. See also: CODSTA-45 BENEFITS Rule improves readability and prevents writing ambiguous code. float var1. then it reports violation message. }. var2++ ) { } return var3. If so. EXAMPLE class Base { public: int member. class A : public Base { void foo( ) { float member. // Violation . short var3. } int foo1( ).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). float var2. } // Violation // Violation }. } short foo2( ) { for( int var2 = 0. void foo( ) { float member.

var4 < 10. short var3. }. class A : public Base { void foo( ) { float member2. void foo( ) { float member2. var4++ ) { } return var3. float var2. float var1. REFERENCES Recommended by ParaSoft // OK . } short foo2( ) { for( int var4 = 0.REPAIR class Base { public: int member. } int foo1( ). } // OK // OK }.

If so. See also: CODSTA-44 BENEFITS Rule improves readability and prevents writing ambiguous code. short var3. // OK . void foo( double var4 ) { float member. float var1. short var3. } // Violation }. float var1. float var2. EXAMPLE class Base { public: int member. REPAIR class Base { public: int member. float var2. } }. void foo( double var3 ) { float member. then it reports violation message.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).

REFERENCES Recommended by ParaSoft .

} } REFERENCES Motorola Coding Standards G-13 . EXAMPLE void foo( int *j) { if(j!=0){ // Violation (*j)++.Use positive logic rather than negative logic whenever practical [CODSTA-46-5] DESCRIPTION Use positive logic rather than negative logic whenever practical. BENEFITS Makes source code more readable. The use of many logical nots "!" within an expression makes the expression difficult to understand and maintain. } } REPAIR void foo( int *j) { if(j==0){ } else { // OK (*j)++.

In C++. // OK // OK .no typedef struct B { int i. Additionally. EXAMPLE struct A { int i. // Violation . typedef struct B B_t.All structures should have typedefs [CODSTA-47-3] DESCRIPTION In C language. }. struct B { int i. using typedefs prevents programming errors due to possible typos in variable declarations. Using a typedef for each structure makes variable declarations of struct types similar to those for built in types. BENEFITS Rule improves readability and maintainability of code. the keyword struct defines a type. // Violation . and no typedefs are necessary. a structure declaration looks similar to a variable declaration of the struct type. which improves readability of code. }. }. or should be used. EXCEPTIONS This rule applies only to C code. } A_t.no typedef REPAIR typedef struct A { int i.

REFERENCES Customer guidelines .

<:.<%2. C++ CODING STANDARDS Chapter 4.1 BENEFITS Rule improves readability of code. %>. AV Rule 12 2. // OK REFERENCES 1. // Violation REPAIR int a[2][2] = { {0.3%>%>. :>. SINCE v7.3} }. %:%: The use of digraphs listed in this rule can obscure the meaning of otherwise simple constructs.1%>. :>.1}. Chapter 6.4 Environment. <:. AIR VEHICLE.The following digraphs will not be used <%. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. {2. %:. %>. Rule 2-5-1 . EXAMPLE int a <: 2 :> <: 2 :> = <%<%0. %:%: [CODSTA-48-3] DESCRIPTION The following digraphs will not be used <%. Section 2. %:. JOINT STRIKE FIGHTER.

EXAMPLE void foo() { for(int i=0. j< 10.1 BENEFITS A while loop provides a more natural representation. a while loop will be used instead.... SINCE v7. */ } int j = 0.) { /* .. */ } } REPAIR void foo() { int i = 0.Null initialize or increment expressions in for loops will not be used. // Violation . a while loop will be used instead [CODSTA-49-3] DESCRIPTION Null initialize or increment expressions in for loops will not be used.) // Violation { /* . Rule reports a violation message if 'for' statement misses init or increment section. for(. i< 10.

AV Rule 200 ... while(j< 10) { /* .. */ } // OK int j = 0. AIR VEHICLE. */ } // OK } REFERENCES JOINT STRIKE FIGHTER.24 Flow Control Structures.while(i< 10) { /* . C++ CODING STANDARDS Chapter 4..

AV Rule 150 2.Hexadecimal constants will be represented using all uppercase letters [CODSTA-50-3] DESCRIPTION Hexadecimal constants will be represented using all uppercase letters. // Violation REPAIR int i = 0x3FFF. See also: CODSTA-51 SINCE v7.18 Constants. AIR VEHICLE. // OK REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 2-13-4 .1 BENEFITS Improved readability and maintenance. Section 2. Chapter 6. JOINT STRIKE FIGHTER. EXAMPLE int i = 0x3fff. C++ CODING STANDARDS Chapter 4.

AIR VEHICLE. AV Rule 14 2. See also: CODSTA-50 SINCE v7.1 BENEFITS Rule improves readability of code. C++ CODING STANDARDS Chapter 4.Literal suffixes shall use uppercase rather than lowercase letters [CODSTA-51-2] DESCRIPTION Literal suffixes shall use uppercase rather than lowercase letters. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6. JOINT STRIKE FIGHTER. Section 2. // OK } REFERENCES 1. Rule 2-13-4 .4 Environment. EXAMPLE void foo(long param = 64l) // Violation { const long a = 64l. // Violation } REPAIR void foo(long param = 64L) // OK { const long a = 64L.

.

++p) // Good { // .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..end() . */ for(. EXAMPLE void foo() { int k = 0. p != c. k--){} for(int i = k+2-10.begin() .1 BENEFITS Rule improves readability of code. k--){} } REPAIR // // // // Violation Violation Violation Violation . Note that the initialization expression may invoke an accessor that returns an initial element in a sequence: for (Iter_type p = c.. k--){} for(k--. k>0. } SINCE v7. k--){} for(int i=0.. k>0. k>0.. /* . k>0. k=2.

*/ for(k=2. k>0. i>0. }. k--){} for(k = obj. /* . int moo().. AV Rule 198 . k>0.moo()..class A { public: int i. i--){} for(k = obj. A obj.i. k--){} for(int i =0. void foo() { int k = 0. k--){} } // // // // OK OK OK OK REFERENCES JOINT STRIKE FIGHTER. AIR VEHICLE.24 Flow Control Structures. C++ CODING STANDARDS Chapter 4. k>0.

k>0. EXAMPLE void foo() { int k = 0. }. void foo() { int k = 0. k>0. k+1){} // Violation } REPAIR void zoo(){} class A { public: int i. ){} // Violation for(int i=0. i++){} // Violation for(k--. k>0. .1 BENEFITS Rule improves readability of code. for(. k--.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.

k-=1){} // // // // OK OK OK OK } REFERENCES JOINT STRIKE FIGHTER. k>0. i>0. k--){} for(int i =0. zoo()){} for(k=2.i. C++ CODING STANDARDS Chapter 4. k>0. k>0. AV Rule 199 . AIR VEHICLE. i=i-1){} for(k = obj.A obj.24 Flow Control Structures. for(int i = k+2-10.

EXAMPLE void foo(int i) { switch(i) { default: .1 BENEFITS An if statement provides a more natural representation. case 2: break. default: . See also: CODSTA-41.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. } } // Violation REPAIR void foo(int i) { switch(i) { case 1: break. } // OK . MISRA2004-15_5 SINCE v7.

AIR VEHICLE. AV Rule 196 .24 Flow Control Structures.} REFERENCES JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4.

'A'. case 2: break. BENEFITS Enhances debugging. SINCE v7. 'B' etc. case 3: break.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.1 EXCEPTIONS This rule is not intended to exclude character constants (e. readability and maintenance. // Violation // Violation // Violation .) from use as case labels.g. 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.

void foo(int color) { switch(color) { case RED: break. } } // OK // OK // OK REFERENCES JOINT STRIKE FIGHTER. default: break.18 Constants. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. case GREEN: break.default: break. case BLUE: break . GREEN = 3 }. } } REPAIR enum color { RED = 1. AV Rule 148 . BLUE = 2.

an explicit unconditional 'break' or a 'return' statement or . break.at the end a 'fall through' comment containing "fall through" phrase (checked case insensitive).2 EXCEPTIONS Rule does not report a violation message for empty labels.'break' and 'return' are nested if(j > 5){ i--. EXAMPLE void MyFunction(int i. int j) { switch(i) { case 1: // Violation i++. SINCE v7. case 2: case 3: // Violation i++. or 'fall through' comment [CODSTA-56-3] DESCRIPTION All 'case' and 'default' labels of 'switch' statement should have: . . BENEFITS Rule prevents unpredictable program behaviour.All 'case' and 'default' labels of 'switch' statement should have an explicit 'break' or a 'return' statement. } else { return i. /* wrong comment */ case 4: // Violation .

empty label case 3: // OK i++. break.} default: . } } REFERENCES Recommended by ParaSoft . } break. } else { return i. default: // OK break. break. } // Violation } REPAIR void MyFunction(int i. /* fall through */ case 4: // OK if(j > 5){ i--. int j) { switch(i) { case 1: // OK i++. case 2: // OK .

' is placed in different line than the ')'..2 EXCEPTIONS Rule does not report a violation message if the '. or 'for' constructs. // Violation for(. // Violation while(param).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. // Violation { } } REPAIR void foo(int param) .e). or while(e).) .g. 'while'. EXAMPLE void foo(int param) { if (param). SINCE v7..e. if(e). BENEFITS Rule prevents accidental termination of 'if'.. or for(e.

2002 . Final Guidance for Industry and FDA Staff Document issued on: January 11.{ if (param) { } // OK for(..) . General Principles of Software Validation. // OK while(param) { // OK } } REFERENCES 1.

. void foo() { /* . SINCE v7....2 BENEFITS Rule prevents silencing compiler and static analysis tools warnings...it just creates a void expression and suppresses warnings. */ (void)someFunction().Cast to void is not allowed [CODSTA-58-4] DESCRIPTION Avoid casts to void. */ } else{ /* . */ } } // OK .. EXAMPLE int someFunction().. void foo() { /* . A (void) cast operator does not cause a value to be converted to void . */ if(someFunction()) { /* . } // Violation REPAIR int someFunction().

REFERENCES Recommended by ParaSoft .

2 EXCEPTIONS Expressions such as [ARRAY_SIZE + 1] are allowed in array declarations for type char.h> void myFunction() { int array[10]. SINCE v7. BENEFITS Rule improves readability and maintainability.h> #define ARRAY_SIZE 10 #define MALLOC_SIZE 20 // Violation // Violation . Macros should be used instead of these calls.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. EXAMPLE #include <stdlib. so that all instances of hardcoded size could be changed by a single code update. } REPAIR #include <stdlib. malloc(20).

malloc(MALLOC_SIZE).void myFunction() { int array[ARRAY_SIZE]. } REFERENCES Recommended by ParaSoft // OK // OK .

. as 1. variable is true but not 1. */ } } REPAIR #define TRUE 1 void foo() { // Violation .Avoid comparing values with TRUE macro/enum constant using equality operators ("==".2 BENEFITS Checking "== TRUE" or "!= TRUE". if(a==TRUE) { /* . but the TRUE macro or enum constant is defined.g.. for example. can be dangerous if e. "!=") [CODSTA-60-3] DESCRIPTION Avoid checking "== TRUE" and "!= TRUE".. SINCE v7. Such checks should be avoided because true can have many possible values (any non-zero value can be true). EXAMPLE #define TRUE 1 void foo() { int a = 10.

if(a) { /* ..int a = 10. */ // OK } } REFERENCES Recommended by ParaSoft ..

EXAMPLE enum Colours { RED. 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. BLUE.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." BENEFITS Rule improves readability and maintainability of 'switch' statement. and all the enumerators are listed in case labels." SINCE v7. or else contain a suitable comment as to why no action is taken. void foo(int i) { switch( i ) { case 0: break. case 1: case 2: break. This clause shall either take appropriate action.2 EXCEPTIONS "If the condition of a switch statement is of type enum. // Violation . The requirement for a final default-clause is defensive programming. GREEN } colour.

case BLUE: break. case 1: case 2: break. } } // OK // OK . default: break. void foo(int i) { switch( i ) { case 0: break. // Violation } } REPAIR enum Colours { RED. } switch( colour ) { case RED: break. GREEN } colour.} switch( colour ) { case RED: break. case GREEN: break. case GREEN: break. BLUE.

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

// 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. EXAMPLE void f ( int ) { reinterpret_cast< void (*)( ) >( &f )." SINCE v7.2 BENEFITS Rule prevents undefined behaviour.A cast shall not convert a pointer to a function to any other pointer type. Section 5. // Violation reinterpret_cast< void * >( &f ). including a pointer to function type [CODSTA-62-3] DESCRIPTION "Conversion of a function pointer to a non-function pointer type causes undefined behaviour. Rule 5-2-6 . Undefined behaviour may arise if a function call is made using a pointer that is the result of a function pointer conversion.

>>=. <<=. us2. EXAMPLE int foo1( ) { signed short s1." SINCE v7. unsigned short us1. | and |=) are not normally meaningful on signed integers or enumeration constants.2 BENEFITS Rule prevents undefined behaviour. ^. us1 = us2 & (unsigned short)s1. &.Bitwise operators shall only be applied to operands of unsigned underlying type [CODSTA-633] DESCRIPTION "Bitwise operations (~. us1 = us2 & s1. ^=. >>. <<. // Violation } REPAIR int foo1( ) { signed short s1. an implementation-defined result is obtained if a right shift is applied to a negative value. Additionally. &=. } // OK . us2. unsigned short us1.

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

EXAMPLE void foo( int i ) { switch( i ) { case 0 : i = 4. To ensure that such errors can be detected. i++. If a developer fails to add a break statement to the end of a switch-clause.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. Whilst this is sometimes intentional. then control flow "falls" into any following switchclause. the last statement in every switch-clause shall be a break statement. it is often an error. break. if (i > 0) // Violation // Violation . as this allows groups of clauses requiring identical statements to be created. case 1 : i = 7. then the last statement in the compound statement shall be a break statement. A special case exists if the switch-clause is empty.2 BENEFITS Prevents unpredictable program behaviour." SINCE v7. or if the switch-clause is a compound statement.

i++. case 1 : i = 7. break. // Violation } } REPAIR void foo( int i ) { switch( i ) { case 0 : i = 4. throw. } case 2 : { // Violation i = 3.{ i = 5. if (i > 0) { i = 5. } default: i = 8. } case 3 : default: i = 8. } break. } } // OK // OK // OK // OK .empty case // OK . break. break. case 2 : { i = 3. break.

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

int i ) { S * s1 = reinterpret_cast< S * >( v ). // 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 . converting from an integral type or a pointer to void type to a pointer to an object leads to unspecified behaviour. // Violation S * s2 = reinterpret_cast< S * >( i ).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. void f ( void * v. EXAMPLE struct S { int i.2 BENEFITS In general. }. int j.

Rule 5-2-8 . Section 5.systems Chapter 6.

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.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. ushort ^= mask. unsigned short ushort." EXAMPLE void foo() { unsigned char mask = ~(0x10). and not the number of bits in the original types of the expression. // OK } . unsigned short ushort." SINCE v7. 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. // Violation } REPAIR void foo() { unsigned short mask = ~(0x10). ushort ^= mask.

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

// Violation void foo(const int i).2 BENEFITS Rule improves readability and maintainability of code. INT i. void foo(int i){} // Violation REPAIR typedef int INT." SINCE v7. EXAMPLE typedef int INT. 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. void foo(const int i){} // OK REFERENCES . a function return type. extern INT i. // OK void foo(const int i). it may not be clear to which declaration that re-declaration refers.The types used for an object. INT i. extern int i.

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

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: .2 BENEFITS Rule improves portability and prevents undefined behaviour. For example. then the overload that would be matched by 0x8000 is therefore dependent on the implemented integer size. EXAMPLE unsigned long var = 02. If an overload set includes candidates for an unsigned int and an int.The presence of any suffixes.The magnitude of the constant. but of type (signed) int in a 32-bit environment." SINCE v7. . the value 0x8000 is of type unsigned int in a 16-bit environment. // Violation REPAIR unsigned long var = 02U.The number base in which the value is expressed. // OK REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems . Adding a "U" suffix to the value specifies that it is unsigned. . .The implemented sizes of the integer types.

Section 2.Chapter 6. Rule 2-13-3 .

<=.2 EXCEPTIONS Exceptionally. >.The relational operators <.The binary + operator may be used to add an integral value in the range 0 to 9 to ‘0’. . the equality operators == and !=." SINCE v7.." EXAMPLE void foo() { char ch = 't'. the following operators may be used if the associated restriction is observed: . >= may be used to determine if a character (or wide character) represents a digit. .The binary – operator may be used to subtract character ‘0’. != 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 =. (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.. } . and the unary & operator. ==.Expressions with type (plain) char and wchar_t shall not be used as operands to built-in operators other than =. // OK if ( ( ch >= 'a' ) && ( ch <= 'z' ) ) // Violation { //.

} REPAIR void foo() { char ch = 't'.. Section 4.. Rule 4-5-3 . } } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. // OK if ( ch == 't' ) // OK { //.

COLOUR_3. >. >=. the equality operators == and !=. <. !=. COLOUR_COUNT } colour. and the relational operators <. >=." SINCE v7. COLOUR_2. >. =.2 BENEFITS "Enumerations have implementation-defined representation and so should not be used in arithmetic contexts.Expressions with type enum shall not be used as operands to built-in operators other than [ ]. COLOUR_2. the assignment operator =. COLOUR_COUNT } colour. void foo() { if ( ( COLOUR_0 + COLOUR_1 ) == colour ){} // Violation } REPAIR /* Examples of correct code */ enum { COLOUR_0. the unary & operator. <=. 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 [ ]. COLOUR_3. COLOUR_1. ==. COLOUR_1. <=." EXAMPLE /* Examples of incorrect code */ enum { COLOUR_0. 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. Rule 4-5-2 . Section 4.

// Violation // Violation REPAIR struct MyStruct { signed int si01 : 2." SINCE v7. // OK // OK . EXAMPLE struct MyStruct { signed int si01 : 1. Anonymous signed bit-fields of any length are allowed. signed int si02 : 1. The values which may be represented by a bit-field of length one may not meet developer expectations. signed int : 1. }.2 NOTES Rule reports violations only for explicitly signed types BENEFITS Rule prevents the potential pitfalls and erroneous code. }.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.

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

'#pragma endasm' or an assembler instruction that form is different than "asm" is found. allowing a consistent mechanism to be used. Section 7. // OK } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.2 BENEFITS Rule improves consistency of the code.Assembler instructions shall only be introduced using the asm declaration [CODSTA-73-3] DESCRIPTION "The asm declaration is available to all C++ implementations. the parameters to asm are still implementation-defined. SINCE v7." Rule reports a violation if '#pragma asm'. #pragma endasm } // Violation // Violation REPAIR void foo() { asm ( "NOP" ). EXAMPLE void foo() { #pragma asm "NOP". Rule 7-4-2 . However.

.

.. EXAMPLE enum Color{RED.2 BENEFITS Rule prevents undefined behaviour. /* ... */ }.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. struct S { Color n : 2. BLACK}. // Violation REPAIR struct S { unsigned int n: 2 // OK /* ." SINCE v7. BLUE. */ }. REFERENCES .

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

REPAIR /* Examples of correct code */ struct S { unsigned char c : 2. // OK . EXAMPLE /* Examples of incorrect code */ struct S { char c : 2.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. // Violation }. // OK signed short f : 3." SINCE v7. // OK unsigned int : 0. // Violation short f : 3.2 BENEFITS Rule prevents undefined behaviour. // Violation int : 0. 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.

bool b : 4 // OK }. Rule 9-6-2 . REFERENCES MISRA C++:2008 . Section 9.Guidelines for the use of the C++ language in critical systems Chapter 6.

Section 7. 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. Rule 7-3-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." SINCE v7.2 BENEFITS Rule improves readability of code. The use of main for other functions may not meet 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.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. Therefore.2 BENEFITS Prevents unspecified behaviour.jumps backward ++j. can also lead to the program exhibiting unspecified behaviour. and it is possible that these flags may themselves be less transparent than the goto they replace. } . for C++. EXAMPLE void foo(int j) { L1: ++j." SINCE v7. the restricted use of goto is allowed where that use will not lead to semantics contrary to developer expectations. However. // Violation . in many cases a total ban on goto requires the introduction of flags to ensure correct control flow. goto L1. analyse and.

REPAIR void foo(int j) { ++j. Rule 6-6-2 . Section 6. goto L1. // OK ++j. L1: } jumps forward REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

} } . 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.2 BENEFITS Prevents unspecified behaviour. the restricted use of goto is allowed where that use will not lead to semantics contrary to developer expectations.. However. goto L1. Jumping in to nested blocks is prohibited as it may lead to complex flow graphs. Unconstrained use of goto can lead to programs that are extremely difficult to comprehend. 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. or in a block enclosing the goto statement. EXAMPLE void f1 ( ) { int j = 0. j < 10 . Therefore..Any label referenced by a goto statement shall be declared in the same block. can also lead to the program exhibiting unspecified behaviour. */ L1: // Violation j. for ( j = 0." SINCE v7. for C++. analyse and. ++j ) { /* .

*/ } L1: // OK j.. for ( j = 0.. Section 6. j < 10 . ++j ) { /* .REPAIR void f1 ( ) { int j = 0. Rule 6-6-1 . goto L1. } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

for example. for dual outcome loops or optimal coding. a < 10. One break or goto statement is acceptable in a loop since this allows." EXAMPLE void foo( ) { int a.2 BENEFITS "Restricting the number of exits from a loop is done in the interests of good structured programming. } } } REPAIR void foo( ) { int a. for (a = 0." SINCE v7. } if (a == 7) { break. a++) { // Violation if (a == 5) { break.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. .

Section 6. } } } REFERENCES MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. Rule 6-6-4 .for (a = 0. a++) { // OK if (a == 5 || a == 7) { break. a < 10.

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. int y.. y = 10.2 EXCEPTIONS Rule does not report a violation if the 'continue' is used within 'for' loop. EXAMPLE void foo() { int x = 0. while(x < y) { x++. The required testing may not be achievable due to control flow dependencies." SINCE v7. /* . This complexity may impede effective testing as extra logic must be tested. */ continue. } // Violation . BENEFITS Rule eliminates unnecessary complexity within the code..

Rule 6-6-3 .} 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.

2 BENEFITS Rule improves good programming style and readability. 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. Rule 3-3-2 . Chapter 6.Guidelines for the use of the C++ language in critical systems. then it has internal linkage." See also: MISRA2004-8_11 SINCE v7. EXAMPLE static void f1 ( ). static void f1 ( ) { } // OK REFERENCES 1.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. MISRA C++:2008 . void f1 ( ) { } // Violation REPAIR static void f1 ( ). Section 3. However. A re-declaration of such a function is not required to have the static keyword. but it will still have internal linkage.

.

g.if there's a termination point in a function called from within the loop.throw that is not caught by try/catch inside of the loop . the rule will still report a violation. The rule does only limited checking of 'catch' handlers. The rule reports a violations if an iteration statement (while.Avoid infinite loops [CODSTA-82-3] DESCRIPTION Infinite loops are usually caused by user error and result in resource exhaustion or program termination.break . . for) does not have a termination point. Only loops with empty or simple constant conditions are checked.3 NOTES The rule does not check called functions .goto to a label outside of the loop . resource exhaustion or computer "freezing". The rule does not check if the termination point is reachable (e.return . The rule assumes that a loop can be terminated if it contains: . abort or _Exit SINCE v7. do while.calls to standard functions: exit. 'break' inside of an 'if' statement is considered to be valid regardless of the 'if' condition). which is used to stop the loop. BENEFITS Finds possible infinite loops that could result in unwanted program termination.

++ptr) { if (!*ptr) { goto END_LOOP. } } while(true) { if (!s) { // return. } while(true) { if (!s) { return. } break. } // Violation . } ++s. } do { char * ptr = s. for(. } } END_LOOP: } while(1). } do { // OK // OK // OK .. case '\0': break. } ++s.infinite loop // The break is for 'switch'! // Violation .infinite loop // Jump does not end 'do while' loop REPAIR void foo(char *s) { for (. case '\0': break.. ptr.) { switch (*s++) { case 'a': continue.infinite loop // Code commented out by mistake // Violation .EXAMPLE void foo(char *s) { for (.) { switch (*s++) { case 'a': continue.

char * ptr = s. for(. ptr. ++ptr) { if (!*ptr) { goto END_LOOP. } } } while(1). END_LOOP: } REFERENCES Recommended by ParaSoft .

'FB > variable'.a const variable with known initializer higher than 0. . in a process scheduler).a constant higher than 0." The rule reports a violation if: . 'variable = variable . of course. EXAMPLE void foo(int p){ . 'FB >= variable' where FB is a constant or a const variable or parameter. '++variable'.parameter/variable/expression of unsigned type. . 'variable = variable + PV'. 'variable -= PV'.a loop is non-infinite and does not contain in condition single relational expression 'variable < FB'. code that traverses a linked list).a loop contains proper condition with upper bound but does not contain incrementation of checked variable 'variable++'. 'variable = PV + variable' . .g. '--variable'. 'variable += PV'. apply to iterations that are meant to be non-terminating (e.3 BENEFITS Rule prevents writing endless loops. and the function containing the failing iteration returns an error. 'variable <= FB'.a loop contains proper condition with lower bound but does not contain decrementing of checked variable 'variable--'.g.. When the upper bound is exceeded an assertion failure is triggered.PV' where PV is: .." "One way to support the rule is to add an explicit upper bound to all loops that have a variable number of iterations (e. SINCE v7. This rule does not.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.

while(i < 5){ i = i + 2. i++){ // Violation .int i = 0.. } // OK while(i < 7){ i++.variable is not compared with constant // Violation . i--){ // Violation . } // Violation .no decrementing of variable inside loop for(i = 10. } while(i < 7){ loop // . i <= 7. while(i == 5){ i = i + 2.. i >= 7.no decrementing in loop } } REPAIR void foo(const int p){ int i = 0..no incrementation in loop } while(i > 7){ // .no relational operator in condition // Violation . i <= 7. } // Violation . } // OK while(i < p){ i++. } while(i < p){ i++. i++){ // OK } . } // OK for(i = 10..no incrementation of variable inside for(i = 10.

while(i > 7){ --i. Rule 2 . i >= 7. i--){ // OK } } REFERENCES The Power of Ten . } // OK for(i = 10.Rules for Developing Safety Critical Code.

abort or _Exit SINCE v7. Only loops with empty or simple constant conditions are checked.return .. BENEFITS The rule prevents unexpected termination of loop that can not terminate.calls to standard functions: exit.if there's a termination point in a function called from within the loop.){ // code break.g.3 NOTES The rule does not check called functions . in a process scheduler). which is used to stop the loop. the rule won't report a violation. do while. It should be statically provable that the iteration cannot terminate.throw that is not caught by try/catch inside of the loop .goto to a label outside of the loop .Avoid exit points within infinite loops [CODSTA-85-3] DESCRIPTION "This rule applies to iterations that are meant to be non-terminating (e. EXAMPLE void foo(){ for(. The rule assumes that a loop can be terminated if it contains: . for) has a termination point.break .. } // Violation ." The rule reports a violations if an iteration statement (while.

. } // Violation } REPAIR void foo(){ for(.){ // code } while(1){ // code } // OK // OK } REFERENCES The Power of Ten .while(1){ // code return. Rule 2 .Rules for Developing Safety Critical Code.

int q){ p++. switch or ternary operator. return p + q. EXAMPLE int foo3(int p. } // Violation REPAIR int foo4(int p." The rule reports a violation if a parameter is not checked before the first use inside function. } p++.The validity of parameters must be checked inside each function [CODSTA-86-3] DESCRIPTION "The validity of parameters must be checked inside each function. // OK . return p + q.3 NOTES The rule assumes that the parameter is validated if it is used inside condition of statements: if. BENEFITS The rule prevents use incorrect value of parameter. SINCE v7. int q){ if(p == 0 || q == 0){ return 0. q++. q++.

} REFERENCES The Power of Ten .Rules for Developing Safety Critical Code. Rule 7 .

no more than one level of dereferencing is allowed. **p = 1." EXAMPLE void foo(){ int** p. REFERENCES The Power of Ten .Use no more than one level of dereferencing [CODSTA-87-3] DESCRIPTION "The use of pointers should be restricted. int i. // Violation i = **q. especially by tool-based static analyzers. // Violation } REPAIR Do not use more than one level of dereferencing. . They can make it hard to follow or analyze the flow of data in a program. Specifically." SINCE v7.3 BENEFITS "Pointers are easily misused.Rules for Developing Safety Critical Code. int** q. even by experienced programmers.

Rule 9 .

especially by tool-based static analyzers. /* Violation .variable z */ foo1(y).3 BENEFITS The rule improves readability of code and causes that the code can be easier checked by static analyzers.unnamed parameter ignored */ void foo3(FP p). /* OK .variable x */ void foo1(FP * y) { /* Violation .param x */ int (*z)(void) = 0. Function pointers are not permitted. /* OK . extern FP x[].function declarations are ignored */ REPAIR Do not declare pointers to functions. /* Violation ." SINCE v7. EXAMPLE typedef void (*FP)(). They can make it hard to follow or analyze the flow of data in a program. Pointers are easily misused. even by experienced programmers.Function pointers are not permitted [CODSTA-88-3] DESCRIPTION "The use of pointers should be restricted. REFERENCES .usage is ignored */ } void foo2(FP) {} /* OK .

Rules for Developing Safety Critical Code.1.4.4 . The Power of Ten . ISO/DIS 26262 point 8. Rule 9 2.

/* int ** ptr. /* Violation */ int** ptr. and should therefore be avoided. INTPTR ptr_t = 0.3 BENEFITS Rule improves safety of the code. INTPTR par_t ) { int* a[10]. /* Violation */ int* a[]. struct S** ps. void fun( int** par. int** foo(). /* Violation */ }. int**(*pfunc2)(). int(**pfunc1)(). SINCE v7.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. EXAMPLE typedef int** INTPTR. } /* Violation */ /* Violation */ /* Violation */ /* Violation */ /* Violation */ /* Violation */ Violation */ /* Violation */ /* Violation */ . /* Violation */ struct S{ int** s.

4.REPAIR Do not declare more than one level of pointer indirection.Rules for Developing Safety Critical Code. ISO/DIS 26262 point 8. The Power of Ten . REFERENCES 1. Rule 9 2.4 .

3 EXCEPTIONS "Where an expression consists of either a sequence of only logical '&&' or a sequence of only logical '||'. int z ) { if ( x || y && z ). // OK // OK . int y." See also: MISRA2004-12_1_e. // Violation return 0. "Parentheses are important in this situation both for readability of code and for ensuring that the behaviour is as the developer intended." EXAMPLE int foo( int x. extra parentheses are not required.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. BENEFITS "The effect of this rule is to require that operands are appropriately parenthesized. // Violation if ( x && !y ). } REPAIR int foo( int x. if ( x && ( !y ) ). int y. constant or function call is not parenthesised. int z ) { if ( x || ( y && z ) ). MISRA2004-12_5 SINCE v7.

Section 5.return 0. AV Rule 158 .21 Operators.Guidelines for the use of the C++ language in critical systems. AIR VEHICLE. Rule 5-2-1 2. } REFERENCES 1. MISRA C++:2008 . JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4. Chapter 6.

second exit point at the end of function */ } *a = 10. SINCE v7.3 EXAMPLE int foo(int i) { if (i == 0) { return 0.A function shall have at most one exit point [CODSTA-91-3] DESCRIPTION Every function should have at most one exit point.h are detected by rule as exit points. /* Violation */ } } void foo2(int* a) { if (a == 0) { return. and _Exit from standard library stdlib. abort. Calls of functions exit. if (i == 0) { result = 0. /* Violation */ } else { return 2. } REPAIR int foo(int i) { int result = 0. } else if (i == 1) { . /* Violation */ } else if (i == 1) { return 1. /* Violation .

3. { = 2.4 . ISO/DIS 26262 point 8. HIS Source Code Metriken. /* OK */ } void foo2(int* a) { if (a != 0) { *a = 10. version 1.4. result.result } else result } return = 1. } } /* OK */ REFERENCES 1.1 Metrik "RETURN" 2.

CODSTA-93 BENEFITS Rule prevents undefined behaviour.h. tgmath. Chapter 6. inttypes.h. stddef. signal.h. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.h. time. the modified macro or object shall have a new name.h. math. fenv. complex. or a modified version of them.h. wctype. wchar. string. This is to avoid any confusion as to whether a standard macro or object. stdarg. stdio. stdbool. float. to enhance functionality or add checks of input values). stdlib.h. Section 17.h.identifiers that begin with the underscore character See also: NAMING-33." Rule checks if the following reserved names are used: .h. limits.macro and typedef names from C standard library headers: assert. Rule 17-0-2 .h.h.h.h. is being used.h.h.h. EXAMPLE #define NULL ( a > b ) #define _NULL ( a > b ) // Violation // Violation REPAIR #define MY_NULL ( a > b ) // OK REFERENCES 1. setjmp. MISRA2004-20_2.h.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. errno. iso646.h .h.g.h. locale. stdint. ctype.h.h.h.h.

.

h. ctype. So.h.h.h. to enhance functionality or add checks of input values). However. stdbool.h.h. limits.h .h. for example. setjmp.h.h. It is permissible to add a new sqrt function for a type not present in the library.h. errno.h. stdio. fenv.function names from C standard library headers: assert. if a new version of the sqrt function is written to check that the input is not negative. math.h. wctype. stdarg.h. inttypes. stddef. stdlib. stdint. it is permissible to overload the name to add new parameter types if the functionality is consistent with those of the original.h. float.h. This ensures that the behaviour associated with the name remains consistent. CODSTA-92 BENEFITS Rule prevents undefined behaviour. complex. but shall be given a new name. The user should himself check if the modified function has the same functionality and could overload a function from standard library.h." Rule checks if the following reserved names are used: .g. rule reports violations on all declared functions which names are reserved. Rule also does not have exception that permits overloading functions with . signal.h.h. iso646.function names that begin with the underscore character See also: NAMING-33. DRAWBACKS It is not possible in static analysis to check if the functionality is consistent with those of the original.h. string. locale.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.h. wchar. tgmath. So. the new function shall not be named "sqrt". time.h.h. MISRA2004-20_2.h. the modified function shall have a new name.

EXAMPLE int printf ( int a. 2002 . Rule 17-0-3 2. Section 17. } // OK REFERENCES 1. Chapter 6. } // Violation REPAIR int my_printf ( int a. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. General Principles of Software Validation. int b ) { return ( ( a > b ) ? a : b ). Final Guidance for Industry and FDA Staff Document issued on: January 11. int b ) { return ( ( a > b ) ? a : b ).types not present in the standard library.

See also: CODSTA-95 SINCE v9. /* Violation */ int* foo(). /* Violation */ void bar(int*) /* Violation */ { int tab[10]. Rule reports violation on any declarations of functions or variables that use pointers or arrays.0 BENEFITS The rule prevents memory leaks. but if you do not use pointers properly there is a possibility that your program might crash. /* Violation */ } . /* Violation */ int *tab1[10]. /* Violation */ void (*FP)(). or takes pointer or array as a parameter. nor to declare global or local variable with pointer or array type. memory corruptions and undefined behaviours. dereferencing a null pointers. EXAMPLE typedef int* INT_P. buffer overflows. It is not allowed to declare function that returns pointer to any type. Function pointers are not allowed as well.no violation on typedef */ INT_P x. /* OK . they come with certain dangers and disadvantages despite their necessity. Because pointers deal with memory dynamically.Do not declare pointer or array type [CODSTA-94-3] DESCRIPTION Through pointer you can access the memory directly.

REFERENCES Recommended by ParaSoft .REPAIR Pointers and arrays should not be used.

See also: CODSTA-94 SINCE v9. /* Violation */ void bar(int*) /* Violation */ { int tab[10]. Because pointers deal with memory dynamically. /* Violation */ } REPAIR . Function pointers are not allowed as well.no violation on simple array */ int *tab1[10]. nor to declare global or local variable with pointer type. /* OK . EXAMPLE typedef int* INT_P. It is not allowed to declare function that returns pointer to any type. Rule reports violation on any declarations of functions or variables that use pointers. /* OK . or takes pointer as a parameter. buffer overflows.no violation on typedef */ INT_P x. dereferencing a null pointers. memory corruptions and undefined behaviours. they come with certain dangers and disadvantages despite their necessity. but if you do not use pointers properly there is a possibility that your program might crash.Do not declare pointer type [CODSTA-95-3] DESCRIPTION Through pointer you can access the memory directly. /* Violation */ int* foo(). /* Violation */ void (*FP)().0 BENEFITS The rule prevents memory leaks.

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] .

then the combination /* */ may be used to make comments out of entire sections of code during the development and debugging phases. JOINT STRIKE FIGHTER.Prefer C++ style comment [COMMENT-01-3] DESCRIPTION Use // for comments. Do not use /* and */. AV Rule 126 . does not allow comments to be nested using /* */. If the characters // are consistently used for writing comments. "C++." BENEFITS Rule improves readability and maintainability.org/resources/cstyle/Ellemtel-rules-mm.14 Comments. Ellemtel Coding Standards http://www. AIR VEHICLE. however.4.html from: 4 Source Code in Files . C++ CODING STANDARDS Chapter 4.chris-lott.Rec.3 Comments . EXAMPLE /* Violation */ REPAIR // OK REFERENCES 1. 9 2.

org/resources/cstyle/Ellemtel-rules-mm. AV Rule 133 .chris-lott.no copyright information REPAIR // Copyright REFERENCES 1. EXAMPLE // Violation .Rule 5 2.html From: 4 Source Code in Files . C++ CODING STANDARDS Chapter 4.4.14 Comments.3 Comments . Ellemtel Coding Standards http://www.Provide copyright information [COMMENT-02-3] DESCRIPTION "All files must include copyright information. AIR VEHICLE. JOINT STRIKE FIGHTER. that is to say a line starting with: // Copyright" BENEFITS Rule improves readability and maintainability.

4. EXAMPLE // No comment "File:" // Violation .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. AIR VEHICLE.html From: 4 Source Code in Files .Rule 4 2. Ellemtel Coding Standards http://www.14 Comments.no introductory comment REPAIR // File: <short description of the file> // OK REFERENCES 1. BENEFITS Rule improves readability and maintainability. AV Rule 133 .org/resources/cstyle/Ellemtel-rules-mm. JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4.chris-lott.3 Comments .

Comment every function [COMMENT-04-3] DESCRIPTION "Write some descriptive comments before every function. } REPAIR // Comment with description for the function. . } int foo3(int x).there is no prototype and function definition is not preceded with a comment . // Violation int foo2(int x){ // Violation return x++. int foo3(int x){ // Violation return x++. 2) function definition if: . void foo1()." Rule reports a violation message on: 1) function prototype if no function definition is visible and prototype is not preceded with a comment. EXAMPLE void foo1(). // Comment with description for the function.there is visible prototype but neither prototype nor function definition is preceded with a comment BENEFITS Rule improves readability and maintainability.

Ellemtel Coding Standards http://www.4.org/resources/cstyle/Ellemtel-rules-mm.3 Comments . 8 2.html from: 4 Source Code in Files . } int foo4(int x). } REFERENCES 1. int foo3(int x){ return x++.int foo2(int x){ return x++. // Comment with description for the function. AV Rule 134 . int foo3(int x). JOINT STRIKE FIGHTER. int foo4(int x){ return x++.Rec.14 Comments. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. } // Comment with description for the function.chris-lott.

OK // comment .OK int var2. // comment . . BENEFITS Rule improves readability of code. SINCE v7. // Violation } REPAIR void foo() { int var1.Each variable declaration should be commented [COMMENT-05-3] DESCRIPTION Each variable declaration should be commented.1 NOTES Rule checks only declarations of local and global variables. EXAMPLE void foo() { int var1. Rule reports a violation message if there is no comment placed in line of variable declaration nor in previous line. // Violation int var2.

C++ CODING STANDARDS Chapter 4.14 Comments. AV Rule 132 . AIR VEHICLE.} REFERENCES JOINT STRIKE FIGHTER.

Rule reports a violation message if there is no comment in line of typedef declaration and in previous line. // OK . // Violation REPAIR typedef int int32.comment REFERENCES JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4. EXAMPLE typedef int int32.14 Comments. AV Rule 132 . AIR VEHICLE.1 BENEFITS Rule improves readability of code. SINCE v7.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 enumeration value declaration and in previous line. AIR VEHICLE. SINCE v7. C++ CODING STANDARDS Chapter 4. // OK . // Violation }.14 Comments. AV Rule 132 .comment }. REPAIR enum { ENUM1 = 2.1 BENEFITS Rule improves readability of code. EXAMPLE enum { ENUM1 = 2.Each enumeration value should be commented [COMMENT-07-3] DESCRIPTION Each enumeration value should be commented. REFERENCES JOINT STRIKE FIGHTER.

EXAMPLE struct S { char* c.Each structure member variable should be commented [COMMENT-08-3] DESCRIPTION Each structure member variable should be commented. C++ CODING STANDARDS Chapter 4.1 BENEFITS Rule improves readability of code. REPAIR struct S { char* c. REFERENCES JOINT STRIKE FIGHTER.OK }. SINCE v7. // comment .14 Comments. AV Rule 132 . Rule reports a violation message if there is no comment in line of structure member declaration and in previous line. AIR VEHICLE. // Violation }.

} REPAIR void foo( void ) { // OK . } . EXAMPLE // Violation in line with 'asm' instruction void foo( void ) { asm ( "NOP" ).All usage of assembler shall be documented [COMMENT-09-3] DESCRIPTION "All usage of assembler shall be documented.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." SINCE v7. BENEFITS Rule improves readability of code. Assembly language code is implementation-defined and therefore is not portable.comment before 'asm' instruction asm ( "NOP" ).

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

double d2) { double d = d1 + d2. then the following issues need to be covered as part of the deviation process: ." EXAMPLE // Violation in line: double d = d1 + d2. } REPAIR double add(double d1. double d2) { double d = d1 + d2. double add(double d1. . // OK .Demonstrate that an appropriate process is being applied.A justification explaining why floating-point is the appropriate or only solution. . SINCE v7.Use of floating-point arithmetic shall be documented [COMMENT-10-3] DESCRIPTION "If floating-point is to be used.Demonstrate that appropriate skills are available.floating point arithmetic } . ." Rule checks if in previous or the same line as floating-point arithmetic expression there is a comment.Document the floating-point implementation.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.

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

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.EXCEPT Exceptions RULES Never allow an exception to be thrown from a destructor.e. and swap [EXCEPT-01-1] Throw by value. 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] . deallocation. throw. 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.) 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.

EXAMPLE class Exceptions{}. 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. 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()." The rule reports a violation if from a destructor. }. class A{ A(). operator delete and swap function. and swap [EXCEPT-011] DESCRIPTION "Never allow an error to be reported from a destructor. BENEFITS Rule prevents propagation of exceptions out of the destructor. ~A()..Never allow an exception to be thrown from a destructor. or a swap function. void operator delete(void*). A::~A(){ throw Exceptions(). operator delete). deallocation.g. } // Violation . and to commit work if no problems occur. an operator delete or a swap function is thrown an exception or is called a function that can throw exceptions. a resource deallocation function (e.

B::~B(){ foo(). ~B(). } // OK class B { public: B(). // can throw exceptions }. void foo() throw(). // can not throw exceptions static void soo() throw(). void operator delete(void*). ~A().void A::operator delete(void*){ throw Exceptions(). } // OK void A::operator delete(void*){ soo(). ~B(). // can throw exceptions static void soo(). // can not throw exceptions }. . void foo(). A::~A(){ foo(). } // Violation REPAIR class A{ A(). } // Violation class B { public: B(). } // Violation void B::operator delete(void*){ soo(). void operator delete(void*).

. Final Guidance for Industry and FDA Staff Document issued on: January 11. } catch (.. void foo(). Chapter: "Construction. Andrei Alexandrescu. (C) 2005 Pearson Education.. } catch (. Third Edition. Rule 51 2. // can throw exceptions static void soo(). // can throw exceptions }. and Copying". "Effective C++: 55 Specific Ways to Improve Your Programs and Design".. (C) 2005 Pearson Education. Scott Meyers. General Principles of Software Validation. Herb Sutter.void operator delete(void*). 2002 . "C++ Coding Standards.){ } } // OK // OK REFERENCES 1. Inc. Destruction. B::~B(){ try{ foo()." AddisonWesley. Chapter 2. Addison-Wesley.){ } } void B::operator delete(void*){ try{ soo().. Inc. Item 8 3.

caught by pointer Violation . } catch(Exception* newException) { // throw newException. This is the combination that meshes best with exception semantics.' to 'throw except. Violation . catch by reference [EXCEPT-02-1] DESCRIPTION Exceptions should be thrown by value (not pointer) and caught by reference (usually to const). prefer just 'throw. void restoreSanity(). bool sanityObserved().Throw by value. // argument } } message"). void foo_Violation() { Exception *exp = new Exception("error if (!sanityObserved()) { throw exp. BENEFITS Prevents memory management problems and preserves polymorphism of the rethrown object. When rethrowing the same exception. }. // } try { restoreSanity(). avoiding issues related to memory management of exceptions.throwing a pointer Violation .rethrowing of .'. EXAMPLE class Exception { public: Exception( char* ).

Final Guidance for Industry and FDA Staff Document issued on: January 11." AddisonWesley. (C) 2005 Pearson Education. void restoreSanity(). Andrei Alexandrescu. Herb Sutter. } } // OK // OK // OK REFERENCES 1. General Principles of Software Validation.REPAIR class Exception { public: Exception( char* ). Inc. Chapter: "Error Handling and Exceptions". 2002 3. void foo_OK() { Exception exp("error message"). }. bool sanityObserved(). } try { restoreSanity(). "C++ Coding Standards. } catch(Exception& newException) { throw. Rule 73 2. if (!sanityObserved()) { throw exp. PCI Data Security Standard (PCI DSS) Version 1.2 Requirement 6: Develop and maintain secure systems and applications .

REFERENCES 1. BENEFITS Prevents throwing from within a destructor. Scott Meyers. "Effective C++: 55 Specific Ways to Improve . This rule is for C++ programming language only. // Violation REPAIR class Exception {}.Do not throw from within destructor [EXCEPT-03-1] DESCRIPTION This rule checks if you throw from within a destructor. It may lead to memory leaks and improper object destruction. } }. EXAMPLE class Foo { public: Foo( ) { } ~Foo( ) { throw. class Foo { public: Foo( ) { } ~Foo( ) { try { // OK } catch (Exception& e) { // caught all exceptions } } }.

Section 15. Final Guidance for Industry and FDA Staff Document issued on: January 11. Item 8 2.Your Programs and Design". 2002 . Rule 15-5-1 4. Chapter 2.html 3. General Principles of Software Validation. http://www.helsinki. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6. (C) 2005 Pearson Education.cs. Inc.fi/u/vihavain/s03/cpp/items/CppStyleRules2.. Third Edition. Addison-Wesley.

This rule enforces that proper logging is performed for such exceptions. then the rule does not report violation. std::clog to generate a log message. EXAMPLE // example of incorrect code class Exception { }.use std::cout.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. } } . void x(). it is critical to have a proper log of suspicious events. // might throw Exception } catch (const Exception& e) { // Violation .call of function that begins with 'log' or 'warning' or . BENEFITS An exception is an indication of an abnormal condition during the application runtime.no logging return. As a proper error logging procedure is recognized: . EXCEPTIONS If an exception is rethrown and could be logged somewhere else. std::cerr. When debugging abnormal conditions from the security standpoint. void foo1() { try { x().

// error logging procedure void foo1() { try { x(). return. return. // might throw Exception } catch (const Exception& e) { // OK log("Error"). void x(). } catch (float e) { // OK std::clog << "Error". } } void foo2() { try { x(). // might throw Exception } catch (const Exception& e) { // OK std::cerr << "Error". } } void foo3() { try { x().REPAIR // examples of correct code #include <iostream> class Exception{}. return. void log(char* msg). } catch (int * e) { // OK std::cout << "Error". . // might throw Exception } catch (const Exception& e) { // OK throw.

// might throw Exception } catch (const Exception& e) { // OK throw MyException(). void foo4() { try { x(). http://cwe. } } REFERENCES 1. General Principles of Software Validation.com/HTML/12. http://freshsources.mitre.07/ALLISON/ALLISON.HTM 3. Final Guidance for Industry and FDA Staff Document issued on: January 11.org/data/definitions/391. 2002 .} } class MyException { }.html 2.

try // Violation { buf = new char[512].e. int main() { char *buf. catch and try shall not be used. SINCE v7.. } // .) [EXCEPT-05-2] DESCRIPTION Do not use C++ exceptions. EXAMPLE #include <iostream> using namespace std. throw. // Violation } catch( char * str ) // Violation { cout << "Exception raised: " << str << '\n'. } REPAIR #include <iostream> . if( buf == 0 ) throw "Memory allocation failure!".C++ exceptions shall not be used (i.. return 0.1 BENEFITS Rule improves portability of the code.

} REFERENCES JOINT STRIKE FIGHTER. int main() { char *buf.using namespace std. if( buf == 0 ) cout<< "Memory allocation failure!".27 Fault Handling. // OK return 0. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. AV Rule 208 . buf = new char[512].

it is implementation-defined whether the call stack is unwound.. BENEFITS Rule prevents undefined behaviour. int main( ) { try // Violation { // . In particular. before termination. so the destructors of any automatic objects may or may not be executed." Rule checks if outermost statement of the 'main' function is a try statement with catch-all handler.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. EXAMPLE class Exception{}. the developer can ensure that the program terminates in a consistent manner. SINCE v7.. By enforcing the provision of a "last-ditch catch-all".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.

.html . Section 15.. } return 0.org/data/definitions/391. Rule 15-3-2 2. int main( ) { try // OK { // .. } catch ( . } catch ( Exception e ) { // . } REFERENCES 1.. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.. } return 0..catch ( Exception e ) { // . http://cwe. } REPAIR class Exception{}.. ) { // ....mitre.

" SINCE v7.An empty throw (throw. syntactically. Its use is intended to enable the handling of an exception to be split across two or more handlers. if(a) { throw. EXAMPLE class Exception{}. This may lead to an implementation-defined program termination. there is nothing to prevent throw. where there is no exception object to re-throw. being used outside a catch handler.) 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. However. // Violation } } REPAIR class Exception{}. void foo(int a) .2 BENEFITS Rule prevents implementation-defined behaviour. void foo(int a) { Exception E.

Final Guidance for Industry and FDA Staff Document issued on: January 11. if(a) { throw E. Section 15. Rule 15-1-3 2. General Principles of Software Validation. } // OK } REFERENCES 1.{ Exception E. 2002 . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

" SINCE v7.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. BENEFITS "Throwing an exception during start-up or termination results in the program being terminated in an implementation-defined manner. after main has returned.2 NOTES Rule checks only one level of nested function calls. // Violation – thrown after main exits } . Similarly. it is in a start-up phase." EXAMPLE class C { public: C ( ) { throw ( 0 ). 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. // Violation – thrown before main starts } ~C ( ) { throw ( 0 ). constructing and initializing static objects.

}.. C c. REFERENCES 1.. ) { // . General Principles of Software Validation. Section 15. int main( . } REPAIR Exceptions should not be throwing during start-up or termination phase... MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. Rule 15-3-1 2. Final Guidance for Industry and FDA Staff Document issued on: January 11. 2002 .

and when." SINCE v7.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. . class A { // Implementation }. // Violation – pointer type thrown } else { throw ( a2 ). void fn ( int16_t i ) { static A a1. if ( i > 10 ) { throw ( &a1 ). then it may be unclear which function is responsible for destroying it.2 BENEFITS Prevents memory management problems EXAMPLE typedef short int16_t. // Violation – pointer type thrown } } REPAIR typedef short int16_t. A* a2 = new A.

ISO/DIS 26262 point 8. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.4. Rule 15-0-2 2. Final Guidance for Industry and FDA Staff Document issued on: January 11. // OK } } REFERENCES 1. // OK } else { throw ( *a2 ). Section 15. if ( i > 10 ) { throw ( a1 ).class A { // Implementation }. A* a2 = new A. 2002 3.4 . void fn ( int16_t i ) { static A a1. General Principles of Software Validation.

not all compilers issue a diagnostic message.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.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.2 BENEFITS Rule detects errors not reported by all compilers EXAMPLE /* The code is compilable with MSVC 6." SINCE v7. } catch ( Exception e ) { } } . however.

} catch ( Exception e ) { } case 2: // OK break. 2002 . Final Guidance for Industry and FDA Staff Document issued on: January 11. } switch ( i ) { case 1: // OK try { // . } Label_10: // OK } REFERENCES 1.} REPAIR /* The example of correct code */ class Exception{}. General Principles of Software Validation. Rule 15-0-3 2. Section 15.. void f ( int i ) { if ( 10 == i ) { goto Label_10.. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.

} }.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.. it is that exception that propagates in preference to the one that was about to be thrown. or when evaluating the assignment expression that initializes the exception object.) { ..2 BENEFITS Rule improves readability of code EXAMPLE class E { public: E ( ) { throw 10." SINCE v7. int foo1() { try { if ( 0 ) { throw E ( ). // Violation } } catch(.

Section 15. // OK } } catch(.. Rule 15-1-1 2. int foo() { try { if ( 0 ) { throw E ( ). Final Guidance for Industry and FDA Staff Document issued on: January 11.. General Principles of Software Validation. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. 2002 .) { } } REFERENCES 1.} } REPAIR class E { public: E ( ){ } }.

EXAMPLE #define NULL 0 void foo() { try { throw ( NULL ). // OK . // Violation } catch ( int i ) // NULL exception handled here { // . particularly if the program only has handlers for pointer-to-type exceptions. } } REPAIR #define NULL 0 void foo() { try { throw ( 0 )." SINCE v7...2 BENEFITS Rule improves readability and maintainability of code.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.

Section 15. Rule 15-1-2 2. Final Guidance for Industry and FDA Staff Document issued on: January 11. } } REFERENCES 1.} catch ( int i ) // NULL exception handled here { // . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6.. 2002 .. General Principles of Software Validation.

" EXAMPLE class A {}. see also: EXCEPT-18 SINCE v7. In particular. class B {}. it terminates in an implementation-defined manner. If an exception is thrown as an object of a derived class.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 is implementation-defined whether the call stack is unwound before termination. so the destructors of any automatic objects may or may not be invoked." 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. BENEFITS "The objective of this rule is that a program should catch all exceptions that it is expected to throw. void main ( int i ) throw ( ) { try { . a "compatible type" may be either the derived class or any of its bases.2 NOTES Rule checks only one level of nested function calls.

// Violation } } catch ( A const & ) { } } REPAIR class A {}. // OK } } catch ( A const & ) { } catch ( B const & ) { } } REFERENCES . } else { throw B ( ). class B {}.if ( i > 10 ) { throw A ( ). void main ( int i ) throw ( ) { try { if ( i > 10 ) { throw A ( ). } else { throw B ( ).

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

void foo ( ) { throw ( 21 ). leading to implementation-defined termination of the program.2 NOTES Rule checks only two levels of nested function calls BENEFITS Rule prevents undefined behaviour. the function unexpected() is called.Where a function's declaration includes an exception-specification." SINCE v7. If std::bad_exception is not listed in the exception-specification. The behaviour of this function can be overridden within a project. but by default causes an exception of std::bad_exception to be thrown. then terminate() will be called. EXAMPLE class Exception{}. } // Violation . 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. } void goo ( ) throw ( Exception ) { foo ( ).

2002 . Final Guidance for Industry and FDA Staff Document issued on: January 11. Rule 15-5-2 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. void foo ( ) { throw ( 21 ).REPAIR class Exception{}. General Principles of Software Validation. Section 15. } REFERENCES 1. } void goo ( ) throw ( Exception. int ) // OK { foo ( ).

void foo() { try { throw ExpD1 ( ). Also.A class type exception shall always be caught by reference [EXCEPT-15-3] DESCRIPTION "If a class type exception object is caught by value. class ExpD1: public ExpBase { }. SINCE v7. only the base class’s functions (including virtual functions) can be called. if the exception object is of a derived class and is caught as the base. slicing does not occur. any additional member data in the derived class cannot be accessed. slicing occurs.2 BENEFITS "If the exception is caught by reference. throw ExpBase ( )." Rule detects class or struct type exception object that is caught by value. } catch ( ExpBase b ) // Violation . That is.derived type objects will be // caught as the base type { } } ." EXAMPLE class ExpBase { }.

Rule 15-3-5 2. void foo() { try { throw ExpD1 ( ).exceptions caught by reference { } } REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. Final Guidance for Industry and FDA Staff Document issued on: January 11. } catch ( ExpBase &b ) // OK . 2002 . throw ExpBase ( ). General Principles of Software Validation. class ExpD1: public ExpBase { }. Section 15.REPAIR class ExpBase { }.

SINCE v7. the catch part) of a function-try-block of a class constructor/destructor is undefined. class C { public: int32_t x. the object may have been successfully destroyed before the exception is handled. in the destructor. Conversely. C( ) try { // Action that may raise an exception } ." EXAMPLE typedef int int32_t.e. the catch part) of a function-try-block of a class constructor/destructor is not allowed.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. so the static member is guaranteed to exist when the handler accesses it. the object will not exist when the handler attempts to access its members.2 BENEFITS "The effect of accessing a non-static member of a class or a base class in the handler (i. the lifetime of a static member is greater than that of the object itself. if a memory allocation exception is thrown during creation of the object.e. For example. so again will not be available to the handler. By contrast.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6... ) // 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 ( . 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. ) // Violation { if ( 0 == x ) // Non-compliant – x may not exist at this point { // Action dependent on value of x } } }. General Principles of Software Validation. 2002 .. Section 15.. Final Guidance for Industry and FDA Staff Document issued on: January 11. Rule 15-3-3 2.catch ( .

. the base class handler will be used. 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.. } catch ( B &b ) { // .2 BENEFITS Rule prevents writing unreachable code.. The derived class handler is unreachable code and can never be executed. a derived class exception will match with a handler for its base class." SINCE v7.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. . When testing to see if the type of an exception matches the type of a handler.. EXAMPLE class B { }. class D: public B { }. the handlers shall be ordered most-derived to base class. If the base class handler is found before the handler for the derived class. void foo() { try { // .

. void foo() { try { // .. } } REFERENCES 1... Rule 15-3-6 2.Guidelines for the use of the C++ language in critical systems Chapter 6.. } } REPAIR class B { }. Section 15... } catch ( B &b ) // OK . Final Guidance for Industry and FDA Staff Document issued on: January 11.. MISRA C++:2008 .Derived class caught before base class { // .} catch ( D &d ) // Violation { // . General Principles of Software Validation. 2002 .Base class caught after derived class { // . class D: public B { }. } catch ( D &d ) // OK .

BENEFITS "The objective of this rule is that a program should catch all exceptions that it is expected to throw. it terminates in an implementation-defined manner. class A { int i." EXAMPLE class B{}." 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. If an exception is thrown as an object of a derived class. 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. A ( ) : i(1) { try { if ( i > 10 ) { . a "compatible type" may be either the derived class or any of its bases.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. In particular.

A a. } } catch ( A const & ) { } } }. // Violation .unhandled exception of class B REPAIR class B{}. A a. & ) & ) . // OK ) ( ).throw A ( ). class A { int i. ( ). } else { throw B ( ). A ( ) : i(1) { try { if ( i > 10 { throw A } else { throw B } } catch ( A const { } catch ( B const { } } }.

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

' 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] .' or '->' operator [FORMAT-17-3] There shall be no white space preceding '.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 '.

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. 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] . the leading parenthesis and the first argument are to be written on the same line as the function name. 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.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.

// Violation } REPAIR void foo() { int j. Different operating systems. and editors handle tabs in different ways. BENEFITS Rule prevents inconsistent display of code containing tabs in different environments. display devices. Code containing tabs will likely be indented incorrectly if ported to another environment.9 Style. // OK } REFERENCES JOINT STRIKE FIGHTER. EXAMPLE void foo() { int i. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. AV Rule 43 .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.

enum E {EN1 = 2. FORMAT-34 EXCEPTIONS Rule does not adhere to enums.4. }. // initializations and empty blocks. // OK // OK . struct S1 { int a. // class FooBar{}. }.2. struct S1 { int a. EXAMPLE class A1 { int a.3. EN2 = 1}. }. }.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. OK OK OK BENEFITS Rule improves readability and maintainability. // int array[] = {1. See also: FORMAT-03.5}. // Violation // Violation REPAIR class A1 { int a.

REFERENCES 1. AV Rule 61 . C++ CODING STANDARDS Chapter 4.org/resources/cstyle/Ellemtel-rules-mm.9 Style.chris-lott.html from: 6 Style Classes . JOINT STRIKE FIGHTER. 24 2.6. Ellemtel Coding Standards http://www.3 Compound Statements. AIR VEHICLE.Rec.

float f.'}' ends declaration of class/structure/union/enum BENEFITS Rule improves readability and maintainability. See also: FORMAT-02. // Violation } struct S{ int i. } // OK do { i++.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. REPAIR int goo(int i) { if (i == 0) { return i. It is allowed to place tokens after '}' in the same line if: . initializations and empty blocks. FORMAT-34 EXCEPTIONS Rule does not adhere to enums.'}' ends 'do-while' construct . EXAMPLE int goo(int i) { if (i == 0) { return i. } while (i < 10). // Violation . }ss. } // Violation do { i++.

} while (i < 10). }ss.4.Rec.Exception } struct S { int i.Exception enum E {EN1 = 2.3 Compound Statements. JOINT STRIKE FIGHTER.Exception REFERENCES 1. 24 2. // OK .2.Exception // OK .html from: 6 Style Classes . // OK .chris-lott.9 Style. float f. int array[] = {1.Exception // OK . Ellemtel Coding Standards http://www. AV Rule 61 .5}.org/resources/cstyle/Ellemtel-rules-mm. C++ CODING STANDARDS Chapter 4.3. class FooBar{}. // OK . AIR VEHICLE.6. EN2 = 1}.

// OK } REFERENCES Recommended by ParaSoft . void foo() { int someLocalVariableHoldingTheLimit = (MAXIMUM_LIMIT * 10) (MAXIMUM_LIMIT/2). EXAMPLE const int MAXIMUM_LIMIT = 100. Additionally. Tab is counted as one character. This rule promotes readability across various editors.Physical lines should be less than eighty characters [FORMAT-04-3] DESCRIPTION This rule checks that physical lines are less than eighty characters. // Violation } REPAIR const int MAXIMUM_LIMIT = 100. some printers will not print columns greater than 80 columns. BENEFITS Rule improves readability of code. void foo() { int someLocalVariableHoldingTheLimit = (MAXIMUM_LIMIT * 10) (MAXIMUM_LIMIT/2).

.

PARAMETER_3. PARAMETER_2.1.1). PARAMETER_4)\ (\ PARAMETER_1 + PARAMETER_2 + PARAMETER_3 + PARAMETER_4\ ) void main() { .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.\ PARAMETER_3. EXAMPLE // Violation #define SUM(\ PARAMETER_1.\ PARAMETER_4)\ (\ PARAMETER_1+\ PARAMETER_2+\ PARAMETER_3+\ PARAMETER_4\ ) void main() { int val = SUM(1. Macros over 10 lines are hard to read.\ PARAMETER_2.1. } REPAIR // OK #define SUM( PARAMETER_1. BENEFITS Readability.

1.1.int val = SUM(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. char c. } REFERENCES JOINT STRIKE FIGHTER. // Violation } REPAIR void foo() { int ii. AIR VEHICLE. // OK char cc.9 Style. C++ CODING STANDARDS Chapter 4. AV Rule 42 . BENEFITS This rule promotes readability and maintainability by reducing code complexity. EXAMPLE void foo() { int i.

EXAMPLE int y = int z=1. // OK REFERENCES Recommended by ParaSoft . // Violation // Violation REPAIR int x = 1. See also: FORMAT-08 BENEFITS This convention promotes readability by clearly separating the operands from the operator.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. 1.

See also: FORMAT-07 BENEFITS This convention promotes readability by clearly separating the operands from the operator. // Violation // Violation REPAIR int x = 1. EXAMPLE int y = int z=1.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. 1. // OK REFERENCES Recommended by ParaSoft .

// Violation y=z | 0x0f. // OK } REFERENCES Recommended by ParaSoft . // Violation } REPAIR void foo() { int z = 73. EXAMPLE void foo() { int z = 73. See also: FORMAT-10.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. y=z | 0x0f. FORMAT-11 BENEFITS This convention promotes readability by clearly separating the operands from the operator. int y=0. int y=0. y=z|0x0f.

y=z|0x0f. int y=0.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. int y=0. EXAMPLE void foo() { int z = 73. // OK } REFERENCES Recommended by ParaSoft . FORMAT-11 BENEFITS This convention promotes readability by clearly separating the operands from the operator. // Violation } REPAIR void foo() { int z = 73. // Violation y=z | 0x0f. y=z | 0x0f.

y = z & y. y y y y y = = = = = z & y. int y = 0.0 BENEFITS This convention promotes readability by clearly separating the operands from the operator. z&y.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 &. z & y. FORMAT-10 SINCE v7. // // // // // Violation Violation Violation Violation Violation } REPAIR void Space( ) { int z = 73. int y = 0. z& y. See also: FORMAT-09. z &y. EXAMPLE void Space( ) { int z = 73. } // OK .

REFERENCES Recommended by ParaSoft .

. for.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 . As conditional statement keywords are recognized: if. int y) { if (x < y){} if (x > y){} for (.).no space */ .. while See also: FORMAT-13 BENEFITS The rule improves readability of code. EXAMPLE void foo(int x.there is a tab or comment or the opening parenthesis is not in the same line as conditional statement keyword. /* Violation while (x < 10) /* Violation x++. do{ /* .. */ }while(y > 1). int y) { if(x < y){} /* Violation if (x > y){} /* Violation for(. /* Violation } REPAIR void foo(int x.).there is more than one space . while (x < 10) /* /* /* /* OK OK OK OK */ */ */ */ . switch.two spaces */ tab is used */ */ */ .

do{ /* .. /* OK */ } REFERENCES Recommended by ParaSoft .x++. */ }while (y > 1).

if. int y=1. switch.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. See also: FORMAT-12 BENEFITS A maximum of 1 ASCII space after the opening parenthesis improves readability. while. if (x == y) // OK { } if ( x == y ) // OK { } . int y=1. EXAMPLE void foo() { int x=1. if( { } x == y ) // Violation } REPAIR void foo() { int x=1.

} REFERENCES Recommended by ParaSoft .

j = ( i < 0 ) ? ( -i ) : ( i ). int i=1. } REFERENCES Recommended by ParaSoft // OK . j = ( i < 0 )?( -i ) : ( i ). EXAMPLE void foo() { int j=10.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. j = ( i < 0 ) ? ( -i ) : ( i ). int i=1. } // Violation // Violation REPAIR void foo() { int j=10.

} // Violation // Violation REPAIR void foo() { int j=10. int i=1. EXAMPLE void foo() { int j=10. } REFERENCES Recommended by ParaSoft // OK . j = ( i < 0 ) ? ( -i ) : ( i ).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. int i=1. j = ( i < 0 )?( -i ) : ( i ). j = ( i < 0 ) ? ( -i ) : ( i ).

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 '. comments and backslashes. The violation is not reported if '. /* Violation */ myObjPtr-> x. void fooR(struct MyStruct* myObjPtr) { . These operators are used to access members/elements and cannot be considered separately from them. x. } myObj.' or '->' operator [FORMAT-17-3] DESCRIPTION The rule reports a violation if there is a space or tab character immediately following '. EXAMPLE struct MyStruct { int x. BENEFITS This promotes continuity in the relationship between the operators and the members/elements on which they act.' or '->' is preceded by 'operator' keyword. } myObj.' or '->' operators. /* Violation */ } #define MACRO a. b /* Violation */ REPAIR struct MyStruct { int x. See also: FORMAT-18 NOTES The violation is not reported if '.' or '->' is last in line ignoring white spaces. void foo(struct MyStruct* myObjPtr) { myObj. This allows splitting long expressions between lines.

AV Rule 63 . /* OK */ myObjPtr-> /* OK: '->' is last in line*/ x. C++ CODING STANDARDS Chapter 4. #endif REFERENCES 1.org/resources/cstyle/Ellemtel-rules-mm. AIR VEHICLE.JOINT STRIKE FIGHTER.Rec.myObj./*comment*/ x.7 Miscellaneous . /* OK: preceded by 'operator' keyword */ }. myObj.Ellemtel Coding Standards http://www. /* OK: no space immediately after '.' is last in line */ \ b #ifdef __cplusplus struct S { int operator -> ().9 Style.6. 27 2. /* OK: '.chris-lott.x.html From: 6 Style .' */ } #define MACRO a.

These operators are used to access members/elements and cannot be considered separately from them. BENEFITS This promotes continuity in the relationship between the operators and the members/elements on which they act.' or '->' is preceded by 'operator' keyword.' or '->' operators.There shall be no white space preceding '.x. The violation is not reported if '. This allows splitting long expressions between lines. } myObj. } myObj. void foo(struct MyStruct* myObjPtr) { myObj . /* Violation */ myObjPtr ->x.' or '->' operator [FORMAT-18-3] DESCRIPTION The rule reports a violation if there is a space or tab character immediately preceding '.b /* Violation */ REPAIR struct MyStruct { int x. void fooR(struct MyStruct* myObjPtr) { . See also: FORMAT-17 NOTES The Violation is not reported if '. /* Violation */ } #define MACRO a . EXAMPLE struct MyStruct { int x.' or '->' is first in line ignoring white spaces and comments.

myObj.6. #endif REFERENCES 1.x.9 Style.' is first in line */ #ifdef __cplusplus struct S { int operator -> (). AV Rule 63 .Ellemtel Coding Standards http://www. 27 2.Rec.' */ } #define MACRO a \ . AIR VEHICLE.org/resources/cstyle/Ellemtel-rules-mm.x.html From: 6 Style . /* OK: no space immediately before '.JOINT STRIKE FIGHTER. /* OK: preceded by 'operator' keyword */ }. /* OK */ myObjPtr ->x. C++ CODING STANDARDS Chapter 4.7 Miscellaneous .b /* OK: '.chris-lott. /* OK: '->' is first in line*/ myObj /*comment*/.

// Violation int xxx. y.yy.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. yyy. // OK } REFERENCES Recommended by ParaSoft . a space shall be used to highlight this fact. This greatly improves the readability of 'C'. EXAMPLE void foo() { int xx. // Violation } REPAIR void foo() { int x.

for ( i = 0. EXAMPLE void foo() { int i. i++) // OK { } } REFERENCES Recommended by ParaSoft . i <= 10.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.i <= 10. BENEFITS Since semicolons delineate individual statements. a space shall be used to highlight this fact. for ( i = 0. This greatly improves the readability of 'C'.i++) // Violation { } } REPAIR void foo() { int i.

AIR VEHICLE. // Violation } REPAIR void foo() { int i=0. EXAMPLE void foo() { int i=0. // OK } REFERENCES JOINT STRIKE FIGHTER.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. C++ CODING STANDARDS Chapter 4.i. -.9 Style. BENEFITS Improves readability. These operators act solely on their operand and cannot be considered separately from it. AV Rule 63 . This promotes continuity in the relationship between the operators and their associated operand. --i.

} // Violation REPAIR void foo() { int y = 0. y ++. EXAMPLE void foo() { int y = 0. AV Rule 63 . } // OK REFERENCES JOINT STRIKE FIGHTER. BENEFITS Improves the readability of code. C++ CODING STANDARDS Chapter 4. This promotes continuity in the relationship between the operators and their associated operand.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. AIR VEHICLE.9 Style. y++. These operators act solely on their operand and cannot be consider separately from it.

EXAMPLE void foo() { sizeof (int). FORMAT-25 BENEFITS Improves the readability of code. See also: FORMAT-24. // OK } REFERENCES Recommended by ParaSoft .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. // Violation } REPAIR void foo() { sizeof(int).

// OK } REFERENCES Recommended by ParaSoft . arguments. See also: FORMAT-23. // Violation } REPAIR void foo() { sizeof(int). EXAMPLE void foo() { sizeof( int ). or expressions.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. FORMAT-25 BENEFITS Improves the readability of code.

// Violation } REPAIR #define true 1 #define false 0 int goo() { return(true). } // OK REFERENCES Recommended by ParaSoft . FORMAT-24 BENEFITS Improves the readability of code. // OK } void xoo() { return.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. EXAMPLE #define true 1 #define false 0 int foo() { return true.

.

BENEFITS This convention promotes readability by clearly separating the operands from the operator. if(x||y) { } if(x { } || // Violation y) // Violation } REPAIR void foo() { int x = 1.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. int y = 1. if(x || y) // OK { } } . EXAMPLE void foo() { int x = 1. int y = 1.

REFERENCES Recommended by ParaSoft .

Incorrect first line of comment indentation * .Variable "TabSize" contains the size of tab character in spaces.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. }. // Violation // Violation // Violation // Violation // Violation /** Violation . . EXAMPLE class A { }.Rule can be parameterized by changing values of the following variables in Python scripts: .in context of "()" x = 1.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. FORMAT-36. void foo(){ } class B { int a.. */ void koo( int x){ if (x == 0 || x == 1){ // OK . int b. .Both variables are set to 4. See also: FORMAT-34.Variable "IndentSize" contains the size of indentation in spaces. . . // Violation . BENEFITS Improves readability of code. FORMAT-37 NOTES ..

x = 2. // OK // OK // OK // OK // OK /** OK . // OK x = 2. // Violation } } REPAIR class A { }. void foo(){ } class B { int a...Correct first line of comment indentation * .in context of "()" x = 1. }. // OK } } REFERENCES Recommended by ParaSoft . int b. */ void koo( int x){ if (x == 0 || x == 1){ // OK .

org/resources/cstyle/Ellemtel-rules-mm.In a function definition." BENEFITS Rule improves readability and maintainability. EXAMPLE int foo() { return 0.html From: 6 Style . 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.Rec. } // Violation REPAIR int foo() { return 0. the return type of the function should be written on a separate line directly above the function name.2 Functions .chris-lott.6. } // OK REFERENCES Ellemtel Coding Standards http://www. 22 .

} // Violation REPAIR void foo( ) { int a.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. C++ CODING STANDARDS Chapter 4. BENEFITS Rule increases readability and prevents confusion.19 Variables. b. See also: FORMAT-33 NOTES Violation is not reported if variables are declared by macros. } // OK // OK REFERENCES JOINT STRIKE FIGHTER. AV Rule 152 . int b. EXAMPLE void foo( ) { int a. AIR VEHICLE.

chris-lott.Rec.2 Functions .6.org/resources/cstyle/Ellemtel-rules-mm.html From: 6 Style . 23 ." BENEFITS Rule improves readability of code. EXAMPLE void foo () {// Violation } REPAIR void foo() {// OK } REFERENCES Ellemtel Coding Standards http://www.Place left parenthesis directly after function name [FORMAT-30-3] DESCRIPTION "Always write the left parenthesis directly after a function name.

int i) { if (i != j > 0) {} } // Violation REPAIR void foo( int j. BENEFITS Makes code more readable. int i) { if (i != j && j > 0) {} } // OK REFERENCES Motorola Coding Standards G-12 . explicit logical tests should be separated in conditional expressions.Separate logical tests in conditional expressions [FORMAT-31-3] DESCRIPTION To aid in readability. EXAMPLE void foo( int j.

5 from: 6 Style .Rec. int* p2.org/resources/cstyle/Ellemtel-rules-mm.9 Style.// OK } REFERENCES 1." BENEFITS Rule makes source code more readable.Ellemtel Coding Standards http://www.// Violation int &r1 = k. EXAMPLE void foo() { int k=42. int *p1.chris-lott. AIR VEHICLE.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.// OK int& r2 = k.4 Pointers and References . AV Rule 62 .// Violation } REPAIR void foo() { int k=42.html#6. C++ CODING STANDARDS Chapter 4.JOINT STRIKE FIGHTER. 26 2.6.

See also: FORMAT-29 BENEFITS Rule prevents confusion and makes source code more readable. EXAMPLE void foo( ) { int* a.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.html#11 From: 11 Variables . 26 2.6.5 Pointers and References Rec. b. Rule 8-0-1 .org/resources/cstyle/Ellemtel-rules-mm. } // Violation REPAIR void foo( ) { int* a. 6 Style . int b. } // OK // OK REFERENCES 1. Section 8.chris-lott. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.Rule 39." Determining the types of variables becomes confusing when pointers and access specifiers are used for multiple declarations in the same statement. Ellemtel Coding Standards http://www.

.

// Rule does not report violation initializations and empty blocks. }. enum E {EN1 = 2. // OK // OK .2. }. // int array[] = {1. }. OK OK OK if in line with brace 'tab' is used. See also: FORMAT-02.4.3. BENEFITS Rule improves readability and maintainability. // Violation REPAIR class Foobar { int a. // Violation struct S1 { int a.5}.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. // class FooBar{}. FORMAT-03 EXCEPTIONS Rule does not adhere to enums. }. EXAMPLE class Foobar { int a. EN2 = 1}. struct S1 { int a.

6.3 Compound Statements.Rec.REFERENCES 1. 24 1.9 Style. AV Rule 60 . C++ CODING STANDARDS Chapter 4. AIR VEHICLE.org/resources/cstyle/Ellemtel-rules-mm. Ellemtel Coding Standards http://www. JOINT STRIKE FIGHTER.chris-lott.html from: 6 Style Classes .

html from: 6 Style . // Violation // Violation REPAIR void foo( )." BENEFITS Rule improves readability and maintainability of code. EXAMPLE void foo ( ). // OK void goo( int a ). the leading parenthesis and the first argument (if any) are to be written on the same line as the function name. 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. // OK REFERENCES Ellemtel Coding Standards http://www.org/resources/cstyle/Ellemtel-rules-mm.2 Functions .6.chris-lott.Rec. void goo( int a ). 21 .When declaring functions.

Rule does not check indentation for lines which are in context of "()" or "[]" or lines which start with preprocessor directives.1 NOTES . . .Rule can be parameterized by changing value of the "TabSize" variable in Python scripts (by default it is set to 4 spaces). // Violation x = 2. // Violation x = 2. // Violation } . BENEFITS Rule improves readability and maintainability. EXAMPLE void foo( int x ) { if (x == 0) { } x = 2.Rule treats tab characters as an alignment to correct column indentation. x = 2. See also: FORMAT-27.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. FORMAT-37 SINCE v7. // Violation x = 2.

// OK } REFERENCES Recommended by ParaSoft . // OK x = 2.REPAIR void foo( int x ) { if (x == 0) { } x = 2. // OK x = 2. // OK x = 2. // OK x = 2.

default) should be indented more than control statement keyword.Rule can be parameterized by changing values of the following variables in Python scripts: "MinIndentSize" .size of tab character in spaces All variables are set to 4 by default. catch.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. // OK . else. for. // OK .the minimum admissible size of indentation in spaces "MaxIndentSize" . switch. while. case.indent size = 2 while (x == 0) x = 1.the maximum admissible size of indentation in spaces "TabSize" .Rule does not check indentation for lines which starts with preprocessor directives. . For example: MinIndentSize = 2.indent size = 4 BENEFITS Rule improves readability and maintainability. FORMAT-36 SINCE v7. .1 NOTES .indent size = 3 while (x == 0) x = 1. do while. // OK . See also: FORMAT-27. MaxIndentSize = 4: while (x == 0) x = 1. try.

// OK x++. } } REPAIR void foo( int x ) { while (x == 0) x = 1.EXAMPLE void foo( int x ) { while (x == 0) x = 1. // Violation if (x == 0) { x++. } } REFERENCES Recommended by ParaSoft . // Violation x++. // OK if (x == 0) { x++.

the leading parenthesis and the first argument are to be written on the same line as the function name. int b. void zoo( int a. the leading parenthesis and the first argument will be written on the same line as the function name. SINCE v7. int c).1 BENEFITS Readability and style. int c ) { // Violation // Violation // Violation } REPAIR void foo(int a. int b. Each additional argument will be written on a separate line (with the closing parenthesis directly after the last argument). each additional argument will be written on a separate line [FORMAT-38-3] DESCRIPTION When declaring and defining functions with more than two parameters.// Violation void zoo( int a. EXAMPLE void foo(int a. int b. int c). int b. // OK .When declaring functions with more than 2 parameters.

// OK REFERENCES JOINT STRIKE FIGHTER.int c) // OK { } void goo(int a. AV Rule 58 . int b).9 Style. C++ CODING STANDARDS Chapter 4. AIR VEHICLE.

EXAMPLE #include "zheader2. A violation is reported if #include in previous line has name which sorts after #include in current line.h" "zheader2. BENEFITS Rule improves readability and maintainability.Sort #include directives in alphabetical order [FORMAT-39-4] DESCRIPTION Rule checks if #include directives are sorted.2 NOTES <header> includes are not compared with "header" includes.<header> not compared with "header" #include <algorithm> // Violation REPAIR #include #include #include #include #include "zheader0.previous include not in previous line #include <iostream> // ok . SINCE v9.h" "zheader1.h" // ok .h" // Violation // this line have no #include #include "zheader0.h" #include "zheader1.h" <algorithm> <iostream> . Two includes are compared only if they are in consequent lines.

no white space neither after the opening square brace '[' nor before the closing square brace ']'. 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 ']' . format = "[1]" In this case should be no white space neither after the opening square brace '[' nor before the closing square brace ']'. // Violation .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. The modification can be done in python method 'formatRule'. To variable 'format' should be assigned the string containing the preferred format. // OK int a2[ 1]. // OK int a2[ 1]. // OK 2. // Violation int a3[1 ]. 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 ']'. For example: int a1[1]. // Violation int a4[ 1 ]. There are three possibilities: 1. For example: int a1[1].

1 ]" there should be at least one white space after the opening '[' and before the closing square brace ']'. int a3[1 ]. format = "[ In this case square brace int a1[1]. /* OK . int a2[ 1]. For example: // Violation // Violation // Violation // OK BENEFITS The rule improves readability of code.space removed */ void foo() { tab[ 0 ] = 0.int a3[1 ]. // Violation 3.space added */ } REFERENCES Recommended by Parasoft . int a4[ 1 ]. /* Violation */ void foo() { tab[0 ] = 0. EXAMPLE // the default format: int tab[ 10]. // Violation int a4[ 1 ]. /* Violation */ } REPAIR // the default format: int tab[10]. /* OK .

BENEFITS The rule improves readability of code. ['x'] = 1 }. The intention of this rule is to have the bracket "glued" together with preceding token. /* Violation */ delete [] arr.2 EXCEPTIONS No violation is reported for following code: const char special[256] = { [0] = 1. See also: FORMAT-17.an opening square bracket ('[') is first token in line.There shall be no space between '[' opening square bracket and preceding token [FORMAT-415] DESCRIPTION The rule reports a violation if: . tab or comment preceding opening square bracket ('[') . FORMAT-18. /* Violation */ tab [0] = 0. EXAMPLE int tab [10]. ['?'] = 1.there is a space. /* Violation */ void foo(int param []) { /* Violation */ char* arr = new char [10]. FORMAT-40 SINCE v9. /* Violation */ } . /* Violation */ tab/*comment*/[0] = 0.

REPAIR int tab[10]. tab[0] = 0. } REFERENCES Recommended by Parasoft /* OK */ /* OK */ /* OK */ /* OK */ /* OK */ . void foo(int param[]) { char* arr = new char[10]. delete[] arr.

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] .

EXAMPLE // header file int i = 0. Multiple source files each including a file containing initializations will.// OK REFERENCES 1.Headers should not contain any initialization [INIT-01-3] DESCRIPTION Header should not contain initialization of anything. Final Guidance for Industry and FDA Staff Document issued on: January 11..// Violation REPAIR // header file int i.e. NOTES Rule is designed for C code. i. Putting initialization in header doesn't make clear which function "own" the data. BENEFITS Rule prevents producing "multiply defined" diagnostics. produce "multiply defined" diagnostics. General Principles of Software Validation. 2002 . it doesn't localize the "defining instance". in general.

private: unsigned int ai. }. MISRA2004_10_1_h BENEFITS The rule prevents undesirable implicit conversions. EXAMPLE struct S { unsigned int m_i. S s = {-10}. signed int n_i. A::A() : ai(-10){ } REPAIR struct S { unsigned int m_i. See also: PB-08. }. // Violation . void foo() { unsigned int y = -21. }. } // Violation // Violation class A { public: A().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.

private: unsigned int ai. si(-10){ } // OK REFERENCES 1. S s = { 10. Final Guidance for Industry and FDA Staff Document issued on: January 11. ISO/DIS 26262 point 8. signed int x = -21. A::A() : ai(10). }.4 . General Principles of Software Validation. 2002 2. -10}.void foo() { unsigned int y = 21. } // OK // OK // OK class A { public: A(). signed int si.4.

By always initializing variables. this can result in significantly faster code. the keyword extern is always used. Instances of a class are usually initialized even if no arguments are provided in the declaration (the empty constructor is invoked). } // Violation // Violation . Normally. the compiler gives a warning if a variable is undefined. the code is made more efficient since no temporary objects are created for the initialization. BENEFITS Prevents reading from uninitialized variables. and arrays. void foo( ) { int b. To declare a variable that has been initialized in another file. EXAMPLE int a. instead of assigning values to them before they are first used. non-primitive types. For objects having large amounts of data.Initialize all variables [INIT-03-3] DESCRIPTION "A variable must always be initialized before use." EXCEPTIONS Exception to this rule are 'volatile' data. It is then sufficient to take care of such cases.

void foo( ) { int b = 0. Final Guidance for Industry and FDA Staff Document issued on: January 11. "C++ Coding Standards.4 . AV Rule 142 4. General Principles of Software Validation.REPAIR int a = 0. Inc. ISO/DIS 26262 point 8. 2002 6. } // OK // OK REFERENCES 1.16 Initialization. Ellemtel Coding Standards http://www. Rule 19 3. Herb Sutter.html#11 From: 11 Variables ." AddisonWesley.4.org/data/definitions/457.org/resources/cstyle/Ellemtel-rules-mm.Rule 41 2. Andrei Alexandrescu. C++ CODING STANDARDS Chapter 4.mitre.html 5. JOINT STRIKE FIGHTER. (C) 2005 Pearson Education. AIR VEHICLE. Chapter: "Coding Style". http://cwe.chris-lott.

int * p) { int *i = 0. int * p) { int *i. BENEFITS Initializing pointer variables prevents dereferencing of uninitialized pointers. // Violation if (y) { j = 0.Initialize all pointer variables [INIT-04-2] DESCRIPTION This rule checks if all of your pointer variables are initialized. } } REPAIR void foo(int y. // Violation int *j. NOTES This rule enforces a good coding standard practice: always initialize pointer variables. } else { j = p. EXAMPLE void foo(int y. // OK int *j = y ? 0 : p. even if you're going to change (assign) the variable at once. // OK } .

General Principles of Software Validation. Andrei Alexandrescu. ISO/DIS 26262 point 8. Inc. 2002 3. Chapter: "Coding Style".4 . Final Guidance for Industry and FDA Staff Document issued on: January 11." AddisonWesley.REFERENCES 1. Herb Sutter. Rule 19 2.4. (C) 2005 Pearson Education. "C++ Coding Standards.

EXAMPLE void foo() { int *ptr = 0. General Principles of Software Validation. Final Guidance for Industry and FDA Staff Document issued on: January 11.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. int &rptr = ptr. // OK } REFERENCES 1. BENEFITS Prevents illegal accessing to not existing variable which was free previously. 2002 . int &rptr = *ptr. // Violation } REPAIR void foo() { int ptr = 0. and consequently can refer to the object whose address can be null. The reference to an object in the free store can be deleted via a pointer.

in constructor initialization list . C::C( ) // Violation .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.All member variables should be initialized in constructor [INIT-06-1] DESCRIPTION Constructors should initialize all member variables. int mem_c.inside body of constructor . BENEFITS Prevents reading from uninitialized variables. int mem_e. }. mem_b. EXAMPLE class C { public: C( ). The rule checks if a member variable is initialized: . mem_e . mem_c. int mem_b.mem_a. int mem_d. mem_d. private: int mem_a.not initialized { } .

Chapter 1. // initialized inside constructor body int mem_c. }. Inc. // initialized inside function 'init' called from constructor int mem_d. (C) 2005 Pearson Education.. } REFERENCES 1. void init(). void init2(). // initialized inside function 'init2' called from 'init' int mem_e. Scott Meyers. Third Edition. // initialized in constructor initialization list int mem_b.all members are initialized { mem_b = 1. } C::C( ) : mem_a( 0 ) // OK .REPAIR class C { public: C( ). init2(). void getPtr(int *). init(). Addison-Wesley. } void C::init2() { mem_d = 2. void C::init() { mem_c = 2. // its non-const pointer is passed to an external function. getPtr(&mem_e). Item 4 . "Effective C++: 55 Specific Ways to Improve Your Programs and Design". private: int mem_a.

General Principles of Software Validation. Final Guidance for Industry and FDA Staff Document issued on: January 11.2.4.4 . 2002 3. ISO/DIS 26262 point 8.

NOTES Classes that have only static members or no members at all are omitted by this rule. int main() { B bb. EXAMPLE class B { public: static int s. the compiler will write a public constructor for you by default. int b. BENEFITS If you follow this rule. } REPAIR class A { . }. especially pointer members. This rule detects if you do not define at least one constructor. int a. you will make class initialization explicit and prevent the compiler from initializing members improperly. // Violation return 0.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.

}. int main() { C cc. class D // OK { public: static int s. // OK D dd. } REFERENCES Recommended by ParaSoft . int b. // OK return 0.public: A(){} private: static int w. static int a. void qwe(int x). }. // OK A a. int a. class C // OK { public: int foo(). }. static int b.

If you do not write at least one constructor in a class. // Violation return new B(). the compiler will write a public constructor for you by default. NOTES Classes that have only static members or no members at all are omitted by this rule.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. B* foo(B* b) { B* a=new B(). }. This rule detects if you do not define at least one constructor. . especially pointer members. // Violation return 0. int b. BENEFITS If you follow this rule. int a. EXAMPLE class B { public: static int s. // Violation } int main() { foo(new B()). you will make class initialization explicit and prevent the compiler from initializing members improperly.

int a. int b.} REPAIR class A { public: A(){} static int w. A* foo2() { A* a=new A(). // OK } REFERENCES Recommended by ParaSoft . // OK return new A(). }.

// OK REFERENCES 1. 2002 .Initialize static class members [INIT-09-1] DESCRIPTION All static member variables should be initialized. // Violation static int b. // OK const int C::a. }. SINCE v7. static int b. EXAMPLE class C{ const static int a. }. Final Guidance for Industry and FDA Staff Document issued on: January 11. int C::b = 0. int C::b.0 BENEFITS Prevents reading from uninitialized variables. General Principles of Software Validation. // Violation REPAIR class C{ const static int a = 0.

2.4.4 . ISO/DIS 26262 point 8.

just to ensure that the destructors would be called in the right order. Thus. MISRA-030 BENEFITS Prevents access to null pointer when memory is not allocated. To avoid that overhead. That would be an expensive proposition.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. int a. compilers would have to keep track of the order in which the members were initialized for each object. and the order of members in an initialization list is ignored. class B : public A { public: B( int ). EXAMPLE class A { public: A( int x ) : a( x ). INIT-14. b( a ) {} private: int b. if members were initialized in the order of their appearance in an initialization list. See also: INIT-06.b is declared before a . the order of construction and destruction is the same for all objects of a given type. private: int a. // Violation ." In example section variable b from class A will not be initialized as we assumed (initialized by the same value). float b. }.

int a. Scott Meyers. Item 13 3. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". (C) 2005 Pearson Education.10 Classes.a is declared before b class B : public A { public: B( int ). A( 1 ). Final Guidance for Industry and FDA Staff Document issued on: January 11. Addison-Wesley. b( a ) {} private: int a. Chapter: "Constructors. A( 1 ). 2002 . }. private: float b. and Assignment Operators". int b. Second Edition. Destructors.b is declared before a REFERENCES 1.. Inc. C++ CODING STANDARDS Chapter 4. Inc. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". B::B( int y ) : b( 5 ). a( y ) {} before b // Violation .. a( y ) {} // OK . // OK . AV Rule 75 4. AIR VEHICLE. Chapter 1. Third Edition. }.a is declared REPAIR class A { public: A( int x ) : a( x ). Scott Meyers. Item 4 2. (C) 2005 Pearson Education. JOINT STRIKE FIGHTER. B::B( int y ) : b( 5 ). General Principles of Software Validation.}. Addison-Wesley.

.

mem_c. mem_b. EXAMPLE class C { public: C& operator=(const C&). BENEFITS Assign to all member variables in operator= function in order to prevent data corruption.Assign to all data members in operator= [INIT-11-2] DESCRIPTION If you write operator=. mem_d . int mem_b. this rule ensures that you assigned to every data member of your object. int mem_c.mem_a. private: int mem_a. int mem_d. }. See also: MRM-43 NOTES The rule assumes that member variable might be initialized by passing its non-const pointer to an external function.not assigned { } . The rule checks if a member variable is initialized: . C& C::operator=(const C&) // Violation .inside body of assignment operator .inside body of function called from assignment operator (three levels of nested function's calls are checked).

// assigned inside function 'init2' called from 'init' int mem_d.. Inc. Chapter 2. // assigned inside operator= body int mem_b. void C::init() { mem_b = 2. init().. } void C::init2() { mem_c = 2. Scott Meyers. // its non-const pointer is passed to an external function. } C& C::operator=(const C&) // OK . } REFERENCES 1. getPtr(&mem_d). Inc. "Effective C++: 55 Specific Ways to Improve Your Programs and Design".all members are assigned { mem_a = 1. init2(). Second Edition. (C) 2005 Pearson Education. Third Edition. Addison-Wesley. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". private: int mem_a. Item 12 2. . (C) 2005 Pearson Education. void init(). void getPtr(int *). Addison-Wesley. // assigned inside function 'init' called from operator= int mem_c.REPAIR class C { public: C& operator=(const C&). Scott Meyers. void init2(). }.

2002 . General Principles of Software Validation.Chapter: "Constructors. and Assignment Operators". Item 16 3. Destructors. Final Guidance for Industry and FDA Staff Document issued on: January 11.

As a bonus. Fortunately." SINCE v7. something that can't be said for true non-local static objects. non-local static objects are replaced with local static objects. where it's declared static. Clients then call the functions instead of referring to the objects." EXAMPLE #include <iostream> using namespace std. you're guaranteed that the references you get back will refer to initialized objects. the object it uses could be uninitialized. a small design change eliminates the problem entirely.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. because the relative order of initialization of non-local static objects defined in different translation units is undefined. All that has to be done is to move each non-local static object into its own function. if you never call a function emulating a non-local static object. So if you replace direct accesses to non-local static objects with calls to functions that return references to local static objects. class FileSystem { . In other words. These functions return references to the objects they contain.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. you never incur the cost of constructing and destructing the object.

C++ CODING STANDARDS . } class Directory { public: Directory( ).public: size_t numDisks( ) const. AIR VEHICLE. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Chapter 1. extern FileSystem tfs. }. FileSystem& tfs_one( ) { static FileSystem fs.numDisks( ). class FileSystem { public: size_t numDisks( ) const. JOINT STRIKE FIGHTER. Item 4 2. Third Edition. return fs. Directory::Directory( ) { size_t disks_one = tfs_one(). // OK REFERENCES 1. // Violation REPAIR #include <iostream> using namespace std. Addison-Wesley.numDisks( ). Scott Meyers. (C) 2005 Pearson Education.. class Directory { public: Directory( ). } Directory tempDir( ). Directory::Directory( ) { size_t disks_tfs = tfs. }. } Directory tempDir( ). }. }. Inc.

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

AIR VEHICLE.b)). AV Rule 124 2. JOINT STRIKE FIGHTER. General Principles of Software Validation.13 Functions. Final Guidance for Industry and FDA Staff Document issued on: January 11. C++ CODING STANDARDS Chapter 4.} inline int foo(int a. int b) // OK { return(goo(a. 2002 . } REFERENCES 1.

RWCString and CString are implicitly shared. 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. BENEFITS Improves code consistency and runtime performance. // Violation . EXAMPLE class A { public: const A violation( A a ) { value return a. } }." See also: PB-20.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.returning by value REPAIR class A { public: const A& valid( const A &a ) { return a. they may be treated like ints or other basic types. 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. } // OK // OK .passing parameter by // Violation . Due to C++'s type system and the fact that QString.

2002 . "C++ Coding Standards. REFERENCES 1.chris-lott. Scott Meyers. Third Edition. JOINT STRIKE FIGHTER. AV Rule 125 7. Chapter: "Design Style"..13 Functions. Inc. Chapter 4.9. Scott Meyers. Scott Meyers.1 Function Arguments . "Effective C++: 55 Specific Ways to Improve Your Programs and Design". (C) 2005 Pearson Education. Item 3 5. Andrei Alexandrescu.}. Ellemtel Coding Standards http://www. AIR VEHICLE. Herb Sutter.org/resources/cstyle/Ellemtel-rules-mm. Addison-Wesley. Item 22 4. Second Edition. Inc. 43 6. (C) 2005 Pearson Education. Rule 09 2.. Chapter: "Classes and Functions: Design and Declaration". (C) 2005 Pearson Education. Final Guidance for Industry and FDA Staff Document issued on: January 11. Chapter 1. Addison-Wesley. "Effective C++: 55 Specific Ways to Improve Your Programs and Design".. Third Edition.Rec. Inc. Addison-Wesley. (C) 2005 Pearson Education. Inc. Item 20 3. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". General Principles of Software Validation. C++ CODING STANDARDS Chapter 4.html From: 9 Function ." AddisonWesley.

Assignment versions of operators write to their left-hand argument. bb . you allow clients of your classes to make the difficult trade-off between efficiency and convenience.. / . // Violation // Violation . operator+). because stand-alone versions must typically return a new object.g.g. the assignment version of an operator (e..bc. and that costs us the construction and destruction of a temporary.. >> .Consider using op= instead of stand-alone op [JSF-125_b-2] DESCRIPTION When you define stand-alone version of operators: + . operator+=) should be also defined. void foo( ) { B ba. A& operator-( A& a. ^. ." EXAMPLE class A { public: }. class B { public: B& operator+=( B& b ). & . A& b ). A& b )." BENEFITS "Assignment versions of operators are more efficient than stand-alone versions. bd. B& operator+( B& a. | . << (e. "Offering assignment versions of operators as well as stand-alone versions. % . }. * . A& operator+( A& a. B& b ). so there is no need to generate a temporary to hold the operator's return value." "You should consider using assignment versions of operators instead of stand-alone versions whenever performance is at a premium.

A& class B { public: B& operator+=( B& b }. Chapter: "Efficiency". A& operator+( A& a. b ). bb = ba. // OK // OK ). b ). AIR VEHICLE. A& operator-=( A& a ). }. bb += bc. C++ CODING STANDARDS Chapter 4. bb += bd. AV Rule 125 . JOINT STRIKE FIGHTER. // Violation } REPAIR class A { public: A& operator+=( A& a ). B& operator+( B& a. bd.bb = ba + bc + bd. } b ). "More Effective C++: 35 New Ways to Improve Your Programs and Designs". bb . Scott Meyers.bc. Copyright 1996.13 Functions. A& A& operator-( A& a. Item 22 2. B& void foo( ) { B ba. // OK // OK // OK REFERENCES 1. Addison-Wesley.

If the characters // are consistently used for writing comments.chris-lott. EXAMPLE /* Violation */ REPAIR // OK REFERENCES 1.org/resources/cstyle/Ellemtel-rules-mm. AV Rule 126 . Do not use /* and */. 9 2. AIR VEHICLE.Prefer C++ style comment [JSF-126-2] DESCRIPTION Use // for comments. "C++. JOINT STRIKE FIGHTER.3 Comments .Rec. then the combination /* */ may be used to make comments out of entire sections of code during the development and debugging phases.14 Comments. C++ CODING STANDARDS Chapter 4." BENEFITS Rule improves readability and maintainability.html from: 4 Source Code in Files . Ellemtel Coding Standards http://www.4. does not allow comments to be nested using /* */. however.

" NOTES There are situations where rule may report false positive or false negative." EXAMPLE void foo() { int x = 5. #if or #ifdef constructs with a comment). Such situations are caused by similarity between source code and comment text.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. } */ } // Violation REPAIR void foo() { int x = 5.g. /* Section of code commented out if (x==0){ x++. 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. /* Comment without // OK .

} #endif } REFERENCES 1. Origin: Misra Guidelines . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. C++ CODING STANDARDS Chapter 4. Section 2. Chapter 6. Rule 2-7-3 . Section 2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 2 2.14 Comments. AIR VEHICLE.code within */ #if 0 if (x==0){ x++. AV Rule 127 4. Chapter 6.Rule 10 3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. JOINT STRIKE FIGHTER. Rule 2-7-2 5.

JOINT STRIKE FIGHTER. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. BENEFITS Prevents from various undefined and implementation-defined behaviours associated with them and they shall not be used.4 Environment.Rule 8 2.Do not use wide string literals [JSF-13-3] DESCRIPTION Wide string literals shall not be used. AV Rule 13 . Origin: Misra Guidelines ./* Violation */ } REPAIR #include <stddef.h> void foo() { char* x = "Fred".h> void foo() { wchar_t* x = L"Fred". EXAMPLE #include <stddef./* OK */ } REFERENCES 1.

SINCE v7. Rule reports a violation message if there is no comment placed in line of variable declaration nor in previous line.1 NOTES Rule checks only declarations of local and global variables.OK // comment . EXAMPLE void foo() { int var1. // Violation } REPAIR void foo() { int var1. // Violation int var2. // comment .Each variable declaration should be commented [JSF-132_a-3] DESCRIPTION Each variable declaration should be commented. BENEFITS Rule improves readability of code. .OK int var2.

C++ CODING STANDARDS Chapter 4.} REFERENCES JOINT STRIKE FIGHTER.14 Comments. AIR VEHICLE. AV Rule 132 .

1 BENEFITS Rule improves readability of code.Each typedef should be commented [JSF-132_b-3] DESCRIPTION Each typedef should be commented.comment REFERENCES JOINT STRIKE FIGHTER. AV Rule 132 . Rule reports a violation message if there is no comment in line of typedef declaration and in previous line.14 Comments. // Violation REPAIR typedef int int32. EXAMPLE typedef int int32. SINCE v7. C++ CODING STANDARDS Chapter 4. // OK . AIR VEHICLE.

Rule reports a violation message if there is no comment in line of enumeration value declaration and in previous line. EXAMPLE enum { ENUM1 = 2.1 BENEFITS Rule improves readability of code.Each enumeration value should be commented [JSF-132_c-3] DESCRIPTION Each enumeration value should be commented. REPAIR enum { ENUM1 = 2. AV Rule 132 . // OK . SINCE v7. C++ CODING STANDARDS Chapter 4. // Violation }.14 Comments. AIR VEHICLE.comment }. REFERENCES JOINT STRIKE FIGHTER.

SINCE v7. // Violation }. REPAIR struct S { char* c. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. Rule reports a violation message if there is no comment in line of structure member declaration and in previous line.14 Comments. // comment .OK }. REFERENCES JOINT STRIKE FIGHTER. EXAMPLE struct S { char* c.Each structure member variable should be commented [JSF-132_d-3] DESCRIPTION Each structure member variable should be commented. AV Rule 132 .1 BENEFITS Rule improves readability of code.

Ellemtel Coding Standards http://www.Rule 4 2.no introductory comment REPAIR // File: <short description of the file> // OK REFERENCES 1.org/resources/cstyle/Ellemtel-rules-mm.3 Comments . JOINT STRIKE FIGHTER." NOTES C and C++ style comments are allowed. EXAMPLE // No comment "File:" // Violation .html From: 4 Source Code in Files . AIR VEHICLE. AV Rule 133 . C++ CODING STANDARDS Chapter 4. BENEFITS Rule improves readability and maintainability.chris-lott.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.14 Comments.4.

no copyright information REPAIR // Copyright REFERENCES 1.4.14 Comments. C++ CODING STANDARDS Chapter 4.3 Comments . AIR VEHICLE. EXAMPLE // Violation .html From: 4 Source Code in Files . JOINT STRIKE FIGHTER. that is to say a line starting with: // Copyright" BENEFITS Rule improves readability and maintainability. Ellemtel Coding Standards http://www.org/resources/cstyle/Ellemtel-rules-mm.Rule 5 2. AV Rule 133 .Provide copyright information [JSF-133_b-3] DESCRIPTION "All files must include copyright information.chris-lott.

Comment every function [JSF-134-4] DESCRIPTION "Write some descriptive comments before every function. int foo3(int x){ // Violation return x++." Rule reports a violation message on: 1) function prototype if no function definition is visible and prototype is not preceded with a comment. EXAMPLE void foo1().there is visible prototype but neither prototype nor function definition is preceded with a comment BENEFITS Rule improves readability and maintainability. 2) function definition if: . . // Comment with description for the function.there is no prototype and function definition is not preceded with a comment . void foo1(). } REPAIR // Comment with description for the function. } int foo3(int x). // Violation int foo2(int x){ // Violation return x++.

int foo3(int x){ return x++.3 Comments . C++ CODING STANDARDS Chapter 4.Rec.4. Ellemtel Coding Standards http://www. int foo3(int x). 8 2.html from: 4 Source Code in Files . AIR VEHICLE.14 Comments.chris-lott.int foo2(int x){ return x++.org/resources/cstyle/Ellemtel-rules-mm. AV Rule 134 . } REFERENCES 1. } int foo4(int x). JOINT STRIKE FIGHTER. } // Comment with description for the function. // Comment with description for the function. int foo4(int x){ return x++.

and therefore hide that identifier [JSF-135_a-2] DESCRIPTION Do not hide names of global variables and parameters. ISO/DIS 26262 point 8. AIR VEHICLE. /* Violation */ x = 3.4 . Section 5 2. } REPAIR Avoid hiding names of global variables and parameters.Rule 21 3. EXAMPLE int x.4. Section 2. Rule 2-10-2 5. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. JOINT STRIKE FIGHTER. BENEFITS Hiding names of global variables or parameters can lead to errors and confusion. Chapter 6. REFERENCES 1.Identifiers in an inner scope shall not use the same name as an identifier in an outer scope. C++ CODING STANDARDS Chapter 4. AV Rule 135 4. Origin: Misra Guidelines . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. void foo( ) { int x.15 Declarations and Definitions.

.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 2.4.Identifiers in an inner scope shall not use the same name as an identifier in an outer scope.4 . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 2-10-2 5. Chapter 6. BENEFITS Hiding names of local variables can lead to errors and confusion. and therefore hide that identifier [JSF-135_b-2] DESCRIPTION Do not hide names of local variables. { int a. C++ CODING STANDARDS Chapter 4. Origin: Misra Guidelines .15 Declarations and Definitions. } } /* Violation */ REPAIR Avoid hiding names of local variables. JOINT STRIKE FIGHTER. AV Rule 135 4. EXAMPLE int foo( ) { int a.Rule 21 3. AIR VEHICLE. Section 5 2. ISO/DIS 26262 point 8. REFERENCES 1.

.

Rec. Ellemtel Coding Standards http://www. 57 3. ISO/DIS 26262 point 8. C++ CODING STANDARDS Chapter 4.Rule 22 2. // Violation REPAIR void foo( ) { int localVar. AV Rule 136 4. JOINT STRIKE FIGHTER.org/resources/cstyle/Ellemtel-rules-mm.15 Declarations and Definitions.Declare objects at function scope [JSF-136-4] DESCRIPTION Declarations of objects should be at function scope unless a wider scope is necessary. } // OK REFERENCES 1.4 . BENEFITS Prevents using global variables.chris-lott. EXAMPLE int globalVar.html From: 16 Memory Allocation . AIR VEHICLE. Misra Guidelines .4.

/* OK */ REFERENCES 1. /* Violation */ void foo1() {}.Rule 23 2.Make declarations at file scope static where possible [JSF-137-4] DESCRIPTION All declarations at file scope should be static where possible.15 Declarations and Definitions. Origin: Misra Guidelines . AIR VEHICLE. BENEFITS Prevents from accidentally overwriting of functions or variables EXAMPLE int g1. AV Rule 137 . /* Violation */ REPAIR static int g2. JOINT STRIKE FIGHTER. /* OK */ static void foo2(){}. C++ CODING STANDARDS Chapter 4.

// Violation } } REPAIR Do not declare variables simultaneously with internal and external linkage in the same translation unit. void foo( ) { extern unsigned short x. REFERENCES 1. BENEFITS Rule prevents variable-name hiding which can be confusing. static unsigned short y. EXAMPLE static unsigned short x.15 Declarations and Definitions. Origin: Misra Guidelines .Rule 24 2. C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER. AIR VEHICLE. // Violation { extern unsigned short y.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. // Violation extern unsigned short y. AV Rule 138 .

JOINT STRIKE FIGHTER. /* file. C++ CODING STANDARDS Chapter 4. /* Violation */ REPAIR /* file.h */ static int x.c */ #include "file. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. AIR VEHICLE. AV Rule 138 . Section 8 2.c */ #include "file." See also: CODSTA-81 BENEFITS Rule improves good programming style and readability. /* file.h */ static int x.h" static int x.h" extern int x.15 Declarations and Definitions. /* OK */ REFERENCES 1.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. EXAMPLE /* file.

.

Rule 27 2. /* Violation */ /* misra_027.h */ extern int a. Origin: Misra Guidelines . clarity of code and prevents errorneous code.h" extern int a. BENEFITS Rule improves readability. /* OK */ /* misra_027. AV Rule 139 .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. JOINT STRIKE FIGHTER. */ extern int a. This rule will inform about multiple declarations of symbols.15 Declarations and Definitions. REPAIR /* misra_027. AIR VEHICLE. REFERENCES 1.c */ #include "misra_027.h */ /* Do not declare external object in more than one file.c */ #include "misra_027. EXAMPLE /* misra_027.h" int a. C++ CODING STANDARDS Chapter 4.

.

Chapter 6. JOINT STRIKE FIGHTER.1 BENEFITS Rule improves readability of code. // OK } REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. EXAMPLE void foo(long param = 64l) // Violation { const long a = 64l. Rule 2-13-4 .4 Environment.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. C++ CODING STANDARDS Chapter 4. Section 2. AIR VEHICLE. // Violation } REPAIR void foo(long param = 64L) // OK { const long a = 64L. AV Rule 14 2.

.

REFERENCES 1.15 Declarations and Definitions.Do not use register storage class [JSF-140-2] DESCRIPTION The register storage class specifier shall not be used. Origin: Misra Guidelines . C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER. } // Violation REPAIR Do not use the 'register' storage class specifier. BENEFITS Prevents from dependencies on compiler. AV Rule 140 .Rule 28 2. EXAMPLE void foo() { register int a. AIR VEHICLE.

structure. or enumeration will not be declared in the definition of its type. C++ CODING STANDARDS Chapter 4. // Violation REPAIR enum direction_e { up.A class. AV Rule 141 . down }. EXAMPLE enum { up. SINCE v7.1 BENEFITS Rule improves readability. structure. down } direction. or enumeration will not be declared in the definition of its type [JSF-141-3] DESCRIPTION A class.15 Declarations and Definitions. AIR VEHICLE. // OK REFERENCES JOINT STRIKE FIGHTER. direction_e direction.

.

b++. EXAMPLE void foo( ) { int b. INIT-10. "Effective C++: 55 Specific Ways to Improve . INIT-14. BENEFITS Prevents reading from uninitialized variables. } // OK REFERENCES 1. Scott Meyers. This does not necessarily require initialisation at declaration. BD-PB-NOTINIT NOTES The rule assumes that local variable might be initialized by passing its non-const pointer to an external function. b++. } // Violation REPAIR void foo( ) { int b = 0. 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.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.

C++ CODING STANDARDS Chapter 4. Rule 8-5-1 .Your Programs and Design". AIR VEHICLE. Inc. Section 8. Third Edition. Chapter 6. Section 9. AV Rule 142 6.Rule 30 3. Misra Guidelines . (C) 2005 Pearson Education.Rule 40 5. rule 9. Ellemtel Coding Standards http://www.chris-lott.. Chapter 1. JOINT STRIKE FIGHTER.16 Initialization.1 4. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.html#11 From: 11 Variables . Addison-Wesley. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Item 4 2.org/resources/cstyle/Ellemtel-rules-mm.

Initialize all variables [JSF-142_b-2] DESCRIPTION "A variable must always be initialized before use. By always initializing variables. void foo( ) { int b. } // Violation // Violation . Instances of a class are usually initialized even if no arguments are provided in the declaration (the empty constructor is invoked). the compiler gives a warning if a variable is undefined. the keyword extern is always used. non-primitive types. EXAMPLE int a. For objects having large amounts of data." EXCEPTIONS Exception to this rule are 'volatile' data. and arrays. this can result in significantly faster code. To declare a variable that has been initialized in another file. BENEFITS Prevents reading from uninitialized variables. instead of assigning values to them before they are first used. Normally. It is then sufficient to take care of such cases. the code is made more efficient since no temporary objects are created for the initialization.

} // OK // OK REFERENCES 1. AIR VEHICLE.16 Initialization. void foo( ) { int b = 0. General Principles of Software Validation. Inc.html#11 From: 11 Variables .org/resources/cstyle/Ellemtel-rules-mm. Herb Sutter. (C) 2005 Pearson Education.4." AddisonWesley. Chapter: "Coding Style".4 . C++ CODING STANDARDS Chapter 4. 2002 6. AV Rule 142 4.Rule 41 2.org/data/definitions/457. Rule 19 3. "C++ Coding Standards. http://cwe. Andrei Alexandrescu. Ellemtel Coding Standards http://www.REPAIR int a = 0.html 5. JOINT STRIKE FIGHTER.mitre. ISO/DIS 26262 point 8. Final Guidance for Industry and FDA Staff Document issued on: January 11.chris-lott.

Rule reports a violation message if: . void fun_1(int x) { int i.e. // 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 .local variable is prematurely declared and is only used in for loop SINCE v7.1 NOTES Rule is enabled for C++ only. int max=0. there is no variable usage after initialization statement and before new value assignment) . BENEFITS Prevent clients from accessing variables without meaningful values. ++i) { . EXAMPLE int f(int).value assigned to local variable during initialization is not used (i. i<max .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.

General Principles of Software Validation.16 Initialization. AIR VEHICLE. void fun_2(int x) { int max = f(x). i++) // OK { } } REFERENCES 1. AV Rule 143 2. Final Guidance for Industry and FDA Staff Document issued on: January 11. 2002 . // OK: max not introduced until meaningful // value is available for(int i = 0.} } REPAIR int f(int). C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER. i < max.

If this method of initialization is chosen then the first element should be initialized to zero (or NULL). 2. . 4. 6 }. The rule given here goes further in requiring the use of additional braces to indicate nested structures. // Violation struct S { int i." 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. 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. and nested braces need not be used." NOTES Rule checks only up to three-level nested bracket initialization.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. 5. The zero initialization of arrays or structures shall only be applied at the top level. structures and union types to be enclosed in a single pair of braces (though the behaviour if this is not done is undefined). 3. The non-zero initialization of arrays or structures requires an explicit initializer for each element.

Misra Guidelines . }t. MISRA C++:2008 . 2}. AIR VEHICLE. } s = {1. Chapter 6. { 3. 4 }. // OK REFERENCES 1. AV Rule 144 4.Rule 31 3. Rule 8-5-2 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. // OK struct S { int i. 6 } }. 2 }. { 5. Section 8. } s = {1.Guidelines for the use of the C++ language in critical systems. struct T { int j.16 Initialization. }t. JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4. { 2 }}. // Violation REPAIR int y[3][2] = { { 1.struct T { int j. Section 9 2.

unless all items are explicitly initialized. Z2. }. Z3 = 3. enum TEST3 { /* Violation */ X3. Y. }. the '=' construct shall not be used to explicitly initialize members other than the first." BENEFITS Helps avoid errors and confusion. enum TEST2 { /* Violation */ X2. unless all items are explicitly initialised [JSF-145-2] DESCRIPTION "In enumerator list. Y2 = 2. }.In an enumerator list. Y3. the "=" construct shall not be used to explicitly initialise members other than the first. EXAMPLE enum TEST { /* Violation */ X = 1. }. Z. Z = 3. Y. . REPAIR enum TEST { /* OK */ X.

}. Z3 = 3. MISRA C++:2008 . Y3 = 2. Chapter 6. enum TEST3 { /* OK */ X3 = 1. REFERENCES 1. Section 8. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.enum TEST2 { /* OK */ X2 = 1. Origin: Misra Guidelines .Guidelines for the use of the C++ language in critical systems. Section 9 2. Z2. Y2. Rule 8-5-3 .Rule 32 3. }.

short int* ps.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. double* pd. /* /* /* /* Violation Violation Violation Violation } REPAIR void foo() { int* pi. BENEFITS Prevents from casting with possible data losing. float* pf. EXAMPLE void foo() { int* pi. (int*)pd. (long*)pf. } /* OK */ /* OK */ */ */ */ */ . float* pf. double* pd. pf = (float*)pd. ps = (short*)pi. short int* ps. long * pl. (short*)pf. pi pi ps pl = = = = (int*)pf.

AIR VEHICLE.17 Types.Rule 16 2. AV Rule 147 . Origin: Misra Guidelines .REFERENCES 1. C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER.

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. // Violation // Violation // Violation .1 EXCEPTIONS This rule is not intended to exclude character constants (e. 'A'. SINCE v7. 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.) from use as case labels. case 2: break. 'B' etc. Rule reports a violation message if integer types (constants) are used as case labels. BENEFITS Enhances debugging. case 3: break.g.

C++ CODING STANDARDS Chapter 4. } } REPAIR enum color { RED = 1. case BLUE: break . case GREEN: break.default: break. void foo(int color) { switch(color) { case RED: break. BLUE = 2.18 Constants. AIR VEHICLE. GREEN = 3 }. default: break. } } // OK // OK // OK REFERENCES JOINT STRIKE FIGHTER. AV Rule 148 .

strictly speaking. EXAMPLE void foo() { int code1. but is a permitted exception to this rule." EXCEPTIONS Rule ignores any #pragma parasoft / codewizard directives. It is better not to use octal constants or escape sequences at all and to statically check for any occurrences. Rule prevents using implementation-defined values. with writing fixed length constants. int code2. for example. /* Violation */ } REPAIR void foo1() . int code3. an octal constant. BENEFITS Rule increases readability and maintainability. So there is a danger. Rule ignores any values inside asm blocks. The integer constant zero (written as a single numeric digit) is. code1 = 052. /* Violation */ code2 = 071. Octal escape sequences can be problematic because the inadvertent introduction of a decimal digit ends the octal escape and introduces another character. Additionally \0 is the only permitted octal escape sequence. /* Violation */ code3 = '\100'.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.

{ int code1. /* OK */ /* OK */ /* OK */ } REFERENCES 1. code2 = 57. int code2. Chapter 6. code3 = 64. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. AIR VEHICLE.Rule 19 3. JOINT STRIKE FIGHTER. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 2-13-2 . code1 = 42. C++ CODING STANDARDS Chapter 4. int code3. Section 2. Section 7 2. Origin: Misra Guidelines .18 Constants. AV Rule 149 4.

C++ CODING STANDARDS Chapter 4. Rule 2-13-4 . Section 2.Hexadecimal constants will be represented using all uppercase letters [JSF-150-3] DESCRIPTION Hexadecimal constants will be represented using all uppercase letters. Chapter 6.1 BENEFITS Improved readability and maintenance. AV Rule 150 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.18 Constants. AIR VEHICLE. EXAMPLE int i = 0x3fff. // Violation REPAIR int i = 0x3FFF. See also: CODSTA-51 SINCE v7. JOINT STRIKE FIGHTER. // OK REFERENCES 1.

BENEFITS Rule improves readability and maintainability. Use symbolic values instead. int foo( int a[]. // OK void boo(int). // OK int i = 5. // Violation boo(56). float b ) { int e. int foo( float a[]. int b ) { int e. int f = 0. We also skip usage of 0 or 1 because they are equivalent of true or false. int f = 0. They are not self-explanatory.Avoid magic numbers [JSF-151-3] DESCRIPTION Avoid spelling literal constants in code. // OK . // Violation return 8. // Violation e= 8. a[5] = 56. EXAMPLE void boo(int). // Violation } REPAIR const int MAX = 8. See also: CODSTA-29 NOTES We excluded using literal constants in initialization.

JOINT STRIKE FIGHTER. "C++ Coding Standards. Herb Sutter. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. return MAX. Andrei Alexandrescu. boo(a[5])." AddisonWesley. e = MAX. (C) 2005 Pearson Education. Inc.18 Constants. Chapter: "Coding Style". AV Rule 151 . // // // // OK OK OK OK } REFERENCES 1.a[i] = MAX. Rule 17 2.

} // Violation // Violation // Violation // Violation // Violation REPAIR void moo(const char * p) { } void foo() { . EXAMPLE void moo(char * p) { } void foo() { char* c1 = "Hello". SINCE v7. moo("Hello").1-2] DESCRIPTION A string literal shall not be modified. char c2[] = "Hello". parameter or expression.1 BENEFITS The effect of attempting to modify a string literal is undefined. char c3[6] = "Hello". char* c12. Rule reports violations if a string literal is assigned to non-const variable.A string literal shall not be modified [JSF-151. c12 = "Hello".

General Principles of Software Validation. c12 = "Hello". AIR VEHICLE. const char* c12. JOINT STRIKE FIGHTER. } // OK // OK // OK // OK // OK REFERENCES 1. C++ CODING STANDARDS Chapter 4. const char c3[6] = "Hello".18 Constants.1 2. const char c2[] = "Hello". 2002 . AV Rule 151. moo("Hello").const char* c1 = "Hello". Final Guidance for Industry and FDA Staff Document issued on: January 11.

AIR VEHICLE. BENEFITS Rule increases readability and prevents confusion. C++ CODING STANDARDS Chapter 4. EXAMPLE void foo( ) { int a.19 Variables. AV Rule 152 .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. } // OK // OK REFERENCES JOINT STRIKE FIGHTER. See also: FORMAT-33 NOTES Violation is not reported if variables are declared by macros. int b. } // Violation REPAIR void foo( ) { int a. b.

REPAIR Do not use union.Unions shall not be used [JSF-153-2] DESCRIPTION "Even when memory is being reused for related purposes. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. char _buf[ sizeof( int ) ]. this rule prohibits the use of unions for any purpose. Inc. Rule 97 3. Chapter: "Type Safety". BENEFITS Rule prevents undefined behaviour and erroneous code. Therefore. EXAMPLE union U { /* Violation */ int _i.Rule 109 . Section 18 2. Origin: Misra Guidelines ." AddisonWesley. "C++ Coding Standards. Andrei Alexandrescu. Herb Sutter. }. REFERENCES 1. (C) 2005 Pearson Education." Note: Rule reports a violation message on each union's declaration. there is still a risk that the data may be misinterpreted.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 9-5-1 .20 Unions and Bit Fields.4. Section 9. Chapter 6. JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. AV Rule 153 5.

f2:2. f3:2. unsigned long f3:2. short or char types for bit fields is not allowed because the behaviour is undefined.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. f5:2. REFERENCES f1:2." BENEFITS Prevents implementation-defined behaviour. EXAMPLE enum Enum { E1. int f5:2. /* /* /* /* /* Violation Violation Violation Violation Violation REPAIR struct Struct { unsigned int unsigned int unsigned int signed int signed int }. enum Enum f4:2. E2}. unsigned short f2:2. The use of enum. f4:2. struct Struct { unsigned char f1:2. /* /* /* /* /* OK OK OK OK OK */ */ */ */ */ */ */ */ */ */ . }.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4.20 Unions and Bit Fields.1. AIR VEHICLE. Origin: Misra Guidelines .Rule 111 3. Section 6 2. AV Rule 154 .

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. EXAMPLE typedef signed int t. in larger data-types. or group of bits. typedef int plain. This rules checks that all declared bit fields have names.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. BENEFITS Prevents using unaccessible data. /* Violation */ plain r:5. in conjunction with unions (see rule 110). struct tag { unsigned t:4. Provided the elements of the structure are only ever accessed by their name. }. REPAIR . the programmer needs to make no assumptions about the way the bit fields are stored within the structure. There are two main uses to which bit-fields could be put: 1) To access individual bits. const t:5.

C++ CODING STANDARDS Chapter 4. AV Rule 156 . JOINT STRIKE FIGHTER. Origin: Misra Guidelines rule 113 2. REFERENCES 1.21 Operators.Name all the members of a structure (or union). AIR VEHICLE.

which cause changes in the state of the execution environment of the calling function. int j. The operations that cause side effects are accessing a volatile object. or calling a function that does any of those operations. if ((j == i) || (0 == i++)) . 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. EXAMPLE void foo( ) { int i." See also: MISRA2004-12_2_a. MISRA2004-12_4_b NOTES Rule checks only three nested level of function calls. If these sub-expressions contain side effects then those side effects may or may not occur.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. modifying an object. BENEFITS Rule prevents conditional evaluation of the right-hand operand that can easily cause problems if the developer relies on a side effect occurring. // Violation } REPAIR . modifying a file.

Section 5. JOINT STRIKE FIGHTER.4 . MISRA C++:2008 . Chapter 6. Section 12 2. int j.void foo( ) { int i. Origin: Misra Guidelines . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. AIR VEHICLE.Rule 33 3. C++ CODING STANDARDS Chapter 4. // OK } REFERENCES 1. AV Rule 157 4.21 Operators. if ((j == i) || (0 == i)) i++.4.Guidelines for the use of the C++ language in critical systems. Rule 5-14-1 5. ISO/DIS 26262 point 8.

int y. BENEFITS "The effect of this rule is to require that operands are appropriately parenthesized. // Violation if ( x && !y ). // OK // OK . int y. if ( x && ( !y ) ). int z ) { if ( x || ( y && z ) ). // Violation return 0." See also: MISRA2004-12_1_e. } REPAIR int foo( int x. "Parentheses are important in this situation both for readability of code and for ensuring that the behaviour is as the developer intended. constant or function call is not parenthesised." EXAMPLE int foo( int x. extra parentheses are not required. int z ) { if ( x || y && z ).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. MISRA2004-12_5 SINCE v7.3 EXCEPTIONS "Where an expression consists of either a sequence of only logical '&&' or a sequence of only logical '||'.

} REFERENCES 1. MISRA C++:2008 . Chapter 6.21 Operators.Guidelines for the use of the C++ language in critical systems. AIR VEHICLE. Rule 5-2-1 2. AV Rule 158 . C++ CODING STANDARDS Chapter 4.return 0. JOINT STRIKE FIGHTER. Section 5.

}. and this is a sure way to introduce subtle bugs and fragilities. || or . int operator&&( A& lhs. (comma) enjoy special treatment from the compiler.(comma). . resulting in unpredictable program behavior. int value( ) { return _i. BENEFITS Overloading these operators changes the way the compiler reads the semantics of an expression." This rule detects when you overload operator &&. A& rhs ) { return lhs. (comma) [JSF-159-2] DESCRIPTION "The built-in &&. they become ordinary functions with very different semantics. If you overload them.(comma). || or . || or .Avoid overloading &&. EXAMPLE class A { public: A( int i ) : _i( i ) {} ~A( ). || or.value( ) && rhs. REFERENCES 1. Herb Sutter. } private: int _i. Andrei Alexandrescu. } // Violation REPAIR Do not overload operator &&." AddisonWesley.value( ). "C++ Coding Standards.

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

and assists the static detection of mistakes. int y. However. 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." 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. EXAMPLE void foo() { int x. z = !(x = y). Boolean values are expected in the following contexts: .the first operand of the conditional operator ? BENEFITS Rule prevents getting "=" and "==" confused. int z. // Violation // Violation . This precludes the use of both simple and compound assignment operators in the operands of a Boolean-valued expression.the controlling expression of an iteration statement .the controlling expression of an if statement . it does not preclude assigning a Boolean value to a variable.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. if ((x > y) && (x = 4)).

Rule 6-2-1 . // OK } REFERENCES 1.Guidelines for the use of the C++ language in critical systems. AIR VEHICLE. Section 13 3. int y.21 Operators. Chapter 6. Section 6. MISRA C++:2008 .if (!(x = y)). // Violation } REPAIR void foo() { int x.Rule 35 2. JOINT STRIKE FIGHTER. z = !(x == y). C++ CODING STANDARDS Chapter 4. Misra Guidelines . int z. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. AV Rule 160 4. // OK if ((x > y) && (x == 4)). // OK if (!(x == y)).

u32b. /* Violation */ /* Violation */ } REPAIR void Conv1_int( ) { unsigned int u32a. /* OK */ . 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.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." EXAMPLE void Conv1_int( ) { unsigned int u32a.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. s32a = (signed int)u32a. s32b. SINCE v7. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. signed int s32a. signed int s32a. s32b. u32b." Rule checks if implicit conversions between signed and unsigned types are used. s32a = u32a. s32b = s32a + u32a.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. ISO/DIS 26262 point 8. Section 5.4. Section 10 2.s32b = s32a + (signed int)u32b. /* OK */ } REFERENCES 1.4 . Rule 5-0-4 3. Chapter 6.

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. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. } /* OK */ . } /* Violation */ REPAIR void Conv1_int( ) { unsigned int u32a. signed int s32a = (signed int)u32a." EXAMPLE void Conv1_int( ) { unsigned int u32a." Rule checks if implicit conversions between signed and unsigned types are used when variables are initialized. signed int s32a = u32a. SINCE v7.

Section 10 2. Chapter 6.4 . ISO/DIS 26262 point 8. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Rule 5-0-4 3. Section 5.REFERENCES 1.

'/='. '-'. '|='.chris-lott.Rule 48 . The following binary arithmetic operators are checked: '+'." 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. 8 2. unsigned char b) { unsigned char c = a + b. '|'.Port.18. '&='. '/'. Misra Guidelines . '^'. '%='.3 Type Conversions . EXAMPLE void foo(signed char a. '<<'. '>>'. '+='. '<<=' BENEFITS Complying with this rule leads to safer and more readable code. } // OK REFERENCES 1. } // Violation REPAIR void foo(signed char a.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.org/resources/cstyle/Ellemtel-rules-mm.html From: 18 Portable Code . Ellemtel Coding Standards http://www. Rec. '*'. '>>='. unsigned char b) { unsigned char c = (unsigned char)a + b.

3. AIR VEHICLE.21 Operators. AV Rule 162 . C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER.

Unsigned arithmetic shall not be used [JSF-163-2] DESCRIPTION Unsigned arithmetic shall not be used. int b = 0. b = p + a. SINCE v7. 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. b = p + a. } // OK . int b = 0. EXAMPLE void foo(unsigned p) { unsigned int a = 0.1 BENEFITS Over time. // Violation } REPAIR void foo(signed p) { signed int a = 0. Rule reports a violation message if type of arithmetic expression operand is unsigned type.

21 Operators. C++ CODING STANDARDS Chapter 4.REFERENCES JOINT STRIKE FIGHTER. AIR VEHICLE. AV Rule 163 .

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). 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). BENEFITS Rule makes the code more readable and less confusing. for example. the left-hand operand of a left-shift or right-shift is a 16-bit integer.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. EXAMPLE typedef unsigned char typedef unsigned short void foo( uint16_t p ) uint8_t." The rule checks right-hand operand of shift operator and reports a violation in following cases: . .the operand is a non-const variable and it's value is not checked by specific pattern. then it is important to ensure that this is shifted only by a number between 0 and 15 inclusive.the operand is a constant with negative value or with value that exceeds the length (in bits) of the left-hand operand . 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). Otherwise both limits will need to be checked. uint16_t.

u16a = (uint16_t) ((uint16_t) u8a << 9).21 Operators. Section 12 2. Chapter 6. /* OK */ if (p >= 0 && p <= 8) { u8a = (uint8_t) (u8a << p). uint8_t.p range checked */ } u8a = (uint8_t) (u8a << 4). /* OK . /* Violation */ } REPAIR typedef unsigned char typedef unsigned short void foo( uint16_t p ) { uint8_t u8a. JOINT STRIKE FIGHTER. MISRA C++:2008 . Section 5. uint16_t. AIR VEHICLE. C++ CODING STANDARDS Chapter 4.Guidelines for the use of the C++ language in critical systems. /* OK . u8a = (uint8_t) (u8a << 9). /* Violation */ u8a = (uint8_t) (u8a << p). AV Rule 164 3.{ uint8_t u8a. uint16_t u16a. Rule 5-8-1 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.constant value in range */ } REFERENCES 1.

-100u >> 5. if e1 has a signed type and a negative value. variable. signed_variable >> 5. int variable.1-2] DESCRIPTION The rule reports a violation message if as left-hand operand of rightshift operator is used one from the following options: .The left-hand operand of a right-shift operator shall not have a negative value [JSF-164. signed int* ptr_signed_variable.constant with a negative value .expression of signed type that contains parameter. -100 >> 5. dereferenced pointer or function call of signed type SINCE v7. *ptr_signed_variable >> 5. "For e1 >> e2.unary operator '-' followed by parameter. the value of (e1 >> e2) is implementation-defined. -variable >> 5.parameter or variable of signed type ." EXAMPLE void foo(signed int signed_param) { signed int signed_variable. } // // // // // // Violation Violation Violation Violation Violation Violation .1 BENEFITS Rule prevents implementation-defined behaviours. variable or expression . signed_param >> 5.

General Principles of Software Validation. 100 >> 5. JOINT STRIKE FIGHTER. 100u >> 5. AIR VEHICLE.1 2. unsigned int* ptr_signed_variable. (unsigned int)variable >> 5.REPAIR void foo(unsigned int unsigned_param) { unsigned int unsigned_variable. 2002 . C++ CODING STANDARDS Chapter 4. unsigned_variable >> 5.21 Operators. unsigned_param >> 5. Final Guidance for Industry and FDA Staff Document issued on: January 11. AV Rule 164. // // // // // // OK OK OK OK OK OK } REFERENCES 1. *ptr_signed_variable >> 5. int variable.

si2 = -ui1. Applying unary minus to an operand of smaller unsigned integer type may generate a meaningful signed result due to integral promotion. signed short si2. Section 12 . signed short si2. but this is not good practice. si2 = -(signed short) ui1. } // OK REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. } // Violation REPAIR void foo() { unsigned char ui1. EXAMPLE void foo() { unsigned char ui1.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." BENEFITS Prevents unexpected result due to integral promotion.

Chapter 6. AIR VEHICLE. JOINT STRIKE FIGHTER. Section 5.Guidelines for the use of the C++ language in critical systems. AV Rule 165 4.2.21 Operators.Rule 39 3. C++ CODING STANDARDS Chapter 4. Origin: Misra Guidelines . Rule 5-3-2 . MISRA C++:2008 .

" NOTES Rule checks only three nested level of function calls. modifying a file. sizeof shall not be used on expressions that contain side effects. EXCEPTIONS An operand of the form sizeof(i) where i is volatile is permitted. EXAMPLE int glob. k. modifying an object. To avoid this error. which cause changes in the state of the execution environment of the calling function.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. l. or calling a function that does any of those operations. . int fun_with_se(){ glob++. as the side effects will not occur. m. // side-effect return glob." "The operations that cause side effects are accessing a volatile object. BENEFITS Prevents error that are caused by believing that operand of sizeof is evaluated. } void foo1(int i){ int j.

// Violation . o.j = sizeof(k = 2). k. m. // Violation . // examples of correct code m = sizeof(fun_without_se()).volatile objects are permitted REFERENCES 1.k is not set to 2 l = sizeof(i++). j = sizeof(k). MISRA C++:2008 . // Violation . l.i is not incremented m = sizeof(fun_with_se()). volatile int vol.21 Operators. } // OK // OK // OK // OK // OK . n. C++ CODING STANDARDS Chapter 4. Section 12 2. AV Rule 166 4. JOINT STRIKE FIGHTER. Section 5. Origin: Misra Guidelines .Guidelines for the use of the C++ language in critical systems. o = sizeof(vol). l = sizeof(i). AIR VEHICLE.Rule 40 3. Chapter 6. k = 2.glob is not incremented } REPAIR int fun_without_se(){ // no side-effect return 1. Rule 5-3-4 . i++. } void foo1(int i){ int j. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. n = sizeof(int).

} REFERENCES 1. /* OK . int k. int k.comment before integer division */ k=i/j.Rule 41 . This rule checks that. /* Violation . Origin: Misra Guidelines .Document integer division [JSF-167-2] DESCRIPTION The implementation of integer division in the chosen compiler should be determined. EXAMPLE void foo() { int i=2. k=j/i. int j=3. documented and taken into account.no comment before division*/ } REPAIR void boo() { int i=2. BENEFITS Prevents unexpected loss of data/precision. wherever there is an integer division in the code. there must be comment on the previous line. int j=3.

JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4. AV Rule 167 .2. AIR VEHICLE.21 Operators.

for (i = 0. int y ) { int i. y++. for (i = 0. int y ) { int i. y + 2). and the same effect can be achieved by other means" See also: misra2004-12_10 BENEFITS Extensive use of comma operator reduces readability. y = 0). y ). } } // Violation // Violation // Violation REPAIR void foo2( int x. i = (x = 1. i++){ foo1( (x--. i < 10. y++. y ). i < 10. x++. i++){ } x--. x++. EXAMPLE void foo1( int x. foo2( y + 2. 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. i >=0. } // OK // OK // OK .The comma operator shall not be used.

AIR VEHICLE. AV Rule 168 .21 Operators.Rule 42 2. C++ CODING STANDARDS Chapter 4. Origin: Misra Guidelines .REFERENCES 1. JOINT STRIKE FIGHTER.

Chapter 6.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. y. y = 0. x = 0. and the same effect can be achieved by other means. Section 5." See also: misra-042 BENEFITS Rule improves readability and maintainability. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. EXAMPLE void foo() { int x. Rule 5-18-1 . y. x = 0. } // Violation REPAIR void foo() { int x. y = 0. Section 12 2. } // OK REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.

Ellemtel Coding Standards http://www." EXCEPTIONS "One exception to this rule is represented by functions which provide interfaces to other languages (such as C).html#12 From: 12 Pointers and References .chris-lott.Pointers to pointers should be avoided whenever possible [JSF-169-4] DESCRIPTION This rule detects if code uses pointers to pointers. By improving the readability of code. declare a class that has a member variable of the pointer type. in which case pointers to pointers are needed." BENEFITS Rule improves the readability of the code and encourages data abstraction.Rec. 48 . the probability of failure is reduced.org/resources/cstyle/Ellemtel-rules-mm. REFERENCES 1. "Pointers to pointers should whenever possible be avoided. EXAMPLE void foo() { int** a. // Violation } REPAIR Instead. which must have the type char*[]. Another example is the second argument to the main function. These are likely to only allow pre-defined data types to be used as arguments in the interface.

22 Pointers & References. JOINT STRIKE FIGHTER. AIR VEHICLE.4.2. AV Rule 169 3. C++ CODING STANDARDS Chapter 4.4 . ISO/DIS 26262 point 8.

as a result it shall not be used. but which in practice is poorly defined by the standard. } /* Violation */ /* Violation */ REPAIR Do not use errno.h> int err_check( ) { errno = 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.5 Libraries.The error indicator errno shall not be used [JSF-17-2] DESCRIPTION "errno is a facility of C and C++. Origin: Misra Guidelines . return (errno). REFERENCES 1. Even for those functions for which the behaviour of errno is well defined. which in theory should be useful. C++ CODING STANDARDS Chapter 4. A non zero value may or may not indicate that a problem has occurred.Rule 119 3. AIR VEHICLE. Section 20 2. 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. AV Rule 17 . EXAMPLE #include <errno. JOINT STRIKE FIGHTER.

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

int ** (***pfunc3)(). int *** ( **pfunc4)(). int *** par3. }. Any explicitly calculated pointer value has the potential to access unintended or invalid memory addresses. EXAMPLE typedef int * INTPTR. This rule bans the explicit calculation of pointer values. BENEFITS Rule improves safety of the code. because it is clearer and hence less error prone than pointer manipulation. struct s { int *** s3." NOTES Array type with unspecified length is treat as a pointer. void function( int * par1.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. Array indexing shall only be applied to objects defined as an array type. Pointers may go out of bounds of arrays or structures. or may even point to effectively arbitrary locations. struct s *** ps3. INTPTR * const * const par5 ) { /* Violation */ /* Violation */ /* Violation */ /* Violation */ /* Violation */ /* Violation */ .

Chapter 6. AIR VEHICLE. Origin: Misra Guidelines .4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. JOINT STRIKE FIGHTER. ISO/DIS 26262 point 8. Rule 5-0-19 4. C++ CODING STANDARDS Chapter 4.4 .22 Pointers & References. AV Rule 170 3. /* Violation */ } REPAIR Do not declare more than two levels of pointer indirection. Section 17 2.Rule 102 5. REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 5.int *** ptr3. /* Violation */ INTPTR * const * const ptr5 = 0.

MISRA-C:2004 Guidelines for the use of the C language in critical systems . Any explicitly calculated pointer value has the potential to access unintended or invalid memory addresses. /* Violation */ REPAIR Do not declare more than two levels of pointer indirection. Pointers may go out of bounds of arrays or structures. or may even point to effectively arbitrary locations. This rule bans the explicit calculation of pointer values. Array indexing shall only be applied to objects defined as an array type.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." NOTES Array type with unspecified length is treat as a pointer. because it is clearer and hence less error prone than pointer manipulation. apInt* rule12. EXAMPLE typedef int* apInt[] . BENEFITS Rule improves safety of the code. REFERENCES 1.

Origin: Misra Guidelines . Section 17 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.Rule 102 5. Rule 5-0-19 4. AIR VEHICLE. AV Rule 170 3.Chapter 6. Chapter 6.4. Section 5.22 Pointers & References. ISO/DIS 26262 point 8. C++ CODING STANDARDS Chapter 4.4 . JOINT STRIKE FIGHTER.

For example: void foo( ) { int a[10].* p3. a. i p1.false positive .* p4. For such cases the rule may report false positives." EXCEPTIONS "Both operands are of the same type and point to the same array" BENEFITS Rule makes the code more readable and less confusing.* p5. p1 p2 p3 p4 p5 } = = = = = a." NOTES "It is permissible to address the next element beyond the end of an array.>. 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.* p2. int* p1. // // // // // OK OK OK Violation . a.i p4. i.false positive Violation .i = = = = = p1 p2 p3 p4 p5 < < < < < a. >=. <.i p2.i p3. a. <= 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. a. but accessing this element is not allowed.

AV Rule 171 4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. i = p2 < a. i = p1 < p2. Chapter 6.Rule 103 3. int* p2. int i.EXAMPLE void foo( int a[] ) { int* p1 = 0. AIR VEHICLE. Origin: Misra Guidelines . i = p3 < a. Section 5. Section 17 2.22 Pointers & References. Rule 5-0-18 . C++ CODING STANDARDS Chapter 4. // Violation // Violation // OK } REPAIR Do not apply pointer comparison to pointers that address elements of different arrays REFERENCES 1. JOINT STRIKE FIGHTER. int* p3 = a.

return (&local_auto). }" BENEFITS Prevents loss of data EXAMPLE int* global. siLocal = &iLocal. } } // Violation // Violation // Violation // Violation . 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). piLocal = &iiLocal. int* foo() { int iLocal. static int* siLocal. global = &iLocal. or to a static object. } void goo() { int* piLocal. For example: int * foo( void ) { int local_auto. return &iLocal. { int iiLocal.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.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.22 Pointers & References. Chapter 6. JOINT STRIKE FIGHTER. Section 17 2. or static object or return from function. Origin: Misra Guidelines . AV Rule 173 4. REFERENCES 1.Rule 106 3.REPAIR Do not assign local address of object to more global. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. AIR VEHICLE. Rule 7-5-2 . C++ CODING STANDARDS Chapter 4. Section 7.

EXAMPLE int* ret_ptr(int* p){ return p. /* Violation . 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. /* here pointer 'ptr' should be checked */ i = *ptr." If a control statement contains in condition non-dereferenced pointer.pointer 'ptr' may be null */ } REPAIR int* ret_ptr(int* p){ return p.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. ptr = ret_ptr(par). } void func(int i. BD-PB-NP BENEFITS Complying with this rule leads to safer code. . int* par){ int* ptr. } int check(int* p){ if(p == 0) return 0. See also: MISRA-107_b. then the rule assumes that this pointer is checked. the program should first check that the pointer is not NULL.

BD-PB-NP */ } .pointer 'ptr' was checked in 'if' condition */ } void func3(int i. int* par){ int* ptr.if(p > 0) return 1. ptr = ret_ptr(par). /* OK . The 'if' condition is not correct. ptr = ret_ptr(par). } void func1(int i. int* par){ int* ptr. /* OK .pointer 'ptr' was checked in 'if' condition */ } } void func2(int i. ptr = ret_ptr(par).pointer 'ptr' was checked in 'check' function */ } } void func4(int i. int* par){ int* ptr. /* OK . } i = *ptr. if(ptr == 0){ i = *ptr. To detect this issue could be used Bug Detectiv rule .pointer 'ptr' was checked in 'if' condition. if(!ptr){ return. /* OK . but the rule does not check such cases. ptr = ret_ptr(par). int* par){ int* ptr. if(ptr){ i = *ptr. if(check(ptr)){ i = *ptr.

} REFERENCES 1.4. JOINT STRIKE FIGHTER.html 4. http://cwe.22 Pointers & References.mitre. AIR VEHICLE.Rule 107 2.org/data/definitions/476. Origin: Misra Guidelines . AV Rule 174 3. ISO/DIS 26262 point 8.4 . C++ CODING STANDARDS Chapter 4.

/* here pointer 's' should be checked */ s->si = i. BD-PB-NP BENEFITS Complying with this rule leads to safer code. the program should first check that the pointer is not NULL. struct S* ret_ptr(struct S* p){ return p. s = ret_ptr(ptr). struct S* ptr.pointer 's' may be null */ } REPAIR struct S{ int si. /* Violation .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. EXAMPLE struct S{ int si. 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. then the rule assumes that this pointer is checked. }." If a control statement contains in condition non-dereferenced pointer. } void func(int i){ struct S* s.

if(!s){ return. s = ret_ptr(ptr). /* OK . s = ret_ptr(ptr). s = ret_ptr(ptr). struct S* ptr. struct S* ptr.pointer 's' was checked in 'if' condition */ } void func3(int i){ struct S* s. /* OK .pointer 's' was checked in 'if' condition */ } } void func2(int i){ struct S* s. if(p > 0) return 1. } void func1(int i){ struct S* s. struct S* ret_ptr(struct S* p){ return p.pointer 's' was checked in 'check' function */ } . } s->si = i. /* OK . if(check(s)){ s->si = i. } int check(struct S* p){ if(p == 0) return 0.}. struct S* ptr. if(s){ s->si = i.

22 Pointers & References. if(s == 0){ s->si = i. Origin: Misra Guidelines . JOINT STRIKE FIGHTER. struct S* ptr. AV Rule 174 3.BD-PB-NP */ } } REFERENCES 1. but the rule does not check such cases.4 .org/data/definitions/476. http://cwe.} void func4(int i){ struct S* s. ISO/DIS 26262 point 8. s = ret_ptr(ptr). The 'if' condition is not correct.4.Rule 107 2. AIR VEHICLE.mitre.pointer 's' was checked in 'if' condition. /* OK . To detect this issue could be used Bug Detectiv rule .html 4. C++ CODING STANDARDS Chapter 4.

"Do not compare a pointer to NULL or assign NULL to a pointer. AIR VEHICLE." BENEFITS According to the ANSI-C standard. Ellemtel Coding Standards http://www.org/resources/cstyle/Ellemtel-rules-mm. AV Rule 175 . it cannot be assigned an arbitrary pointer without an explicit type conversion. problems may arise.Do not compare a pointer to NULL or assign NULL to a pointer.h> void foo( ) { int *lp = NULL.22 Pointers & References. JOINT STRIKE FIGHTER.chris-lott. EXAMPLE #include <stddef. // OK } REFERENCES 1. If this definition remains in ANSI-C++. If NULL is defined to have the type void*. C++ CODING STANDARDS Chapter 4. use 0 instead. use 0 instead [JSF-175-2] DESCRIPTION This rule detects code that compares a pointer to NULL or assigns NULL to a pointer.html From: 12 Pointers and References .Rule 42 2. NULL is defined either as (void*)0 or as 0.h> void foo( ) { int *lp = 0. // Violation } REPAIR #include <stddef.

.

By making a type declaration for the function type. JOINT STRIKE FIGHTER. this is avoided.html From: 12 Pointers and References . AIR VEHICLE. // Violation REPAIR typedef void (*PTF)()." EXAMPLE void (*p)().22 Pointers & References. AV Rule 176 . PTF p. // OK REFERENCES 1. C++ CODING STANDARDS Chapter 4. If pointers to functions are used." BENEFITS "Another reason to use typedef is that the readability of the code is improved.org/resources/cstyle/Ellemtel-rules-mm.Rec. Ellemtel Coding Standards http://www.chris-lott. 49 2.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. the resulting code can be almost unreadable.

and in the worst. }. // Violation void foo(){ A a. allow the most meaningless code to compile. void foo(){ A a. In the latter case. // implicit conversion } REPAIR class A { public: const char* asPointerToConstChar( ) const.Do not use user-defined conversion functions [JSF-177-4] DESCRIPTION Be wary of user-defined conversion functions. // OK }. . This rule warns you when it finds user-defined conversion functions. See also: CODSTA-CPP-04 BENEFITS Generally improves runtime performance and predictability of program behavior. const char* ch_ptr = a. EXAMPLE class A { public: operator const char*( ) const. Such calls may in the best case result in creating and destroying temporary objects. affecting runtime. May detect severe coding defects masked by the compiler. problems that could be detected at compile time are pushed to run-time testing.

"C++ Coding Standards.const char* ch_ptr = a. "More Effective C++: 35 New Ways to Improve Your Programs and Designs". Chapter: "Operators". Copyright 1996. Chapter: "Class Design and Inheritance". // explicit conversion } REFERENCES 1. JOINT STRIKE FIGHTER. Andrei Alexandrescu. AIR VEHICLE. Scott Meyers." AddisonWesley. Item 5 2.23 Type Conversions. Herb Sutter. Rule 40 3. (C) 2005 Pearson Education. Inc. C++ CODING STANDARDS Chapter 4. Addison-Wesley. AV Rule 177 .asPointerToConstChar().

void foo() { Base *pb. This rule detects casts from a base class pointer to a subclass pointer. EXAMPLE class Base {}. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". Inc. . BENEFITS Allowing casts down the inheritance hierarchy leads to maintenance problems. void foo() { Base *pb0. class Derived: public Base {}. class Derived2: public Derived {}. } // OK REFERENCES 1. Derived *pd2 = (Derived2 *) pb2. // Violation // Violation } REPAIR class Base {}. Derived *pd = (Derived *) pb. (C) 2005 Pearson Education.Avoid casts down the inheritance hierarchy [JSF-178-2] DESCRIPTION Avoid casts down the inheritance hierarchy.. Base *pd0 = (Base *) pb0. Base *pb2. and downcasting from a base class is always illegal. Scott Meyers. Addison-Wesley. Second Edition.

AIR VEHICLE. JOINT STRIKE FIGHTER. Item 39 2. C++ CODING STANDARDS Chapter 4.23 Type Conversions. AV Rule 178 .Chapter: "Inheritance and Object-Oriented Design".

referenced through a virtual base pointer.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. using any means other than dynamic_cast has undefined behaviour. B *pB = &d. D *pD = static_cast<D*>(pB)." "Casting from a virtual base to a derived class. The behaviour for dynamic_cast is defined. EXAMPLE // The code is not compilable with all compilers class B { public: virtual int foo(). void fun(){ D d. the layout of a derived class object. }. is unknown at compile time. class D: public virtual B { public: virtual int foo(){} }. OOP-49 SINCE v7.2 BENEFITS Rule prevents undefined behaviours." See also: OOP-29. // Violation } REPAIR .

C++ CODING STANDARDS Chapter 4. Section 5. JOINT STRIKE FIGHTER.23 Type Conversions. AIR VEHICLE. class D: public virtual B { public: virtual int foo(){} }. } // OK REFERENCES 1. Rule 5-2-2 . }. D *pD = dynamic_cast<D*>(pB).class B { public: virtual int foo(). void fun(){ D d. B *pB = &d. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems Chapter 6. AV Rule 179 2.

}. int main( ) { int i = offsetof( struct S. Section 20 . } REPAIR Do not use offsetof.The macro offsetof. buffer ).The macro offsetof shall not be used. Macro is in line: [10] #include <stddef. EXAMPLE // Violation . or cstddef.h> struct S { int x. 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.h. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. return 0. stddef. char buffer[ 128 ]. z. y.h. REFERENCES 1. in library stddef." Rule reports a violation message if the offsetof macro is used and the file includes any of the following headers: stddef. BENEFITS Rule prevents undefined behaviour.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. AV Rule 18 4. Rule 18-2-1 . AIR VEHICLE. Chapter 6. JOINT STRIKE FIGHTER. Origin: Misra Guidelines .5 Libraries.2. Section 18. C++ CODING STANDARDS Chapter 4.Rule 120 3.

between signed and unsigned type . PORT-27. then the programmer should be aware .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. Some of these conversions can result in loss of information. EXCEPTIONS The rule does not report violation if a conversion is used: . 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.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.between integral and floating type .on a constant expression . but explicit casts should be used instead. Such implicit conversions shall not be used." 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. so as to harmonize types within an expression before evaluating it. MISRA2004-10_2.

only signed/unsigned conversion */ float f = ui. /* OK . /* Violation f = d. /* Violation us1 = us2 + us2. and should provide appropriate checking of values in the code" EXAMPLE void bar(unsigned char c). /* Violation } */ .of the issues of truncation and lost of precision associated with the operation. double d) { float f. unsigned short us = (unsigned short)ui. /* OK .integral/floating conversion */ } REFERENCES . unsigned short us1. unsigned short us2 = ui.due to integral promotion */ */ */ REPAIR void bar(unsigned char c). /* OK */ f = (float)d. void foo(unsigned int ui. /* Violation bar(ui). /* OK */ } /* exceptions */ void except(unsigned int ui){ unsigned char uc = 300. void foo(unsigned int ui.constant expression */ int i = ui. /* OK . /* OK */ bar((unsigned char)ui). double d) { float f.

1.23 Type Conversions. AV Rule 180 . Origin: Misra Guidelines rule 43 2. AIR VEHICLE. JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4.

/* Violation */ /* Violation */ /* Violation */ . unsigned int u32a. 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. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.5f. f32a = u32a." Rule checks if implicit conversions between integer and floating types are used.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." EXAMPLE void Conv1_int( ) { float f32a. } REPAIR void Conv1_int( ) { float f32a. SINCE v7. unsigned int u32a. f32a = u32a + 2.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. f32a = f32a + u32a.

f32a = f32a + (float)u32a. /* OK */ /* OK */ /* OK */ } REFERENCES 1.4 . 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.f32a = (float)u32a. Chapter 6. f32a = (float)u32a + 2. Rule 5-0-5 3. Section 5. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.5f.

Notice that this does not imply that all operands in an expression are of the same type. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. the type in which arithmetic will be conducted will depend on the implemented size of an int." EXAMPLE void Conv1_int( ) { unsigned short u16a. unsigned int u32a. all operations should be conducted in exactly the same arithmetic type.u16b. The word 'notionally' is used because. u32b." Rule checks if implicit conversions of complex expressions are used.both additions will notionally be performed in type U32. 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.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. The expression u16a + u16b + u32c is not compliant . in practice.the first addition is notionally performed in type U16 and the second in type U32. SINCE v7. ." "The intention when restricting implicit conversion of complex expressions is to require that in a sequence of arithmetic operations within an expression.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 expression u32a + u16b + u16c is compliant .

Chapter 6. Section 10 2. u32a = u16b + (u16a + u32b). /* Violation */ /* Violation */ } REPAIR void Conv1_int( ) { unsigned short u16a. Section 5. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. u32a = u32b + u16b + u16a. /* OK */ /* OK */ } REFERENCES 1. Rule 5-0-3 3.4 .u16b. u32b.u32a = u16b + u16a + u32b. unsigned int u32a. u32a = u32b + (u16a + u16b). ISO/DIS 26262 point 8. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.4.

SINCE v7. 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. short. (char. 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.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.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. Operands of any other integer type. BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." . Integral promotion describes a process whereby arithmetic operations are always conducted on integer operands of type int or long (signed or unsigned). it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. bit-field and enum) are always converted to type int or unsigned int before an arithmetic operation.

u16a = u32a. unsigned int u32a. /* Violation */ /* Violation */ } REPAIR void Conv1_int( ) { unsigned char u8a. unsigned short u16a. Chapter 6. u8a = u32a. unsigned short u16a. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 10 2. Rule 5-0-6 . /* OK */ /* OK */ } REFERENCES 1.EXAMPLE void Conv1_int( ) { unsigned char u8a. unsigned int u32a. u16a = (unsigned short)u32a. Section 5. u8a = (unsigned char)u32a.

(char. short. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. 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. bit-field and enum) are always converted to type int or unsigned int before an arithmetic operation. SINCE v7. Operands of any other integer type.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." Rule checks if implicit conversions of function return expressions are used." EXAMPLE unsigned int Conv_ret1( signed char a ) { return a. Integral promotion describes a process whereby arithmetic operations are always conducted on integer operands of type int or long (signed or unsigned). /* Violation */ } REPAIR unsigned int Conv_ret1( signed char a ) .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.

4.4 . ISO/DIS 26262 point 8.{ return (unsigned int)a. Section 10 2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. /* OK */ } REFERENCES 1.

(char." EXAMPLE void takes_signed_double(double). void takes_unsigned_int(unsigned int). 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. Operands of any other integer type. SINCE v7. /* Violation */ takes_unsigned_int(uc). void takes_signed_int(signed int). takes_signed_double(si). void foo(signed int si. short. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. /* Violation */ } . unsigned int ui) { unsigned char uc." Rule checks if implicit conversions of function arguments are used. /* Violation */ takes_signed_int(ui). Integral promotion describes a process whereby arithmetic operations are always conducted on integer operands of type int or long (signed or unsigned). bit-field and enum) are always converted to type int or unsigned int before an arithmetic operation.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.

void takes_unsigned_int(unsigned int). void foo(signed int si. Section 10 2. takes_signed_int((int) ui).4. takes_unsigned_int(ui). unsigned int ui) { unsigned char uc. void takes_signed_int(signed int).REPAIR void takes_signed_double(double). ISO/DIS 26262 point 8. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.4 . } /* OK */ /* OK */ /* OK */ REFERENCES 1. takes_signed_double((double) si).

Furthermore it can mask problems if changes are made to the code (e.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.g. Unnecessary casting may also lead to code which is harder to maintain.2 BENEFITS "The use of casting should be sufficient to cause the calculations required to occur with the desired precision. */ p = (int)someFunction1(). Unnecessary casting adds the possibility of confusion. } // Violation // Violation . void foo(int p) { /* .. p = (int)someFunction2()." EXAMPLE typedef int INT. int someFunction1(). one of the types changes and a conversion with possible loss of information occurs)" SINCE v7. INT someFunction2().. and may be such that its interaction with the rules of promotion leads to results other than those expected. should the types of variables change.

void foo(int p) { /* . */ p = someFunction1().5 Libraries.. C++ CODING STANDARDS Chapter 4. INT someFunction2().REPAIR typedef int INT.Rule 44 2. } // OK // OK REFERENCES 1.. p = someFunction2(). AV Rule 181 . Origin: Misra Guidelines . JOINT STRIKE FIGHTER. AIR VEHICLE. int someFunction1().

// Violation . }. Such casts are usually unnecessary and scope resolution operator "::" can be used instead. } class Base1 { int f(). but later the #include is removed and only forward declaration is left. EXAMPLE class Base { }. because appropriate header is included). For example the result of cast can be incorrect if the class definition is not visible (if only forward declaration is seen). Explicit casts can be a source of serious and hard to detect errors. In such cases we recommend to rewrite the code to avoid using explicit casts. Base *b = (Base *)d. Rarely the "::" operator is not applicable. }. The result of cast might not be correct and program behavior changes. class Base2 { int f(). class Derived : public Base { void Func() { Derived *d = new Derived(). protects from errors.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.g. At the moment of adding the cast the class definition is visible (e. }. BENEFITS Simplifies code. which passes unnoticed due to explicit cast.

} // Violation REPAIR class Base { }. class Child2 : public Base1 {}. void foo(Child1* c1. Child2* c2. bool b) { Base1* p = 0. class Child2 : public Base1 {}. // OK . bool b) { Base1* p = b ? (Base1*)c1 : (Base1*)c2. public Base2 { }. // OK . class Base2 { int f().code rewritten } } . public Base2 { }. }.scope operator used } class Child1 : public Base1 {}. int Func1() { Derived1 *d = new Derived1(). // Violation } class Child1 : public Base1 {}. class Derived1 : public Base1.cast removed class Base1 { int f(). } }. if (b) { p = c1. return d->Base1::f(). return (static_cast<Base1*>(d))->f(). int Func1() { Derived1 *d = new Derived1().code rewritten } else { p = c2.class Derived1 : public Base1. void foo(Child1* c1. class Derived : public Base { void Func() { Derived *d = new Derived(). // OK . }. Base *b = d. // OK . Child2* c2.

AV Rule 181 . C++ CODING STANDARDS Chapter 4. AIR VEHICLE.REFERENCES JOINT STRIKE FIGHTER.23 Type Conversions.

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. i = (int) pi. int i. but may be unavoidable when addressing memory mapped registers or other hardware specific features. EXAMPLE void foo( ) { int* pi. REFERENCES 1. BENEFITS Prevents undefined or implementation-defined behaviour. These types are integral types that scale to the size of a pointer for both 32-bit and 64-bit Windows. MISRA-C:2004 Guidelines for the use of the C language in critical systems . } // Violation REPAIR Do not cast pointers to non-pointers. Casting between a pointer and an integer type should be avoided where possible." EXCEPTIONS The rule allows to cast to UINT_PTR or INT_PTR type.

Rec. AIR VEHICLE. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.org/resources/cstyle/Ellemtel-rules-mm. Rule 5-2-9 8.4 .chris-lott.html#18. Section 5.24 Flow Control Structures. Chapter 6.4.Chapter 6.3 Type Conversions . C++ CODING STANDARDS Chapter 4.18. ISO/DIS 26262 point 8. Section 11 2.microsoft. http://msdn2.codeproject.com/system/64BitOSAndPortingIssues.asp 6. http://www. Ellemtel Coding Standards http://www.com/en-gb/library/aa489560.3 From: 18 Portable Code . AV Rule 182 7. JOINT STRIKE FIGHTER. Misra Guidelines rule 45 3.Port.aspx 5. 7 4.

pi = (int*)i. AIR VEHICLE. JOINT STRIKE FIGHTER. Origin: Misra Guidelines rule 45 2. EXAMPLE void foo( ) { int* pi. int i. REFERENCES 1.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. EXCEPTIONS The rule allows to cast integer constant '0' to pointer type. Problems can arise when an arbitrary integer is converted to a pointer. } // Violation REPAIR Do not cast non-pointers to pointers. AV Rule 182 4. BENEFITS Rule prevents undefined or implementation-defined behaviour.24 Flow Control Structures. Section 11 3. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. C++ CODING STANDARDS Chapter 4. ISO/DIS 26262 .

4.4 .point 8.

i = (int) ci. Generally." NOTES Rule is limited to primitive types only. explicit type conversions are needed for reading an external representation of an object. int i. // Violation } REPAIR Do not use casts. BENEFITS Rule improves clarity and maintainability of code. REFERENCES . EXCEPTIONS Explicit type conversions may be used to convert a pointer to a base class to a pointer of a derived class.Never use explicit type conversions (casts) [JSF-183-4] DESCRIPTION "Never use explicit type conversions (casts). EXAMPLE void foo( ) { const int ci = 0. Explicit type conversion must be used to convert an anonymous bit-stream to an object. // Violation i = (int) &i.

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

unsigned int u32a = f32a." EXAMPLE typedef float float32_t.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.0. void goo_float( ) { double f64a. float32_t f32bt = f64a. // Violation // Violation // Violation . float f32a. unsigned short u16a = 1. } REPAIR typedef float float32_t.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." SINCE v7. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. float f32a. void goo_float( ) { double f64a.

C++ CODING STANDARDS Chapter 4.4.23 Type Conversions.float32_t f32bt = (float)f64a. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 5. // OK unsigned int u32a = (unsigned int)f32a. // OK } REFERENCES 1. Rule 5-0-5 4. Section 5. MISRA-C:2004 Guidelines for the use of the C language in critical systems 2. ISO/DIS 26262 point 8. AIR VEHICLE. AV Rule 184 3. // OK unsigned short u16a = (unsigned short)1.4 .0. Chapter 6. Rule 5-0-6 5. JOINT STRIKE FIGHTER. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.

} REPAIR unsigned short goo_float( ) { double f64a. signed int s32a. u32b. f64b. f32a. f32b. // // // // Violation Violation Violation Violation . float f32a. f32b." EXAMPLE unsigned short goo_float( ) { double f64a. f64b. float f32a.s32b. u32b s32b f32a f64a = = = = f32a. f32b + f32a + f64b. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. unsigned int u32a.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. f64a. u32b." SINCE v7. signed int s32a.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.s32b. unsigned int u32a.

Rule 5-0-6 5. Rule 5-0-5 4. Chapter 6. (signed int)f32a. JOINT STRIKE FIGHTER. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.4 . Section 5.23 Type Conversions. C++ CODING STANDARDS Chapter 4.u32b s32b f32a f64a = = = = (unsigned int)f32a. AIR VEHICLE. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6. f64b + f32b + f32a. (float)f64b.4. MISRA-C:2004 Guidelines for the use of the C language in critical systems 2. AV Rule 184 3. Section 5. ISO/DIS 26262 point 8. // // // // OK OK OK OK } REFERENCES 1.

reinterpret_cast. double d = (double)i/j. class Derived : public Base {}. Thus. Derived* d. and static_cast) that address these problems. virtual ~Base( )." EXAMPLE void foo1(){ int i. } // Violation class Base { Base( ).Prefer C++-style casts [JSF-185-2] DESCRIPTION This rule detects C-style casts in your code. void foo2(){ Base* b. the C-style cast syntax: '(type) expression' is difficult to identify for both reviewers and tools. and they allow compilers to diagnose casting errors that would otherwise go undetected. both the location of conversion expressions as well as the subsequent analysis of the conversion rationale proves difficult for C-style casts. dynamic_cast. // Violation . j. d = (Derived*)b. First. Not only are these casts easy to identify. C++ introduces several new-style casts (const_cast. }. Next. but they also communicate more precisely the developer’s intent for applying a cast. they enable most any type to be converted to most any other type without any indication of the reason for the conversion. Consequently." BENEFITS "Programs that use the new casts are easier to parse (both for humans and for tools). "Traditional C-style casts raise several concerns.

void foo2(){ Base* b. Addison-Wesley. class Derived : public Base {}.} REPAIR void foo1(){ int i. double d = static_cast<double>(i)/j. Rule 95 3. Andrei Alexandrescu. JOINT STRIKE FIGHTER. AV Rule 185 . Scott Meyers. "C++ Coding Standards. } // OK REFERENCES 1. } // OK class Base { Base( ). C++ CODING STANDARDS Chapter 4. virtual ~Base( ). d = dynamic_cast<Derived*>(b). Inc. Derived* d. (C) 2005 Pearson Education. Chapter: "Basics".23 Type Conversions. Copyright 1996." AddisonWesley. Item 2 2. "More Effective C++: 35 New Ways to Improve Your Programs and Designs". Chapter: "Type Safety". Herb Sutter. AIR VEHICLE. }. j.

" See also: MISRA2004-14_1_b. defensive programming code). } else{ // Violation a = a .g. MISRA2004-14_1_f. } } REPAIR void foo(int a. MISRA200414_1_e. MISRA2004-14_1_c. int b) { if(a == 3){ a = a + b. int b) { if(a == a){ a = a + b. MISRA2004-14_1_d. EXAMPLE void foo(int a. "This rule refers to code which cannot under any circumstances be reached. A portion of code is unreachable if there is no control flow path from the relevant entry point to that code. MISRA2004-14_1_g BENEFITS Rule helps avoid useless code.b. Code that can be reached but may never be executed is excluded from the rule (e. and which can be identified as such at compile-time. } .There shall be no unreachable code in "else" block [JSF-186_a-2] DESCRIPTION There shall be no unreachable code in "else" statement.

AV Rule 186 4. C++ CODING STANDARDS Chapter 4. Section 14 2.b. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.24 Flow Control Structures. Chapter 6.Rule 52 3. AIR VEHICLE.else{ a = a . Origin: Misra Guidelines . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 0. } // OK } REFERENCES 1. Rule 0-1-1 . JOINT STRIKE FIGHTER.

MISRA2004-14_1_d. } } . 'break'." Rule detects unreachable code after 'return'. defensive programming code). MISRA2004-14_1_c. MISRA2004-14_1_f.There shall be no unreachable code after 'return'. // Violation foo().g. return j. break. 'break'. // Violation foo(). case 2: j = 3. A portion of code is unreachable if there is no control flow path from the relevant entry point to that code. int myFunction(int i. and which can be identified as such at compile-time. 'continue'. MISRA200414_1_e. 'continue' and 'goto' statements. EXAMPLE void foo(). See also: MISRA2004-14_1_a. Code that can be reached but may never be executed is excluded from the rule (e. and 'goto' statements [JSF-186_b-2] DESCRIPTION "This rule refers to code which cannot under any circumstances be reached. int j) { switch(i) { case 1: j = 5. MISRA2004-14_1_g BENEFITS Rule helps avoid useless code.

AIR VEHICLE.Rule 52 3. Rule 0-1-1 . Chapter 6. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. // OK } foo(). C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER. break. int j) { switch(i) { case 1: j = 5. int myFunction(int i. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 14 2. } REFERENCES 1. AV Rule 186 3. Section 0.24 Flow Control Structures. Origin: Misra Guidelines .REPAIR void foo(). return j. // OK case 2: j = 3.

and which can be identified as such at compile-time. } } // Violation REPAIR There shall be no unreachable code .0 BENEFITS Rule helps avoid useless code. A portion of code is unreachable if there is no control flow path from the relevant entry point to that code. Code that can be reached but may never be executed is excluded from the rule (e.g." Rule detects unreachable code inside if/while/for/else block if in a condition a constant value is used. EXAMPLE void foo() { int unreachable_code = 1. See also: The groups of rules MISRA2004-14_1 and MISRA2004-13_7 SINCE v7. if(0) { unreachable_code = 2.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. defensive programming code).

AIR VEHICLE. C++ CODING STANDARDS Chapter 4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Rule 0-1-1 . Section 14 2. AV Rule 186 4.Rule 52 3. Chapter 6. JOINT STRIKE FIGHTER. Origin: Misra Guidelines .24 Flow Control Structures. Section 0. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.REFERENCES 1.

MISRA2004-14_1_c. } } .0 BENEFITS Rule helps avoid useless code." See also: MISRA2004-14_1_a. MISRA2004-14_1_f. default: i = 2. MISRA2004-14_1_b. break. defensive programming code). Code that can be reached but may never be executed is excluded from the rule (e. MISRA200414_1_e. break. and which can be identified as such at compile-time. MISRA2004-14_1_g SINCE v7. A portion of code is unreachable if there is no control flow path from the relevant entry point to that code. EXAMPLE void foo( int i ) { switch (i) { // Violation i = 0.There shall be no unreachable code in switch statement [JSF-186_d-2] DESCRIPTION There shall be no unreachable code in "switch" statement. expressions placed outside case and default body. Rule detects statements. case 1: i = 1. "This rule refers to code which cannot under any circumstances be reached.g.

24 Flow Control Structures. break. case 1: i = 1. } } REFERENCES 1. break. Rule 0-1-1 . break. Section 14 2. Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.REPAIR void foo( int i ) { switch (i) { // OK case 0: i = 0. JOINT STRIKE FIGHTER. default: i = 2. AV Rule 186 3. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. Section 0.

int j ) { for ( i = 0. If a result of for-condition is always false then a body is never executed. and which can be identified as such at compile-time. MISRA2004-14_1_c. i++ ) { j = 1.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. Code that can be reached but may never be executed is excluded from the rule (e. MISRA2004-14_1_b. 'FB >= VAR' that result is always false. 'FB > VAR'. where FB is a constant or a const variable and VAR is a variable assigned in for-init-statement. 'VAR <= FB'." The rule reports a violation if a 'for' loop contains in condition single relational expression 'VAR < FB'.0 BENEFITS Rule helps avoid useless code. MISRA2004-14_1_d. i < 0. MISRA2004-14_1_g SINCE v7.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. EXAMPLE void foo( int i. } } // Violation . MISRA2004-14_1_f. See also: MISRA2004-14_1_a.

C++ CODING STANDARDS Chapter 4. } } // OK REFERENCES 1. AIR VEHICLE. Rule 0-1-1 .REPAIR void foo( int i. Section 14 2. AV Rule 186 3. i++ ) { j = 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. JOINT STRIKE FIGHTER. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. int j ) { for ( i = 0.24 Flow Control Structures. Section 0. Chapter 6. i < 5.

" The rule reports a violation if: . EXAMPLE int foo1( int c ) { if ( c > 2 ) { // Violation . MISRA2004-14_1_e. Code that can be reached but may never be executed is excluded from the rule (e.g. MISRA2004-14_1_b. MISRA2004-14_1_d. and which can be identified as such at compile-time. BENEFITS Rule helps avoid useless code. defensive programming code).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.the code is after switch which has unconditional 'return' inside each 'case' and 'default' See also: MISRA2004-14_1_a. MISRA2004-14_1_c. MISRA2004-14_1_g SINCE v7. A portion of code is unreachable if there is no control flow path from the relevant entry point to that code. where each branch has unconditional 'return' .the code is after 'if/else' construction. Rule MISRA2004-14_1_g reports violations on the code inside loop.0 NOTES This rule does not report violations on the code inside loop.

return 1. default: return 2. default: return i. } // Violation // unreachable code REPAIR int foo1( int if ( c > 2 return } else { return } } c ) { ) { 0. return 0. } return c. } } // OK . return 1.return 0. } return i. int foo2( int i ) { switch(i){ case 1: i++. } else { return 1. case 2: i = i + 2. // unreachable code } int foo2( int i ) { switch(i){ case 1: i++. return 0. case 2: i = i + 2. // OK c.

Section 0. JOINT STRIKE FIGHTER. AIR VEHICLE.24 Flow Control Structures. AV Rule 186 3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 0-1-1 . Chapter 6. C++ CODING STANDARDS Chapter 4. Section 14 2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.REFERENCES 1.

MISRA2004-14_1_f SINCE v7.There shall be no unreachable code after "if" or "switch" statement inside while/for/do." The rule reports a violation on the code inside loop if: . MISRA2004-14_1_d.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. } // Violation .the code is after switch which has unconditional 'return' inside each 'case' and 'default' See also: MISRA2004-14_1_a... MISRA2004-14_1_b. Code that can be reached but may never be executed is excluded from the rule (e. 'continue' or 'return' .g. MISRA2004-14_1_e.the code is after 'if/else' construction. MISRA2004-14_1_c. defensive programming code). EXAMPLE int foo( int c ) { while ( c > 1 ) { if ( c > 2 ) { continue. A portion of code is unreachable if there is no control flow path from the relevant entry point to that code. where each branch has unconditional 'break'. } else { break.0 BENEFITS Rule helps avoid useless code.

} c++. i > 1. } } // OK for (int i = 0. return i. i++ ) { switch(i){ // Violation case 1: i++. i > 1. case 2: i = i + 2. switch(i){ // OK case 1: i++. } . } else { break. return i. default: return i. } REPAIR int foo( int c ) { while ( c > 1 ) { c++. case 2: i = i + 2. // unreachable code } for (int i = 0. default: return i.c++. return i. if ( c > 2 ) { continue. i++ ) { c++. return i. // unreachable code } return c.

AIR VEHICLE. Section 0. Section 14 2.24 Flow Control Structures. } REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.} return c. Rule 0-1-1 . JOINT STRIKE FIGHTER. Chapter 6. AV Rule 186 3. C++ CODING STANDARDS Chapter 4. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.

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." "A null statement (consisting of just a semicolon) performs no operations. which are changes in the state of the execution environment. EXAMPLE . 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. because a programmer forgot to use assignment operator to store the value. even if no variable is modified as a result of the function call. or because he accidentally wrote "==" instead of "=". modifying an object. the statement is considered not to have a side effect. Such programming errors are potentially disastrous. if an expression evaluation result is not used. "Accessing a volatile object." For example. For purposes of this rule any function call is considered as having side effects. modifying a file. The rule does not report violations on empty blocks. NOTES Empty function body is not considered as violating this rule. or calling a function that does any of those operations are all side effects. BENEFITS Complying with this rule leads to safer and more readable code.

function call */ j. void foo( ) { int i = 0. /* Violation ._p. void foo( ) { int i = 0. /* Violation . /* OK . char * _p.assignment */ i <<= 3._iField.no side effects: */ i + 3. *ps. /* Violation . }.result not i.result not } used used used used used used used REPAIR struct tagStruct{ int _iField. }.struct tagStruct { int _iField. struct tagStruct s. volatile struct tagStruct volStr. /* Examples of correct code .result not ps->_p + s. /* OK . int bar( ). volatile int j = 0.assignment */ bar().result not *(ps->_p).result not 3. *ps. /* Violation . /* Violation . /* OK .volatile variable */ volStr._iField.with side effects: */ i = i + 3. /* Violation . char * _p. struct tagStruct s.volatile variable */ */ */ */ */ */ */ */ . /* OK . /* Violation .result not i + bar().result not ps->_iField << s. /* Examples of incorrect code . int bar( ). /* OK .

Section 14 2.if(ps->_iField){} /* OK .Rule 53 3. AV Rule 187 . JOINT STRIKE FIGHTER.empty block */ } REFERENCES 1.24 Flow Control Structures. C++ CODING STANDARDS Chapter 4.cause control flow to change */ . {} /* OK . MISRA-C:2004 Guidelines for the use of the C language in critical system Chapter 6. Origin: Misra Guidelines . AIR VEHICLE.null statement */ /* OK .

/* . AIR VEHICLE.. */ stop_operation: return. */ } REPAIR Do not use labels in your code. C++ CODING STANDARDS Chapter 4. BENEFITS Using labels can lead to errors and confusion. JOINT STRIKE FIGHTER..Do not use labels [JSF-188-3] DESCRIPTION Labels should not be used. EXAMPLE void foo(int count) { /* .. AV Rule 188 . REFERENCES 1. except in switch statements.. /* Violation */ /* .24 Flow Control Structures. */ goto stop_operation. Origin: Misra Guidelines ..Rule 55 2. except in switch statements..

BENEFITS The goto statement can lead to errors and confusion. } REFERENCES 1.html From: 14 Flow Control Structures .The goto statement shall not be used [JSF-189-3] DESCRIPTION The goto statement shall not be used. EXAMPLE int foo( int a ) { if (a < 0) { goto end.Rule 49 . } /* 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. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. } a = foo(a-1).org/resources/cstyle/Ellemtel-rules-mm. end: return a+1. Section 14 2.chris-lott. Ellemtel Coding Standards http://www.

AIR VEHICLE. ISO/DIS 26262 point 8.4 .24 Flow Control Structures. C++ CODING STANDARDS Chapter 4.3. Rule 1 6.4. JOINT STRIKE FIGHTER. AV Rule 189 5. The Power of Ten .1 Metrik "GOTO" 7.Rules for Developing Safety Critical Code. Misra Guidelines .3.Rule 56 4. HIS Source Code Metriken. version 1.

Rule 121 2.h> and the setlocale function shall not be used.Do not use locale. JOINT STRIKE FIGHTER. /* Violation */ } REPAIR Do not use 'setlocale' functions. "C"). C++ CODING STANDARDS Chapter 4. EXAMPLE #include <locale. REFERENCES 1.h> void foo(void) { /* Set the locale back to the default environment */ setlocale(LC_ALL. BENEFITS Prevents changing the locate from the standard C locate.5 Libraries. AIR VEHICLE. Origin: Misra Guidelines . AV Rule 19 .h header and setlocale function [JSF-19-2] DESCRIPTION <locale.

} } } REFERENCES 1.code was changed and does not use continue anymore */ } else { i /= 2. } i /= 2. code may be more comprehensible by using an else clause instead. EXAMPLE int bar( int ). } } /* Violation */ REPAIR int bar( int )." BENEFITS Rule prevents using 'continue' which can lead to errors and confusion. MISRA-C:2004 Guidelines for the use of the C language in critical systems . However.The continue statement shall not be used [JSF-190-2] DESCRIPTION "Avoid the use of continue. void foo( int i ) { while (i--) { if (bar( i )) { continue. void foo( int i ) { while (i--) { if (bar( i )) { /* OK . continue can be used to exit from loops.

ISO/DIS 26262 point 8. AIR VEHICLE.4.chris-lott.4 .org/resources/cstyle/Ellemtel-rules-mm.Chapter 6. C++ CODING STANDARDS Chapter 4. Origin: Misra Guidelines .Rec.Rule 57 4. JOINT STRIKE FIGHTER. Ellemtel Coding Standards http://www. AV Rule 190 5.24 Flow Control Structures. Section 14 2. 53 3.html From: 14 Flow Control Structures .

/* Violation */ } } } } REPAIR #define true 1 void foo(int i) . BENEFITS Using 'break' can lead to errors and confusion.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). 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.

ISO/DIS 26262 point 8. AIR VEHICLE. Origin: Misra Guidelines .4.24 Flow Control Structures. /* OK */ } } REFERENCES 1. /* OK */ case 0 : break. AV Rule 191 3. JOINT STRIKE FIGHTER. /* OK */ default: break.Rule 58 2.4 .{ switch( i ) { case -1 : break. C++ CODING STANDARDS Chapter 4.

The 'else' statement should either take appropriate action or contain a suitable comment as to why no action is taken.. The requirement for a final 'else' statement is defensive programming.. 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 .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." See also: CODSTA-23 BENEFITS Rule ensures proper data flow and improves readability and maintainability. In the case of a simple 'if' statement then the 'else' statement need not be included. the final 'else-if' shall be followed by an 'else' statement.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 6. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Chapter 6.else { // comment or action } } REFERENCES 1. Section 14 2.24 Flow Control Structures. JOINT STRIKE FIGHTER. AIR VEHICLE.Rule 60 3. Rule 6-4-2 . AV Rule 192 4. C++ CODING STANDARDS Chapter 4. Origin: Misra Guidelines .

} case 2 : { i = 3. EXAMPLE void foo( int i ) { switch( i ) { case 0 : i = 4. break.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. then the last statement in the compound statement shall be a break statement. if (i > 0) { i = 5. i++. case 1 : i = 7. or if the switch clause is a compound statement. BENEFITS Prevents unpredictable program behaviour. } default: i = 8. } } // Violation // Violation // Violation // Violation . break." NOTES This rule allows also to use return instead break statement.

} break. i++. break. break. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. break. Misra Guidelines . } case 3 : default: i = 8. case 2 : { i = 3.Rule 47 . case 1 : i = 7.html From: 14 Flow Control Structures . Ellemtel Coding Standards http://www. if (i > 0) { i = 5.Rule 61 3. Section 15 2.chris-lott. } } // OK // OK // OK // OK .org/resources/cstyle/Ellemtel-rules-mm. break.empty case // OK REFERENCES 1.REPAIR void foo( int i ) { switch( i ) { case 0 : i = 4.

4. JOINT STRIKE FIGHTER.24 Flow Control Structures. C++ CODING STANDARDS Chapter 4. AV Rule 193 . AIR VEHICLE.

switch ( tag ) {// OK case 0: { break. } case 1: { foo( ). } case 1: { foo( ).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. EXAMPLE void foo( ) { int tag. then default can be used for error checking. See also: MISRA2004-15_3 BENEFITS Rule prevents possibility of erroneous code. break. If all desired cases are handled outside of default." This rule detects if you fail to provide a default branch for switch statements. } } } REPAIR void foo( ) { int tag. . switch ( tag ) {// Violation case 0: { break.

} default: break. } } REFERENCES 1. AIR VEHICLE.chris-lott.24 Flow Control Structures. Ellemtel Coding Standards http://www. C++ CODING STANDARDS Chapter 4.Rule 48 2. AV Rule 194 .org/resources/cstyle/Ellemtel-rules-mm.break. JOINT STRIKE FIGHTER.html From: 14 Flow Control Structures .

The rule forbids following operators: a) equality operators (== and !=) b) logical operators (!. } } // Violation REPAIR void foo1(int i) { switch(i) { case 0 : break. EXAMPLE void foo(int i) { switch(i == 0) { case 0 : break. && and ||) c) relational operators (<. BENEFITS Rule prevents using values that are effectively Boolean in switch. default:. <= and >=) which produce boolean-by-construct values.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. } } REFERENCES // OK . >. default:.

Section 6.24 Flow Control Structures. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Origin: Misra Guidelines . Chapter 6. Rule 6-4-3 5. JOINT STRIKE FIGHTER. AIR VEHICLE. Section 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. AV Rule 195 4.1. Rule 6-4-7 . Section 15 2. C++ CODING STANDARDS Chapter 4.Rule 63 3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.

case 2: break. MISRA2004-15_5 SINCE v7.1 BENEFITS An if statement provides a more natural representation. } // OK . See also: CODSTA-41. EXAMPLE void foo(int i) { switch(i) { default: . } } // Violation REPAIR void foo(int i) { switch(i) { case 1: break. default: .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.

AIR VEHICLE.24 Flow Control Structures. AV Rule 196 . C++ CODING STANDARDS Chapter 4.} REFERENCES JOINT STRIKE FIGHTER.

i<10. for (i=0. C++ CODING STANDARDS Chapter 4. BENEFITS Prevents giving unexpected results when the variable is tested.i++) /* OK */ { } } REFERENCES 1. AIR VEHICLE. for (i=0. EXAMPLE void foo() { float i.Do not use floating point variables as loop counters [JSF-197-2] DESCRIPTION Floating point variables shall not be used as loop counters.Rule 65 2. Origin: Misra Guidelines .24 Flow Control Structures. AV Rule 197 .i++) { } } /* Violation */ REPAIR void foo() { int i..i<10.. JOINT STRIKE FIGHTER.

++p) // Good { // .. EXAMPLE void foo() { int k = 0. } SINCE v7. /* . k>0.1 BENEFITS Rule improves readability of code. k--){} for(k--.begin() ..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.. k--){} } REPAIR // // // // Violation Violation Violation Violation .. k=2. */ for(. k--){} for(int i = k+2-10.end() . k--){} for(int i=0. k>0. k>0. k>0. p != c.

moo(). AV Rule 198 . /* . i>0.24 Flow Control Structures. k>0. A obj. k>0.. i--){} for(k = obj. int moo().i. C++ CODING STANDARDS Chapter 4.. k--){} } // // // // OK OK OK OK REFERENCES JOINT STRIKE FIGHTER. k>0.class A { public: int i. void foo() { int k = 0. k--){} for(int i =0. }. k--){} for(k = obj. AIR VEHICLE. */ for(k=2.

){} // Violation for(int i=0. k>0.k>0. }. void foo() { int k = 0. for(. k--.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. k>0. k+1){} // Violation } REPAIR void zoo(){} class A { public: int i. i++){} // Violation for(k--. .

zoo()){} for(k=2. k--){} for(int i =0.i. k>0. k>0. i=i-1){} for(k = obj. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. i>0. k-=1){} // // // // OK OK OK OK } REFERENCES JOINT STRIKE FIGHTER.A obj.24 Flow Control Structures. for(int i = k+2-10. AV Rule 199 . k>0.

jmpret = setjmp( mark ). void foo( void ) { int jmpret. /* Violation */ } REPAIR Do not use the setjmp macro and the longjmp function. and shall not be used.Rule 122 .h. REFERENCES 1.h> jmp_buf mark.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. } /* Address for long jump to jump to */ /* Global error number */ /* Violation */ void fphandler( int sig. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 20 2. -1 ). setjmp. or csetjmp. int fperr. BENEFITS Rule prevents normal function call mechanisms from being bypassed." Rule reports a violation message if setjmp or longjmp is used and the file includes any of the following headers: setjmp. int num ) { longjmp( mark. Origin: Misra Guidelines . EXAMPLE #include <setjmp.

Rule 1 . C++ CODING STANDARDS Chapter 4. AIR VEHICLE.5 Libraries. Section 17. The Power of Ten . JOINT STRIKE FIGHTER. Rule 17-0-5 5. AV Rule 20 4.3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.Rules for Developing Safety Critical Code. Chapter 6.

// Violation .. */ } int j = 0. */ } } REPAIR void foo() { int i = 0.Null initialize or increment expressions in for loops will not be used. SINCE v7.. for(.. j< 10. a while loop will be used instead [JSF-200-3] DESCRIPTION Null initialize or increment expressions in for loops will not be used. i< 10..1 BENEFITS A while loop provides a more natural representation. EXAMPLE void foo() { for(int i=0. Rule reports a violation message if 'for' statement misses init or increment section. a while loop will be used instead.) { /* .) // Violation { /* .

24 Flow Control Structures. while(j< 10) { /* .. C++ CODING STANDARDS Chapter 4. AV Rule 200 ..while(i< 10) { /* . */ } // OK int j = 0.. AIR VEHICLE. */ } // OK } REFERENCES JOINT STRIKE FIGHTER..

However other loop control variables representing logical values may be modified in the loop. for-init-statement. i < 5.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. for example a flag to indicate that something has been completed. i < 5. for ( i = 0. and modified in expression. } } /* Violation */ REPAIR void foo( ) { int i." NOTES A - loop-counter is a loop-control-variable that is: Initialized in. EXAMPLE void foo( ) { int i. which is then tested in the for statement. i++ ) { i = i + 3. or prior to. i = i + 3 ) {} /* OK */ } . BENEFITS Modification 'for' loop counter within a body of the loop can lead to errors and confusion. for ( i = 0. and an operand to a relational operator in condition.

AV Rule 201 4. Rule 6-5-3 . Section 13 2. AIR VEHICLE. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.Rule 67 3.Guidelines for the use of the C++ language in critical systems. MISRA C++:2008 . Section 6. Origin: Misra Guidelines .REFERENCES 1. JOINT STRIKE FIGHTER. Chapter 6. C++ CODING STANDARDS Chapter 4.24 Flow Control Structures.

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. In addition the behaviour of such a comparison cannot be predicted before execution. and may well vary from one implementation to another. if (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.. } // Violation // Violation .0f).. if (x == 0. y. 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 ) ) { /* . " EXAMPLE void foo() { float x.

MISRA C++:2008 . Section 6. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. JOINT STRIKE FIGHTER. Chapter 6. Rule 6-2-2 .Guidelines for the use of the C++ language in critical systems. if (x . // OK // OK } REFERENCES 1.Rule 50 3. Misra Guidelines .epsilon <= y && y <= x + epsilon).25 Expressions. AV Rule 202 4. if (-epsilon <= x && x <= epsilon).REPAIR void foo( float epsilon ) { float x. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. y. Section 13 2.

.expressions other than subtraction . AIR VEHICLE. but instead wrap-around in a modular way.. EXAMPLE #if (1u . Origin: Misra Guidelines . JOINT STRIKE FIGHTER. 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. It is not possible to checks: . */ #endif REPAIR Avoid wrap-around for unsigned integer. NOTES This rule checks only simple subtractions for unsigned integer constants. REFERENCES 1.Evaluation of constant unsigned integer expressions should not lead to wrap-around [JSF203-2] DESCRIPTION "Because unsigned integer expressions do not strictly overflow. C++ CODING STANDARDS .Rule 51 2.expressions which use Macro definition or hexadecimal values BENEFITS Prevents from wrap-around for unsigned integer.2u) /* Violation */ /* .complex expressions .

CWE/SANS Top 25 Most Dangerous Software Errors: CWE-190 http://cwe. AV Rule 203 3.Chapter 4.25 Expressions.org/top25/#CWE-190 .mitre.

Avoid assert(false) and prefer assert(!"informational message"). // Violation } REPAIR #include <assert. Andrei Alexandrescu. // OK assert(!"informational message")." BENEFITS Rule improves efficiency and prevents error-prone code.h> void foo( ) { int i = 0. assert( i++ != 0 ). "C++ Coding Standards. Most compilers will helpfully emit the string in their error output. // OK } REFERENCES 1. // Violation assert(i=5). // Violation assert(false). Inc. assert(i != 0).h> void foo( ) { int i = 0." AddisonWesley. "Use assert or an equivalent liberally to document assumptions internal to a module. Herb Sutter. EXAMPLE #include <assert. Never write expressions with side effects in assert statement.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. (C) 2005 Pearson Education. .

AV Rule 204 3. AIR VEHICLE. Final Guidance for Industry and FDA Staff Document issued on: January 11.25 Expressions & References. General Principles of Software Validation. JOINT STRIKE FIGHTER. 2002 . Rule 68 2.Chapter: "Error Handling and Exceptions". C++ CODING STANDARDS Chapter 4.

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. } /* OK */ /* OK */ .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. x++. The use of increment and decrement operators in combination with other arithmetic operators is not recommended because: . x = --y + x++.It can significantly impair the readability of the code ." BENEFITS Improves readability and maintainability. } /* Violation */ REPAIR void foo() { int x. Reduces risk of potential undefined behaviour caused by additional side effects EXAMPLE void foo() { int x. --y. y. x = y + x. it should be the only side-effect in the statement. y.

C++ CODING STANDARDS Chapter 4.25 Expressions. Section 5. Section 12 2. Rule 5-2-10 . AIR VEHICLE.REFERENCES 1. AV Rule 204 3. JOINT STRIKE FIGHTER. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.

consider x = b[i] + i++. As an example of what can go wrong. The problem could be avoided by putting the increment operation in a separate statement. See also: MISRA2004-12_4_a. // Violation } REPAIR void foo( ) { int a. EXAMPLE void foo( ) { int a. . and in particular no reliance can be placed on the order in which side effects occur. b[10]. ?: and . &&. ||. b[10]." The rule reports a violation if a variable is used and incremented/decremented in the same statement.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 (). (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. This will give different results depending on whether b[i] is evaluated before i++ or vice versa. MISRA2004-12_4_b BENEFITS Rule prevents evaluation of expression dependent on compiler version. a = b[a] + a++.

C++ CODING STANDARDS Chapter 4.Rule 46 3. Origin: Misra Guidelines .25 Expressions. Chapter 6. JOINT STRIKE FIGHTER. AIR VEHICLE.a = b[a] + a. Rule 5-0-1 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 . Section 12 2. AV Rule 204 4.Guidelines for the use of the C++ language in critical systems. // OK // OK } REFERENCES 1. Section 5. a++.

" See also: MISRA2004-12_2_a. 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. || and ?:. MISRA2004-12_4_a NOTES Rule checks only two nested level of function calls. The operators which can lead to this problem are &&. either the second or third operands are evaluated but not both. In the case of the ?: operator. The ?: operator is specifically provided to choose between two subexpressions. int foo( ) { return (i > j) ? j++ : i++. If these sub-expressions contain side effects then those side effects may or may not occur.developer expects 2nd and 3rd // operand to be evaluated } . int j. and is therefore less likely to lead to mistakes.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. // Violation . EXAMPLE int i. depending on the values of other sub-expressions.

ISO/DIS 26262 point 8. return i++. return j++.25 Expressions.4 . AIR VEHICLE. int foo( ) { if (i > j) { ++i. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. JOINT STRIKE FIGHTER. } else { ++j. C++ CODING STANDARDS Chapter 4. int j. AV Rule 204 3. Section 12 2.4. } } // OK REFERENCES 1.REPAIR int i.

By side effect we understand accessing a volatile object. Transmogrify(Bump(count). BENEFITS Rule prevents writing source code which might produce different results between compilers. This means that if arguments contain side effects then the order in which side effects take place is unspecified. modifying an object or calling a function that does any of those operations. Rule checks calls of functions that have at least two arguments. // Violation } .Bump(count)).} void foo() { int count = 5. A function call can give different results depending on which of the function's arguments is evaluated first. int Bump(int& x) {return ++x. // Violation Transmogrify(count++.count). EXAMPLE void Transmogrify(int.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. 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.int). EXCEPTIONS Only one level of function calls is checked.

Transmogrify(temp1. AIR VEHICLE. Section 5. // OK count++.Bump(count)). int Bump(int& x) {return ++x. Rule 5-0-1 . Herb Sutter. // OK Transmogrify(count.int). Chapter: "Functions and Operators". Origin: Misra Guidelines . (C) 2005 Pearson Education. Andrei Alexandrescu.Rule 46 3. Chapter 6. Inc. Section 12 2.Guidelines for the use of the C++ language in critical systems. AV Rule 204 5.count). MISRA C++:2008 .REPAIR void Transmogrify(int. JOINT STRIKE FIGHTER. "C++ Coding Standards." AddisonWesley.25 Expressions. C++ CODING STANDARDS Chapter 4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. int temp1 = Bump(count).} void foo() { int count = 5. } REFERENCES 1. Rule 31 4.

} /* Violation */ REPAIR Do not use the volatile keyword. AV Rule 205 .Do not use the volatile keyword [JSF-205-2] DESCRIPTION Do not use the volatile keyword. Origin: Misra Guidelines . JOINT STRIKE FIGHTER. REFERENCES 1.Rule 46 2. See also: misra2004-12_2_f BENEFITS Rule prevents evaluation of expression dependent on compiler version.25 Expressions. C++ CODING STANDARDS Chapter 4. EXAMPLE void foo1() { volatile int v. AIR VEHICLE.

data inconsistency. as well as a number heap memory allocation may lead to exhaustion. other than the placement versions. The functions calloc. 'realloc' and 'free' functions." EXCEPTIONS The rule allows to use a placement new. 'malloc'. The built-in new and delete operators. which are undesirable. ..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. behaviour associated with dynamic of other potential pitfalls. // Violation /* . */ delete[] p." undefined and implementation-defined memory allocation. malloc. non-deterministic EXAMPLE void foo() { int * p = new int[10]. realloc and free also use dynamic heap memory. Dynamic memory leaks. // Violation } REPAIR Do not use neither 'new' and 'delete' operators nor 'calloc'. use dynamic heap memory. memory behaviour.. BENEFITS "There is a range of unspecified.

Section 20 2. C++ CODING STANDARDS Chapter 4. AV Rule 206 5. The Power of Ten . Rule 3 .Guidelines for the use of the C++ language in critical systems Chapter 6. JOINT STRIKE FIGHTER. MISRA C++:2008 . Rule 18-4-1 4. Section 18.REFERENCES 1. AIR VEHICLE. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.Rule 118 3. Misra Guidelines .Rules for Developing Safety Critical Code.26 Memory Allocation.

Rec. and typedefs in a class. Final Guidance for Industry and FDA Staff . C++ CODING STANDARDS Chapter 4.org/resources/cstyle/Ellemtel-rules-mm." BENEFITS Rule improves readability and maintainability of code. typedef int MyInt. // OK // OK // OK REFERENCES 1. and typedefs. AV Rule 207 3. static MyInt glob. Ellemtel Coding Standards http://www. typedef int myint. // Violation // Violation // Violation REPAIR class A { public: enum Days {yesterday}. and typedefs in a class [JSF207-3] DESCRIPTION "Encapsulate global variables and constants. EXAMPLE enum Days {yesterday}. Static variables in a class should be used instead of global variables and constants.html from: 5 Assigning Names .Encapsulate global variables and constants. enumerated types.26 Memory Allocation. enumerated data types. 19 2. }. AIR VEHICLE. JOINT STRIKE FIGHTER. General Principles of Software Validation.chris-lott. enumerated types. myint glob.

Document issued on: January 11. ISO/DIS 26262 point 8.4. 2002 4.4 .

if( buf == 0 ) throw "Memory allocation failure!". // Violation } catch( char * str ) // Violation { cout << "Exception raised: " << str << '\n'. } // ..e.1 BENEFITS Rule improves portability of the code. int main() { char *buf. SINCE v7.C++ exceptions shall not be used (i.. } REPAIR #include <iostream> . catch and try shall not be used. throw. EXAMPLE #include <iostream> using namespace std.) [JSF-208-2] DESCRIPTION Do not use C++ exceptions. return 0. try // Violation { buf = new char[512].

AV Rule 208 . if( buf == 0 ) cout<< "Memory allocation failure!". // OK return 0. int main() { char *buf. C++ CODING STANDARDS Chapter 4.27 Fault Handling. AIR VEHICLE. buf = new char[512]. } REFERENCES JOINT STRIKE FIGHTER.using namespace std.

short. long. /* Violation . /* Violation . but specific-length typedefs should be used. double should not be used.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. signed char) or typedef name does not contain any digits indicating the size (e."main" function return type . return 1.no digits */ static signed char a. but does not guarantee portability because of the asymmetric behaviour of integral promotion. my_int).g." Rule reports a violation message if basic numerical type is used ( e. boolean and enum types ." EXAMPLE typedef signed int my_int. and float. /* Violation (for return type) */ /* Violation */ /* Violation */ /* Violation */ /* Violation */ .g.extern variable declaration . .not typedef */ short int foo( short* v_short. const int z = 1. 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. See also: MISRA-013 EXCEPTIONS Rule does not report a violation for: .bit-field types. float& r_float) { double h.typedef name which starts with 'bool' prefix.plain char. int.

char ch. typedef unsigned char BOOL. extern signed char a. 1 .18. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. float32ref r_float) { float64 h. enum ENUM { EV }. bool b.} REPAIR /* Exceptions: */ typedef char char_t.html from: 18 Portable Code .chris-lott. Ellemtel Coding Standards http://www. prefix */ struct STRUCT { unsigned int i:2.org/resources/cstyle/Ellemtel-rules-mm. return 1.1 Data Abstraction . typedef double float64. }. typedef signed char int8_t. typedef float& float32ref. Section 6 2. typedef short int s16_t. int main() { return 0. typedef const int cs32_t. } /* Correct use of typedef: */ typedef signed int my_int32. } /* 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. s16_t foo( char_t* p_char.Port. cs32_t z = 1. Rec.

28 Portable Code.3. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. JOINT STRIKE FIGHTER. AV Rule 209 .

" Rule reports a violation message if a file includes any of the following headers: signal. Origin: Misra Guidelines . JOINT STRIKE FIGHTER. AIR VEHICLE. AV Rule 21 4.5 Libraries.Rule 123 3. BENEFITS Prevents from problems associated with implementation-defined and undefined behaviour in signal handling. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6. EXAMPLE #include <signal. REFERENCES 1. or csignal.h shall not be used [JSF-21-2] DESCRIPTION "Signal handling contains implementation-defined and undefined behaviour. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.The signal handling facilities of signal. Section 18. Rule 18-7-1 . Section 20 2.h> /* Violation */ REPAIR Do not use <signal.h> header. C++ CODING STANDARDS Chapter 4.h.

// Violation // application assumes that objects of // type A will . EXAMPLE class A { protected: // a could be stored before b.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. }. or vice versa int a. 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. private: int b. separated by an access specifier. class M: A { }. is unspecified. separated by an access-specifier.1 BENEFITS The order of allocation of nonstatic data members. are ordered. void foo(M* message_buffer_ptr) { A* a_ptr = static_cast<A*>(message_buffer_ptr).

class M: A { }. C++ CODING STANDARDS Chapter 4. } REPAIR struct A { int a. }. int b.1 . void foo(M* message_buffer_ptr) { A* a_ptr = static_cast<A*>(message_buffer_ptr).28 Portable Code. AIR VEHICLE. // OK // attributes in B not separated // by an access specifier } REFERENCES JOINT STRIKE FIGHTER. AV Rule 210.always have attribute a // stored before attribute b.

and this approach helps to avoid such errors. However. It is easy to make a mistake with the rather complicated precedence rules of C.// Violation } REPAIR void foo() { int a. MISRA-C:2004 Guidelines for the use of the C language in critical . b = (a = 0). and helps to make the code easier to read." Parentheses are required for the right-hand operand because the right-hand side itself contains an assignment expression. parentheses should also be used to emphasise it. EXAMPLE void foo() { int a. BENEFITS Rule improves readability and maintainability. b. b = a = 0.// OK } REFERENCES 1. do not add too many parentheses so as to clutter the code and make it unreadable. b.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.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 12 2.Rule 47 . C++ CODING STANDARDS Chapter 4. Chapter 6. JOINT STRIKE FIGHTER. Section 5.28 Portable Code.systems Chapter 6. AV Rule 213 3. Rule 5-0-2 4. AIR VEHICLE. Origin: Misra Guidelines .

. and helps to make the code easier to read. and this approach helps to avoid such errors. However.// Violation } REPAIR void foo() { int a. BENEFITS Rule improves readability and maintainability. b." NOTES Macro's body is excluded from checking. It is easy to make a mistake with the rather complicated precedence rules of C. do not add too many parentheses so as to clutter the code and make it unreadable. parentheses should also be used to emphasise it. b = (a = 0). EXAMPLE void foo() { int a.// OK b = (a + 0).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." "No parentheses are required for the right-hand operand of an assignment operator unless the right-hand side itself contains an assignment expression. b.

AV Rule 213 3.28 Portable Code.b = (a = 0). AIR VEHICLE.Rule 47 . C++ CODING STANDARDS Chapter 4. Rule 5-0-2 4. Chapter 6.// OK } REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 5. Origin: Misra Guidelines . JOINT STRIKE FIGHTER.// OK b = a + 0. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 12 2.

b = a * (-1). BENEFITS Rule improves readability and maintainability. However. b." The rule detects parentheses which are not required for the operand of a unary operator. and helps to make the code easier to read. MISRA-C:2004 Guidelines for the use of the C language in critical . } // OK REFERENCES 1. b. b = a * -1. and this approach helps to avoid such errors. It is easy to make a mistake with the rather complicated precedence rules of C. do not add too many parentheses so as to clutter the code and make it unreadable.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. } // Violation REPAIR void foo( ) { int a. EXAMPLE void foo( ) { int a. parentheses should also be used to emphasise it.

Origin: Misra Guidelines . Chapter 6.systems Chapter 6.Rule 47 .28 Portable Code. Section 5. Rule 5-0-2 4. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. JOINT STRIKE FIGHTER. AV Rule 213 3. Section 12 2.

integer operations involving mixed types (prohibited by several rules) may produce different results because of the integral promotions. However. do not add too many parentheses so as to clutter the code and make it unreadable. parentheses should also be used to emphasise it. 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. Some operators (e.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. Similarly." "If all operators are the same. and helps to make the code easier to read. It is easy to make a mistake with the rather complicated precedence rules of C. and this approach helps to avoid such errors.g. parentheses may be used to control the order of operation. addition and multiplication) that are associative in algebra are not necessarily associative in C. EXAMPLE #ifdef _MSC_VER typedef unsigned __int16 uint16.

#endif void fooPlus( uint16 a = uint16 b = uint32 c = uint32 d. d = (a * b) * c. typedef unsigned __int32 uint32. uint32 d.h> typedef u_int16_t uint16.h> typedef u_int16_t uint16. /* Violation d is 65526. 0. uint32 d. #endif void fooPlus( ) { uint16 a = 10. uint32 c = 0.typedef unsigned __int32 uint32. + c). 65535. uint16 b = 65535. d = (a + b) + c. #elif __GNUC__ #include <sys/types. uint16 b = 65535. d = a + (b } ) { 10. #elif __GNUC__ #include <sys/types. typedef u_int32_t uint32. /* Violation d is 9. /* OK d is 65545 */ void fooMultiply( ) { . typedef u_int32_t uint32. uint32 c = 0. a * b wraps modulo 65536 */ } REPAIR #ifdef _MSC_VER typedef unsigned __int16 uint16. a + b wraps modulo 65536 */ } void fooMultiply( ) { uint16 a = 10.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. C++ CODING STANDARDS Chapter 4. Section 5. /* OK d is 655350 */ } REFERENCES 1. * c). JOINT STRIKE FIGHTER. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. AIR VEHICLE. Origin: Misra Guidelines . Rule 5-0-2 4. Chapter 6. AV Rule 213 3.uint16 a = uint16 b = uint32 c = uint32 d.28 Portable Code. 65535. d = a * (b 10. Section 12 2. 0.Rule 47 .

and this approach helps to avoid such errors. Use parentheses unless all operators in the expression are the same. } // Violation REPAIR void foo( ) { int a." See also: MISRA2004-12_5. b. do not add too many parentheses so as to clutter the code and make it unreadable. } // OK . CODSTA-90 NOTES The operands of a logical && and || are checked by the rule MISRA2004-12_5 BENEFITS Rule improves readability and maintainability. b. parentheses should also be used to emphasise it. It is easy to make a mistake with the rather complicated precedence rules of C. and helps to make the code easier to read. b = a * a + a. EXAMPLE void foo( ) { int a.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. However. b = (a * a) + a.

JOINT STRIKE FIGHTER.REFERENCES 1. Origin: Misra Guidelines . Section 12 2. Chapter 6. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 5. AIR VEHICLE.28 Portable Code. Rule 5-0-2 4. AV Rule 213 3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. C++ CODING STANDARDS Chapter 4.Rule 47 .

In other words. These functions return references to the objects they contain. Fortunately.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. 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. if you never call a function emulating a non-local static object. because the relative order of initialization of non-local static objects defined in different translation units is undefined.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. So if you replace direct accesses to non-local static objects with calls to functions that return references to local static objects. non-local static objects are replaced with local static objects. you're guaranteed that the references you get back will refer to initialized objects. As a bonus. where it's declared static." EXAMPLE #include <iostream> using namespace std. Clients then call the functions instead of referring to the objects." SINCE v7. class FileSystem { . the object it uses could be uninitialized. something that can't be said for true non-local static objects. you never incur the cost of constructing and destructing the object.

Directory::Directory( ) { size_t disks_one = tfs_one(). JOINT STRIKE FIGHTER. (C) 2005 Pearson Education. return fs.. C++ CODING STANDARDS . Scott Meyers.numDisks( ). extern FileSystem tfs. Directory::Directory( ) { size_t disks_tfs = tfs. // OK REFERENCES 1. }. } class Directory { public: Directory( ). Inc. Addison-Wesley. } Directory tempDir( ). }. // Violation REPAIR #include <iostream> using namespace std. AIR VEHICLE. class Directory { public: Directory( ). } Directory tempDir( ). class FileSystem { public: size_t numDisks( ) const. }. }. Item 4 2. FileSystem& tfs_one( ) { static FileSystem fs.public: size_t numDisks( ) const. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Third Edition. Chapter 1.numDisks( ).

General Principles of Software Validation.28 Portable Code.Chapter 4. Final Guidance for Industry and FDA Staff Document issued on: January 11. AV Rule 214 3. 2002 .

REFERENCES 1.Avoid pointer arithmetic [JSF-215-3] DESCRIPTION Pointer arithmetic should not be used. /* Violation */ --a. /* Violation */ b = a+5.Rule 101 2. JOINT STRIKE FIGHTER. int tab[10]. BENEFITS Prevents from access to unintended or invalid memory addresses. /* Violation */ } REPAIR Do not use pointer arithmetic. AV Rule 215 . Origin: Misra Guidelines . C++ CODING STANDARDS Chapter 4.28 Portable Code. EXAMPLE void foo() { int* a. AIR VEHICLE. a++. int* b. a=tab.

JOINT STRIKE FIGHTER." The rule prevents inclusion of <stdio. AV Rule 22 4. then the issues associated with the feature need to be understood.Rule 124 3. Section 20 2. EXAMPLE #include <stdio. undefined and implementation-defined behaviours associated with them.5 Libraries.h>.The input/output library stdio. BENEFITS Prevents form problems associated with a large number of unspecified.h shall not be used [JSF-22-2] DESCRIPTION "Streams and file I/O have a large number of unspecified. If any of the features of stdio. AIR VEHICLE.h> library. and <cstdio> headers. C++ CODING STANDARDS Chapter 4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. It is assumed that they will not normally be needed in production code in embedded systems. REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.h need to be used in production code. undefined and implementation-defined behaviour associated with streams and file I/O.h> /* Violation */ REPAIR Do not use <stdio. Chapter 6. Rule 27-0-1 . Origin: Misra Guidelines . Section 27.

.

atoi and atol from library stdlib. Section 20 2. AIR VEHICLE. atoi and atol functions. /* Violation */ } REPAIR Do not use atof. /* Violation */ s = "98854 dollars". int i. long l.5 Libraries. /* Violation */ s = " -9885 pigs". i = atoi( s ).Rule 125 3. BENEFITS Prevents using functions which have sometimes undefined behaviour. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.h> have undefined behaviour associated with them when the string cannot be converted. 'atoi' and 'atol' functions from library <stdlib. JOINT STRIKE FIGHTER. l = atol( s ).h> void foo( void ) { char *s. Origin: Misra Guidelines . MISRA C++:2008 Guidelines for the use of the C++ language in critical . C++ CODING STANDARDS Chapter 4. EXAMPLE #include <stdlib.12E-15". REFERENCES 1. x = atof( s ).The library functions atof. s = " -2309.h shall not be used [JSF-23-2] DESCRIPTION 'atof'. AV Rule 23 4. double x.

systems. Section 18. Chapter 6. Rule 18-0-2 .

cstdlib. REFERENCES 1. system( "dir" ). exit. AIR VEHICLE. Chapter 6.The library functions abort. C++ CODING STANDARDS Chapter 4. AV Rule 24 4. abort( ). libvar = getenv( "LIB" ). JOINT STRIKE FIGHTER. Section 18. Origin: Misra Guidelines . exit( 0 ).h. 'exit'.h libraries shall not be used. getenv and system from library stdlib. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.h shall not be used [JSF-24-2] DESCRIPTION 'abort'. Rule 18-0-3 . getenv and system functions.Rule 126 3. EXAMPLE #include <stdlib. or stdlib_iso. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.5 Libraries.h> void foo( void ) { char *libvar. 'getenv' and 'system' functions from stdlib. Section 20 2. } /* /* /* /* Violation Violation Violation Violation */ */ */ */ REPAIR Do not use abort. BENEFITS Prevents using functions which are not required in an embedded system. exit.

.

The time handling functions of library time. such as the formats of times.h> and <ctime> headers. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Origin: Misra Guidelines . Rule 18-0-4 ." Rule prevents inclusion of <time.5 Libraries. Various aspects are implementation dependent or unspecified. Section 20 2.Rule 127 3. EXAMPLE #include <time.h shall not be used [JSF-25-2] DESCRIPTION "This library is associated with clock times. Section 7.h> /* Violation */ REPAIR Do not include time.h header. C++ CODING STANDARDS Chapter 4. AV Rule 25 4. See also: SECURITY-01 BENEFITS Rule prevents undefined behaviour. Chapter 18. REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. AIR VEHICLE. JOINT STRIKE FIGHTER.

AIR VEHICLE. MISRA C++:2008 . */ #endif // OK REFERENCES 1. #endif.1 BENEFITS Limit the use of the pre-processor to those cases where it is necessary.Rules for Developing Safety Critical Code. #define. Section 16. Rule 16-2-1 3. #endif. JOINT STRIKE FIGHTER.6 Pre-Processing Directives. #include [JSF-26-2] DESCRIPTION Only the following pre-processor directives shall be used: #ifndef. Chapter 6.. #define. The Power of Ten . EXAMPLE #pragma once // Violation REPAIR #ifndef FOO_H #define FOO_H /* .Guidelines for the use of the C++ language in critical systems. #include SINCE v7. AV Rule 26 2. C++ CODING STANDARDS Chapter 4..Only the following pre-processor directives shall be used: #ifndef. Rule 8 .

.

EXAMPLE // file foo.hh // OK #ifndef FOO_HH #define FOO_HH int i. #endif .no multiple inclusion mechanism present REPAIR // file foo.Use multiple include guards [JSF-27-3] DESCRIPTION "Every include file must contain a mechanism that prevents multiple inclusion of the file.hh // Violation ." 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. MISRA2004-19_15 BENEFITS Rule improves maintainability and optimization of code. PFO-08.

4 Include Files . Chapter 6.REFERENCES 1.org/resources/cstyle/Ellemtel-rules-mm. AV Rule 27 3. Section 16.6 Pre-Processing Directives.Rule 7 2.html From: 4 Source Code in Files . C++ CODING STANDARDS Chapter 4. Rule 16-2-3 .4.chris-lott. AIR VEHICLE. Ellemtel Coding Standards http://www.Guidelines for the use of the C++ language in critical systems. JOINT STRIKE FIGHTER. MISRA C++:2008 .

#ifndef Header_filename #define Header_filename // Header declarations. #endif SINCE v7. REPAIR #ifndef FOO_H #define FOO_H int max = 10. EXAMPLE #ifndef MAX // Violation int max = 10.1 BENEFITS Conditional code compilation should be kept to a minimum as it can significantly obscure testing and maintenance efforts.. #endif // Violation int a. // OK . int a.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..

Section 16.6 Pre-Processing Directives. MISRA C++:2008 . JOINT STRIKE FIGHTER. Rule 16-2-1 3. AIR VEHICLE. C++ CODING STANDARDS Chapter 4.Guidelines for the use of the C++ language in critical systems.#endif // OK REFERENCES 1. Chapter 6. The Power of Ten .Rules for Developing Safety Critical Code. Rule 8 . AV Rule 28 2.

CODSTA-39. See also: CODSTA-03. int y ) { /* . BENEFITS "While macros can provide a speed advantage over functions.B) ((A)+(B)) /* Violation */ void foo( int x... int b ) { return (a + b). } void foo( int x. y ). */ } REFERENCES /* OK */ . y ). CODSTA-37... and the problem of function-like macros potentially evaluating parameters multiple times.. CODSTA-40 EXAMPLE #define SUM(A. */ sum( x.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. */ } REPAIR int sum( int a.. This is particularly true with respect to the type checking of parameters. /* ... functions provide a safer and more robust mechanism. int y ) { /* . /* . CODSTA-38. */ SUM( x.

Misra Guidelines .. Ellemtel Coding Standards http://www. Inc.1. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". C++ CODING STANDARDS Chapter 4.5 Inline Functions .9. Section 19 2. Chapter 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 16.org/resources/cstyle/Ellemtel-rules-mm. Addison-Wesley.html From: 9 Functions . Chapter 6.Rule 93 4.chris-lott.6 Pre-Processing Directives. Item 2 3. Scott Meyers. AV Rule 29 6.Rule 35 5. AIR VEHICLE. JOINT STRIKE FIGHTER. Rule 16-0-4 . (C) 2005 Pearson Education. Third Edition. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.

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. To ignore switch statements having more than N cases in the computation of the Cyclomatic Complexity. METRICS-35 SINCE v7. modify the "Count" expression for the cases (Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for . Rule's header should be also changed accordingly. METRICS-34. modify the "Count" expression for the cases (Collector C) from "$$ > 0" to "$$ == 0". METRICS-29. 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. To ignore switch statements in the computation of the Cyclomatic Complexity. METRICS-33. See also: METRICS-18.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.

} switch (k) { case 1: // 3 k++. BENEFITS Studies have found that methods with high Cyclomatic Complexity are errorprone. EXAMPLE void foo2(int i. default: i++. } switch (j) { case 1: // 2 j++. 9 { } do // 10 { }while(0). int b. // Violation .CC value: 21 . int j. int a. default: k++. 5 { } if((a||b)&&(a&&b)) // 6. 7. int k) { switch (i) { case 1: // 1 i++.N. 8. default: j++. } if(a||b) // 4.

2 Code Size and Complexity. AIR VEHICLE. 15 { } if((a||b)&&(a&&b)) // 16. } switch (j) { case 1: // 12 j++. 17. default: j++. AV Rule 3 .switch (i) { case 1: // 11 i++. 18. } REPAIR Keep a Cyclomatic Complexity value on the level lower than 20. default: i++. REFERENCES JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 3. } switch (k) { case 1: // 13 k++. 19 { } do // 20 { }while(0). default: k++. } if(a||b) // 14.

.

macros are. (C) 2005 Pearson Education. // OK REFERENCES 1. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Addison-Wesley..html From: 10 Constants . CODSTA-39.Rule 36 . CODSTA-38. Chapter 1. If the constant is represented by an expression.Do not define constants via #define [JSF-30-2] DESCRIPTION "Constants are to be defined using const or enum. at times.org/resources/cstyle/Ellemtel-rules-mm. Prevents incorrectly macro writing. For example. the name of the constant is not recognized in many debuggers. Scott Meyers. CODSTA-40 BENEFITS Code is easier to debug. The preprocessor performs a textual substitution for macros in the source code which is then compiled. CODSTA-37.chris-lott.1416 // Violation REPAIR const float PI = 3. never using #define. Ellemtel Coding Standards http://www. this expression may be evaluated differently for different instantiations. Item 2 2. depending on the scope of the name. Inc. incorrectly written.1416." See also: MISRA2004-19_7. Third Edition. EXAMPLE #define PI 3. In addition. if a constant has been defined using #define. This has a number of negative consequences.

2. C++ CODING STANDARDS Chapter 4. AV Rule 30 .6 Pre-Processing Directives. JOINT STRIKE FIGHTER. AIR VEHICLE.

can compile by pure luck creating ugly problems with the program EXCEPTIONS Macros are almost never necessary in C++. Chapter: "Coding Style". // OK REFERENCES 1. AIR VEHICLE.#ifdef .#if .#if defined when used as include guards and for conditional compilation.#ifndef ." AddisonWesley.Avoid macros [JSF-31-3] DESCRIPTION Macros are generally an obsolete construct inherited from C language.14. The main problems with macros are that they: .14 // Violation REPAIR const double PI = 3. Andrei Alexandrescu.are not type-safe . C++ CODING STANDARDS . (C) 2005 Pearson Education. BENEFITS Improves code reliability and maintainability. Herb Sutter. Rule 16 2. "C++ Coding Standards.are expanded by the preprocessor so debugging them is not possible . Inc. EXAMPLE #define PI 3. Exceptions to this rule are: . JOINT STRIKE FIGHTER.

6 Pre-Processing Directives.Chapter 4. Section 16.Guidelines for the use of the C++ language in critical systems. Rule 16-2-1 . MISRA C++:2008 . Chapter 6. AV Rule 31 3.

cpp> #include <file3. BENEFITS Rule improves the clarity of code.h) files. The only files included in a . the implementation file may be included as a part of the header file.h) files. EXAMPLE // file. SINCE v7.h) files [JSF-32-3] DESCRIPTION The #include pre-processor directive will only be used to include header (*.1 EXCEPTIONS In the case of template class or function definitions.hh> // Violation // Violation // file.cpp #include <file2.h> // OK . Rule allows for mentioned exception if the implementation file has the same name as a header file.h #include <file2.cpp #include <file2. In this case.hh> // Violation // Violation REPAIR // file.cpp> #include <file3.header (*.h) file .The #include pre-processor directive will only be used to include header (*.cpp file should be the relevant header (*. the code may be partitioned into separate header and implementation files.

h) file REFERENCES JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4.h> // OK .h implementation file // OK .#include <file3. AIR VEHICLE.h) file // OK .h> // file.header (*.header (*.header (*.cpp #include <file2. AV Rule 32 .cpp> file.corresponding to file.h> #include <file3.h #include <file.h) file // OK .6 Pre-Processing Directives.

h> // OK #include <dir1/dir2/foo. However. AV Rule 33 . due to the unfortunate divergence in vendor implementations.h> form will be used.h> // OK: relative path used REFERENCES JOINT STRIKE FIGHTER. AIR VEHICLE.The #include directive shall use the <filename. only the <filename. C++ CODING STANDARDS Chapter 4.h" is typically used to include local header files.h" // Violation REPAIR #include <foo.h> notation to include header files.1 BENEFITS The include form "filename. EXAMPLE #include "foo.7 Header Filess. SINCE v7.h> notation to include header files [JSF-33-2] DESCRIPTION The #include directive shall use the <filename.

1 BENEFITS Rule improves maintainability and optimization of code.#pragma once .no multiple inclusion mechanism present .preprocessor directive or . EXAMPLE // file foo." The multiple inclusion mechanism should be either: . and MISRA2004-19_15 SINCE v7. 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.e. PFO-07.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.hh // Violation .Use mechanism that prevents multiple inclusion of the file i.

AIR VEHICLE. C++ CODING STANDARDS Chapter 4. AV Rule 35 . Ellemtel Coding Standards http://www.hh // OK #pragma once REFERENCES 1.7 Header Files.org/resources/cstyle/Ellemtel-rules-mm. JOINT STRIKE FIGHTER.Rule 7 2.4.4 Include Files .chris-lott.html From: 4 Source Code in Files .REPAIR // file foo.

"file. macros. and class templates and shall not contain or produce definitions of objects or functions (or fragment of functions or objects) that occupy storage. By not having definitions in header files it's possible to include headers in multiple translation units. "file.hh".function templates .static const variables BENEFITS Rule improves readability and maintainability. ".g." See also: MISRA2004-8_5 NOTES As a headers rule detects files with extensions ".h */ void f1(){} int var.i" (e. function templates. inline functions. ". classes.h".i").hh". "file.inline functions .h". EXAMPLE /* file.Don't define entities with linkage in a header file [JSF-39_a-3] DESCRIPTION "Header files should be used to declare objects. functions.const variables if they have internal or no linkage (C++ mode) . class C { void f2(). // Violation // Violation .hxx". "file. ".static data members of class templates . }.hxx". typedefs. EXCEPTIONS The following definitions are allowed in a header file: .

}. AV Rule 39 . class C { void f2(). MISRA C++:2008 . void C::f2() {} REFERENCES 1. template <typename T> void f3 ( T ) { } // OK // OK // OK /* file. AIR VEHICLE.cpp */ #include "file.7 Header Files. Chapter: "Namespaces and Modules".h" void f1(){} int var. Andrei Alexandrescu. C++ CODING STANDARDS Chapter 4.h */ void f1().Guidelines for the use of the C++ language in critical systems. "C++ Coding Standards. Section 3." AddisonWesley. Rule 61 3. JOINT STRIKE FIGHTER.cpp */ #include "file. Rule 3-1-1 2. extern int var. Inc.h" REPAIR /* file. Herb Sutter. (C) 2005 Pearson Education.void C::f2() {} // Violation /* file. Chapter 6.

.... EXAMPLE int /* ...white spaces at the end of line....... /* Violation */ /* multiline comment .............Violation..................... SINCE v7.................. Comments with 'parasoft-suppress' are not counted.................... White spaces at the end of line are counted in the same way as other characters......(e............ /* Violation */ int /* ........1 NOTES Tab is counted as one character............ * ................... To change the default limit of characters modify the variable 'lineLengthLimit' at the begin of python method 'check'. ...................*/ i1 ....................................g.... 'lineLengthLimit = 100' means that the maximal allowed number of characters in a physical line is 100) BENEFITS The rule improves readability of code.... .*/ i2 .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...

......................................... /* Violation */ /* multiline comment .............................................*/ i1 .......................................................... ...... AV Rule 41 ... C++ CODING STANDARDS Chapter 4. ...... AIR VEHICLE.............................9 Style............ ... ...... ..................................OK......................................There is no spaces at the end........................*/ #define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx + \ xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* OK */ int /* ...........Violation. OK */ REFERENCES JOINT STRIKE FIGHTER.................. /* OK */ int /* ............... /* parasoft-suppress ITEM ........ * .....................*/ #define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* Violation */ REPAIR int /* .................................................................................*/ i3 ........................*/ i2 .......................................................OK..

} REFERENCES JOINT STRIKE FIGHTER.9 Style. EXAMPLE void foo() { int i. // OK char cc.Only one statement shall be allowed per line [JSF-42-3] DESCRIPTION This rule checks that there is only one statement per line. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. char c. BENEFITS This rule promotes readability and maintainability by reducing code complexity. // Violation } REPAIR void foo() { int ii. AV Rule 42 .

C++ CODING STANDARDS Chapter 4.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. AV Rule 43 .9 Style. // OK } REFERENCES JOINT STRIKE FIGHTER. and editors handle tabs in different ways. display devices. // Violation } REPAIR void foo() { int j. Code containing tabs will likely be indented incorrectly if ported to another environment. AIR VEHICLE. EXAMPLE void foo() { int i. Different operating systems. BENEFITS Rule prevents inconsistent display of code containing tabs in different environments.

SINCE v7. C++ CODING STANDARDS // OK .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.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.

9 Style. AV Rule 46 .Chapter 4.

JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4. EXAMPLE void _foo( ). CODSTA-93 BENEFITS Rule prevents undefined behaviour. Ellemtel Coding Standards http://www.9 Style.org/resources/cstyle/Ellemtel-rules-mm. AV Rule 47 . // Violation REPAIR void foo( ).chris-lott.html From: 5 Assigning Names . AIR VEHICLE.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 `__'). // OK REFERENCES 1.Rule 16 2." See also: CODSTA-92.

The interchange of the letter 'S' with the number '5' . SINCE v7.Identifiers will not differ by mixture of case.9 Style.The interchange of the letter 'O'.The interchange of the letter 'I'.The interchange of the letter 'Z' with the number '2' .Only a mixture of case .1 BENEFITS Rule improves readability of code.The presence/absence of the underscore character . // Violation REPAIR void foo(int param1. with the number '1' or the letter 'l' . C++ CODING STANDARDS Chapter 4. the underscore character. int param2). // OK REFERENCES JOINT STRIKE FIGHTER. interchange of the similarly looking letters and numbers [JSF-48-3] DESCRIPTION Identifiers will not differ by: . EXAMPLE void foo(int paramS.The interchange of the letter 'n' with the letter 'h'. AIR VEHICLE. with the number '0' or the letter 'D' . AV Rule 48 . int param5).

structure.. }. abb_table = ["RGB". enumeration. EXAMPLE class sample_Class { // . All others letters will be lowercase.. namespace. or type created with typedef will begin with an uppercase letter. "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.Only the first word of the name of a class. namespace.g.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. BENEFITS Rule improves readability and maintainability. enumeration. or typedef will begin with an uppercase letter [JSF-50-3] DESCRIPTION The first word of the name of a class. structure. // Violation . SINCE v7.

. AIR VEHICLE..REPAIR class Sample_class { // . C++ CODING STANDARDS Chapter 4. // OK REFERENCES JOINT STRIKE FIGHTER.9 Style. AV Rule 50 . }.

BENEFITS Rule improves readability and maintainability. private: int some_variable. EXAMPLE class Sample_class { public: int Some_function().1 EXCEPTIONS Constructors and destructors. }.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. // OK // OK . // Violation // Violation REPAIR class Sample_class { public: int some_function(). private: int Some_variable. }. SINCE v7.

9 Style. AV Rule 51 . AIR VEHICLE.REFERENCES JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4.

EXAMPLE const int Max_pressure = 100.9 Style. down}. down}.Identifiers for constant and enumerator values shall be lowercase [JSF-52-2] DESCRIPTION Identifiers for constant and enumerator values shall be lowercase. 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). C++ CODING STANDARDS Chapter 4. // Violation enum Switch_position {Up. SINCE v7. AV Rule 52 . // Violation REPAIR const int max_pressure = 100.1 BENEFITS Although it is an accepted convention to use uppercase letters for constants and enumerators. // OK // OK REFERENCES JOINT STRIKE FIGHTER. enum Switch_position {up. AIR VEHICLE.

See also: PREPROC-08.1 NOTES A header file is defined as any file that is included via #include. EXAMPLE // file. BENEFITS Rule makes source code more readable.h" // file.hpp extern int i.Header files will always have a file name extension of '.h' extension.h' [JSF-53-3] DESCRIPTION The rule reports violations on header files which does not have '.cpp #include "file.cpp #include "file. // Violation REPAIR // file. NAMING-38 SINCE v7.h extern int i. NAMING-37.hpp" // file. REFERENCES // OK .

JOINT STRIKE FIGHTER. AV Rule 53 .9 Style. C++ CODING STANDARDS Chapter 4. AIR VEHICLE.

1 2.9 Style. or ".The following character sequences shall not appear in header file names: '. AIR VEHICLE.h" // Violation REPAIR #include <foo_s. EXAMPLE #include "foo's.h> // OK REFERENCES 1. JOINT STRIKE FIGHTER.e.1 BENEFITS If any of the character sequences '. //. \. \. Final Guidance for Industry and FDA Staff Document issued on: January 11. /*. the resulting behavior is undefined. C++ CODING STANDARDS Chapter 4. or " [JSF53. AV Rule 53. \. General Principles of Software Validation. //. /*.1-2] DESCRIPTION The following character sequences shall not appear in header file names: '. <h-char-sequence>). or " appears in a header file name (i. SINCE v7. 2002 . //. /*.

cpp" [JSF-54-3] DESCRIPTION If a file name extension is not ".h" (reserved for header file) than it should be ".cc // Violation REPAIR //file.cpp // OK REFERENCES JOINT STRIKE FIGHTER.9 Style.cpp" extension should be used for implementation files whereas ". BENEFITS Rule improves readability and maintainability of code.h" are reserved for headers (rule NAMING-41). Rule detects file name extensions different than ".1 NOTES Rule is enabled for C++ only.h". See also: NAMING-41 SINCE v7. AV Rule 54 . AIR VEHICLE. EXAMPLE //file.Implementation files will always have a file name extension of ".cpp" and ". ".cpp" (implementation file). C++ CODING STANDARDS Chapter 4.

).Rule 20 2. ). REPAIR class Test { public: void foo1( protected: void foo2( private: void foo3( }. // OK ).org/resources/cstyle/Ellemtel-rules-mm.Order of scopes in class: public before all others [JSF-57_a-3] DESCRIPTION Public section must be before protected and private sections.chris-lott. CODSTA-CPP-48. See also: CODSTA-CPP-45. ). AIR VEHICLE. CODSTA-CPP-49 BENEFITS Readability and maintainability. // Violation ).6. JOINT STRIKE FIGHTER. CODSTA-CPP-47. REFERENCES 1. EXAMPLE class Test { protected: void foo2( private: void foo3( public: void foo1( }.1 Classes . ). Ellemtel Coding Standards http://www. C++ CODING STANDARDS .html From: 6 Style .

Chapter 4.9 Style. AV Rule 57 .

protected: void foo2( ). REFERENCES 1. CODSTA-CPP-49 BENEFITS Rule improves readability and maintainability.html From: 6 Style .6. Ellemtel Coding Standards http://www. JOINT STRIKE FIGHTER. private: void foo3( ). CODSTA-CPP-46.org/resources/cstyle/Ellemtel-rules-mm. AIR VEHICLE. REPAIR class Test {// OK public: void foo1( ). CODSTA-CPP-48.1 Classes .chris-lott. See also: CODSTA-CPP-45.Order of scopes in classes: protected before private [JSF-57_b-3] DESCRIPTION Protected section must be before private section. C++ CODING STANDARDS . protected: void foo2( ). EXAMPLE class Test {// Violation public: void foo1( ).Rule 20 2. }. }. private: void foo3( ).

Chapter 4.9 Style. AV Rule 57 .

Each additional argument will be written on a separate line (with the closing parenthesis directly after the last argument).When declaring functions with more than 2 parameters. int c). int c ) { // Violation // Violation // Violation } REPAIR void foo(int a. SINCE v7. int c). 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. int b. int b. the leading parenthesis and the first argument will be written on the same line as the function name.// Violation void zoo( int a.1 BENEFITS Readability and style. // OK . int b. EXAMPLE void foo(int a. int b. void zoo( int a.

C++ CODING STANDARDS Chapter 4. int b). AV Rule 58 .int c) // OK { } void goo(int a. AIR VEHICLE. // OK REFERENCES JOINT STRIKE FIGHTER.9 Style.

do foo( x ). do . even if that compound statement contains a single statement. switch(i) . i++) // OK . shall be a compound statement (enclosed within braces).. 'do. // Violation for (i=0..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. while(1). while or for loop.. EXAMPLE void foo( int x ) { int i. i++) // Violation foo( x )..The statement forming the body of a 'switch'." BENEFITS Rule improves readability and maintainability. while (1) // Violation foo( x ). // Violation } REPAIR void foo( int x ) { int i. i< 10. 'while'. i< 10. switch(i) { } // OK for (i=0.

org/resources/cstyle/Ellemtel-rules-mm. Chapter 6.} // OK do // OK {foo( x ).Rec. } REFERENCES 1. Origin: Misra Guidelines . 25 4.9 Style.} while(1). JOINT STRIKE FIGHTER.html from: 6 Style . Origin: Ellemtel Coding Standards http://www. Section 6.{foo( x ). AIR VEHICLE. AV Rule 59 5. Section 14 2.chris-lott.4 Flow Control Statements . Rule 6-3-1 . C++ CODING STANDARDS Chapter 4.6.Rule 59 3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.} while (1) {foo( x ). MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.

if(x > 0) // OK { x = i. j. else if(y > 0) // y = i. } else if(y > 0) // OK { y = i. } else . EXAMPLE void foo( int x. if(x > 0) // x = i. // x = j. int y ) { int i." BENEFITS Rule improves readability and maintainability. else y = j.'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. int { int i. } y ) Violation Violation Violation REPAIR void foo( int x. j. or another 'if' statement. The 'else' keyword shall be followed by either a compound statement.

Rule 6-4-1 . // OK } } REFERENCES 1. AV Rule 59 5.{ y = j. 25 4.chris-lott. Misra Guidelines .4 Flow Control Statements . JOINT STRIKE FIGHTER. Section 6. Ellemtel Coding Standards http://www. Chapter 6.Rule 59 3. AIR VEHICLE.9 Style.org/resources/cstyle/Ellemtel-rules-mm.6.html from: 6 Style . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. x = j. Section 14 2. C++ CODING STANDARDS Chapter 4.Rec. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.

FORMAT-03 EXCEPTIONS Rule does not adhere to enums.4. enum E {EN1 = 2. EXAMPLE class Foobar { int a. OK OK OK if in line with brace 'tab' is used.3. // Violation REPAIR class Foobar { int a. // int array[] = {1. EN2 = 1}. BENEFITS Rule improves readability and maintainability.5}. // class FooBar{}. See also: FORMAT-02. // OK // OK . }. }.2. }. // Violation struct S1 { int a.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. }. struct S1 { int a. // Rule does not report violation initializations and empty blocks.

Ellemtel Coding Standards http://www.REFERENCES 1.3 Compound Statements. AIR VEHICLE. C++ CODING STANDARDS Chapter 4.chris-lott.org/resources/cstyle/Ellemtel-rules-mm. AV Rule 60 .Rec. 24 1.6.html from: 6 Style Classes .9 Style. JOINT STRIKE FIGHTER.

// OK // OK . // Violation // Violation REPAIR class A1 { int a. See also: FORMAT-03. // initializations and empty blocks.4. // int array[] = {1.5}. EN2 = 1}. FORMAT-34 EXCEPTIONS Rule does not adhere to enums. }. // class FooBar{}. }. }. OK OK OK BENEFITS Rule improves readability and maintainability.3. EXAMPLE class A1 { int a.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. }. struct S1 { int a. struct S1 { int a.2. enum E {EN1 = 2.

24 2. AIR VEHICLE.chris-lott.9 Style. Ellemtel Coding Standards http://www.REFERENCES 1. C++ CODING STANDARDS Chapter 4.html from: 6 Style Classes . JOINT STRIKE FIGHTER.3 Compound Statements. AV Rule 61 .org/resources/cstyle/Ellemtel-rules-mm.Rec.6.

'}' ends 'do-while' construct .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. FORMAT-34 EXCEPTIONS Rule does not adhere to enums. } // Violation do { i++. It is allowed to place tokens after '}' in the same line if: . }ss. initializations and empty blocks. float f. See also: FORMAT-02. EXAMPLE int goo(int i) { if (i == 0) { return i. REPAIR int goo(int i) { if (i == 0) { return i. // Violation . } while (i < 10). } // OK do { i++. // Violation } struct S{ int i.'}' ends declaration of class/structure/union/enum BENEFITS Rule improves readability and maintainability.

24 2.4.Exception } struct S { int i. // OK .org/resources/cstyle/Ellemtel-rules-mm. EN2 = 1}. // OK .Exception // OK . float f. AV Rule 61 . // OK .3 Compound Statements. AIR VEHICLE.Exception REFERENCES 1.html from: 6 Style Classes . }ss. int array[] = {1.chris-lott.3. JOINT STRIKE FIGHTER.Exception enum E {EN1 = 2.Exception // OK .} while (i < 10).9 Style. class FooBar{}.Rec. Ellemtel Coding Standards http://www.2.5}.6. C++ CODING STANDARDS Chapter 4.

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.Ellemtel Coding Standards http://www.4 Pointers and References . int* p2.6.// Violation } REPAIR void foo() { int k=42.html#6. C++ CODING STANDARDS Chapter 4.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.9 Style.Rec. AV Rule 62 . AIR VEHICLE." BENEFITS Rule makes source code more readable.JOINT STRIKE FIGHTER.// Violation int &r1 = k. int *p1. EXAMPLE void foo() { int k=42.// OK int& r2 = k.5 from: 6 Style . 26 2.// OK } REFERENCES 1.

void foo(struct MyStruct* myObjPtr) { myObj. x. The violation is not reported if '. See also: FORMAT-18 NOTES The violation is not reported if '. EXAMPLE struct MyStruct { int x. } myObj.' or '->' is last in line ignoring white spaces. BENEFITS This promotes continuity in the relationship between the operators and the members/elements on which they act.There shall be no white space following '. b /* Violation */ REPAIR struct MyStruct { int x. This allows splitting long expressions between lines. /* Violation */ myObjPtr-> x. These operators are used to access members/elements and cannot be considered separately from them.' or '->' operator [JSF-63_a-3] DESCRIPTION The rule reports a violation if there is a space or tab character immediately following '.' or '->' operators. void fooR(struct MyStruct* myObjPtr) { . comments and backslashes. /* Violation */ } #define MACRO a. } myObj.' or '->' is preceded by 'operator' keyword.

JOINT STRIKE FIGHTER.html From: 6 Style .9 Style. #endif REFERENCES 1.myObj. AV Rule 63 .Ellemtel Coding Standards http://www.org/resources/cstyle/Ellemtel-rules-mm.' */ } #define MACRO a.x.chris-lott. /* OK: '.7 Miscellaneous . /* OK */ myObjPtr-> /* OK: '->' is last in line*/ x.6./*comment*/ x. 27 2.Rec.' is last in line */ \ b #ifdef __cplusplus struct S { int operator -> (). /* OK: no space immediately after '. C++ CODING STANDARDS Chapter 4. /* OK: preceded by 'operator' keyword */ }. AIR VEHICLE. myObj.

' or '->' is first in line ignoring white spaces and comments.' or '->' operator [JSF-63_b-3] DESCRIPTION The rule reports a violation if there is a space or tab character immediately preceding '. void fooR(struct MyStruct* myObjPtr) { . EXAMPLE struct MyStruct { int x. BENEFITS This promotes continuity in the relationship between the operators and the members/elements on which they act.' or '->' is preceded by 'operator' keyword.x. See also: FORMAT-17 NOTES The Violation is not reported if '.b /* Violation */ REPAIR struct MyStruct { int x. /* Violation */ } #define MACRO a . These operators are used to access members/elements and cannot be considered separately from them. } myObj.There shall be no white space preceding '. The violation is not reported if '. /* Violation */ myObjPtr ->x. This allows splitting long expressions between lines.' or '->' operators. void foo(struct MyStruct* myObjPtr) { myObj . } myObj.

b /* OK: '. C++ CODING STANDARDS Chapter 4.Ellemtel Coding Standards http://www. /* OK: no space immediately before '.9 Style. /* OK: preceded by 'operator' keyword */ }. AV Rule 63 .x. 27 2.JOINT STRIKE FIGHTER.6.x. /* OK */ myObjPtr ->x.Rec.myObj.' is first in line */ #ifdef __cplusplus struct S { int operator -> ().html From: 6 Style . #endif REFERENCES 1.org/resources/cstyle/Ellemtel-rules-mm.7 Miscellaneous . AIR VEHICLE. /* OK: '->' is first in line*/ myObj /*comment*/.' */ } #define MACRO a \ .chris-lott.

This promotes continuity in the relationship between the operators and their associated operand. --i.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. BENEFITS Improves readability. // OK } REFERENCES JOINT STRIKE FIGHTER. AIR VEHICLE. C++ CODING STANDARDS Chapter 4.9 Style.i. AV Rule 63 . EXAMPLE void foo() { int i=0. -. These operators act solely on their operand and cannot be considered separately from it. // Violation } REPAIR void foo() { int i=0.

These operators act solely on their operand and cannot be consider separately from it. EXAMPLE void foo() { int y = 0. AIR VEHICLE. y ++.9 Style. } // Violation REPAIR void foo() { int y = 0. C++ CODING STANDARDS Chapter 4. y++. AV Rule 63 . } // OK REFERENCES JOINT STRIKE FIGHTER. BENEFITS Improves the readability of code. This promotes continuity in the relationship between the operators and their associated operand.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.

Avoid "public" data members [JSF-67_a-2] DESCRIPTION This rule detects "public" data members that could be accessed by untrusted code. BENEFITS Prevents the use of "public" data members. REFERENCES 1. // Violation REPAIR class A { private: int iData. }. Using public accessor member functions to return data instead will prevent unauthorized access. Ellemtel Coding Standards . // OK public: const int accessiData( ). EXAMPLE class A { public: int iData. Public data members can be directly accessed by any user code. See also: OOP-19 NOTES Rule skips 'static const' variables. }.

Third Edition.1 Considerations Regarding Access Rights . Inc. Rule 41 3. Herb Sutter. Final Guidance for Industry and FDA Staff Document issued on: January 11. JOINT STRIKE FIGHTER. Chapter: "Class Design and Inheritance". Second Edition. Scott Meyers. Andrei Alexandrescu.org/resources/cstyle/Ellemtel-rules-mm. "C++ Coding Standards. (C) 2005 Pearson Education." AddisonWesley.. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Addison-Wesley. Chapter 4.10 Classes. (C) 2005 Pearson Education. (C) 2005 Pearson Education. AIR VEHICLE. General Principles of Software Validation.chris-lott. Item 20 5. Inc.. 2002 .http://www.html From: 7 Classes . "Effective C++: 50 Specific Ways to Improve Your Programs and Design". Item 22 4.Rule 22 2. Addison-Wesley. Scott Meyers. AV Rule 67 6. Inc. C++ CODING STANDARDS Chapter 4. Chapter: "Classes and Functions: Design and Declaration".7.

// Violation REPAIR class A { private: int iPrivateData. can be directly accessed by other untrusted classes using inheritance. }. Protected data members.Avoid 'protected' data members [JSF-67_b-2] DESCRIPTION This rule detects usage of "protected" data members. REFERENCES // OK . Using protected accessor member functions to return data instead will prevent unauthorized access. EXAMPLE class A { protected: int iProtectedData. while inaccessible within their classes. BENEFITS Prevents the use of "protected" data members. See also: OOP-18 NOTES Rule skips 'static const' variables. protected: const int accessData(). }.

"Effective C++: 55 Specific Ways to Improve Your Programs and Design". JOINT STRIKE FIGHTER. Third Edition. Item 22 2. AIR VEHICLE.1.10 Classes. Chapter 4. C++ CODING STANDARDS Chapter 4. Rule 41 3.org/resources/cstyle/Ellemtel-rules-mm. Herb Sutter. Andrei Alexandrescu. 2002 .7. (C) 2005 Pearson Education. Ellemtel Coding Standards http://www." AddisonWesley. (C) 2005 Pearson Education. Inc. Addison-Wesley.chris-lott. Final Guidance for Industry and FDA Staff Document issued on: January 11. "C++ Coding Standards. AV Rule 67 5. General Principles of Software Validation.1 Considerations regarding Access Rights . Inc. Scott Meyers..html From: 7 Classes .Rule 22 4. Chapter: "Class Design and Inheritance".

MRM-48. CODSTA-CPP-19. MRM-40. 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. // Violation }.0 BENEFITS "The compiler-generated versions of these functions will try to call their base class counterparts. MRM04. 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. MRM-05. CODSTA-CPP-21. but in a base class specifically designed to prevent copying. This works. OOP-34 SINCE v7. MRM-47. because the copying operations are private in the base class. MRM-37. . private: HomeForSale(const HomeForSale&). and those calls will be rejected. OOP-27." EXAMPLE class HomeForSale { public: HomeForSale(). CODSTA-CPP-24. MRM-38. // Violation HomeForSale& operator=(const HomeForSale&).Declare the copy constructor and copy assignment operator private not in class itself.

Inc. Scott Meyers. Addison-Wesley. AIR VEHICLE.10 Classes. JOINT STRIKE FIGHTER. Chapter 2. AV Rule 68 . REFERENCES 1. C++ CODING STANDARDS Chapter 4. Uncopyable& operator=(const Uncopyable&). // OK // OK class HomeForSale2 : private Uncopyable { }. (C) 2005 Pearson Education.. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Third Edition. Item 6 2. }.REPAIR class Uncopyable { protected: Uncopyable() {} ~Uncopyable() {} private: Uncopyable(const Uncopyable&).

and highly recommended. proven.1 BENEFITS "Writing const appropriately helps you gain a better understanding of your design and makes your code sturdier and safer. If you find it impossible to make a member function const." See also: CODSTA-CPP-78 SINCE v7. Understanding how and where a program's state changes is vital. you usually gain a better understanding of the ways in which that member function might modify an object's state.Member functions shall be declared const whenever possible [JSF-69-3] DESCRIPTION "Const-correctness is worthwhile. effective. } }." EXAMPLE class A { int foo(int a) { return a. and const documents that directly in code where the compiler can help to enforce it. // Violation REPAIR class A { int foo(int a) const { // OK .

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

NOTES The rule checks only simple cases (use of variables. parameters. Destructor should not be called manually [JSF-70. 'throw'. Don't make assumptions about what delete does and doesn't do. a[b]. It is generally undefined and unsafe to do anything except assign another valid value to an invalidated object. Be aware of object lifetimes and validity. 'return'.Semantically invalidated objects: Typical examples include dangling pointers to deleted objects (e. a. . 'default'.Destroyed objects: Typical examples are automatic objects that have gone out of scope and deleted heap-based objects. a pointer p after a delete p. It assumes that pointer to deleted object is used if between 'delete' and an use of that pointer there is no 'case'.g. .1-2] DESCRIPTION "There are three major kinds of invalid objects: . freed memory is freed. The rule does not check a flow.Freed memory shouldn't be accessed under any circumstances. 'break'.~T()). BENEFITS Rule prevents writing unsafe and error prone code. 'goto'.Objects that were never valid. or *a expressions after they were deleted). a->b. EXAMPLE class A { . exit().g." The rule reports violations on the use of pointers to deleted objects and on explicit calls of destructors. Never dereference an invalid iterator or pointer. and shouldn't be subsequently accessed under any circumstances.) and invalidated iterators.b. Don't try to play with object lifetime by calling the destructor manually (e.. abort(). obj.

AV Rule 70.10 Classes. return a. Rule 99 2. C++ CODING STANDARDS Chapter 4. char* foo3(char * ptr){ char * a = new char. // Violation }. obj. return a." AddisonWesley. // OK } a = ptr + 1. (C) 2005 Pearson Education. void foo1( ) { A obj. AIR VEHICLE. delete a. ~A(). "C++ Coding Standards. JOINT STRIKE FIGHTER. Andrei Alexandrescu. (*a)++. Chapter: "Type Safety". // OK } REPAIR Don't use invalid objects.1 . if(a > ptr){ delete a. Inc. Herb Sutter.~A( ). }. } // Violation char* foo2( ) { char * a = new char. // Violation } else { (*a)++. REFERENCES 1.public: A().

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

A::A() { foo(). INIT-06 SINCE v7. EXAMPLE class A { public: A(). 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. } // Violation .1 BENEFITS Public (and in some cases protected) methods assume object initialization and class invariants have been established prior to invocation. 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. private: int obj1. void foo().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. }. Thus. Rule reports a violation message if class constructor invokes public or protected method. See also: OOP-16.

AV Rule 71 2. Final Guidance for Industry and FDA Staff Document issued on: January 11. C++ CODING STANDARDS Chapter 4. REFERENCES 1.REPAIR Do not call public/protected methods from constructor. JOINT STRIKE FIGHTER. AIR VEHICLE. 2002 .10 Classes. General Principles of Software Validation.

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. virtual functions do not behave "virtually. in general. Hence. may identify runtime bugs in the application. a virtual function will always be resolved to the type of the constructor.call post-constructor during the first call of a member function . // Violation } virtual void init_Base( ). }.1-2] DESCRIPTION Inside constructors and destructors.document the requirements for clients of the code .Avoid calling virtual functions from constructors and destructors [JSF-71. The same applies to destructors." Called while executing a constructor. // Violation . Alternatives to calling virtual functions in these circumstances most often include requirements to call a post-constructor function: . EXAMPLE class Base { public: Base( ) { init_Base( ). public: Derived( ) { init_Base( ). using virtual functions in constructors and destructors is error prone. Further. a call from a constructor to a pure virtual function has undefined behavior. // Violation init_Derived1( ). and may lead to defects ranging from memory leaks to program crashes. class Derived : public Base { Derived* derived.

// OK Derived::init_Derived1( ). void Base::init_Base(){} void Derived::init_Derived1( ) {} void Derived::init_Derived2( ) {} REPAIR class Base { public: Base( ) { Base::init_Base( ). Inc. Chapter: "Construction. Destruction. public: Derived( ) { Base::init_Base( ). void Base::init_Base(){} void Derived::init_Derived1( ) {} void Derived::init_Derived2( ) {} REFERENCES 1.this->init_Derived2( ). // OK } virtual void init_Base( ). // Violation } virtual void init_Derived1( ). class Derived : public Base { Derived* derived. virtual void init_Derived2( ). }. Rule 49 . "C++ Coding Standards. }. }. virtual void init_Derived2( ). // OK derived->init_Derived2( ). Andrei Alexandrescu. and Copying". // OK } virtual void init_Derived1( )." AddisonWesley. Herb Sutter. (C) 2005 Pearson Education.

2002 . C++ CODING STANDARDS Chapter 4. "Examining C++ Program Analyzers". Scott Meyers and Martin Klaus. AV Rule 71. (C) 2005 Pearson Education. Third Edition.html 4. Scott Meyers. General Principles of Software Validation. Chapter: "Constructors/Destructors/Assignment". the February 1997. JOINT STRIKE FIGHTER.com/ddjpaper1_frames. AIR VEHICLE. Dr. Dobbs' Journal.. Item 9 3.aristeia. Inc. Chapter 2. Final Guidance for Industry and FDA Staff Document issued on: January 11. Item 13 http://www.1 5.2. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Addison-Wesley.10 Classes.

// Violation } private: string myFile. and then assignment will be performed later. }. class A { public: A( const char* file. INIT-10.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. never assigned. Initialization eliminates the overhead of performing assignment later. // Violation myPath = path. Assigning to data members causes a default constructor to be called first. MISRA-030 BENEFITS Improves code consistency and runtime performance EXAMPLE #include <string> using namespace std. class A { . const char* path ) { myFile = file. Note that constants and references can only be initialized. REPAIR #include <string> using namespace std. string myPath. See also: INIT-06.

Inc. Inc. Scott Meyers. Scott Meyers. Destruction. Addison-Wesley. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Final Guidance for Industry and FDA Staff Document issued on: January 11. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". myPath(path) {} // OK private: string myFile. C++ CODING STANDARDS Chapter 4. General Principles of Software Validation. Inc. Chapter 1. JOINT STRIKE FIGHTER. Item 4 4. }. and Copying"..10 Classes. Chapter: "Construction. string myPath. (C) 2005 Pearson Education. Andrei Alexandrescu.. Herb Sutter. REFERENCES 1. Third Edition. (C) 2005 Pearson Education." AddisonWesley. Addison-Wesley. and Assignment Operators". Chapter: "Design Style". Rule 09. Chapter: "Constructors. AV Rule 74 5.public: A( const char* file. Destructors. Second Edition. Item 12 3. Rule 48 2. AIR VEHICLE. 2002 . "C++ Coding Standards. (C) 2005 Pearson Education. const char* path ) : myFile(file).

EXAMPLE class A { public: A( int x ) : a( x ). and the order of members in an initialization list is ignored. INIT-14. the order of construction and destruction is the same for all objects of a given type. Thus. That would be an expensive proposition. class B : public A { public: B( int ). To avoid that overhead.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. float b. int a." In example section variable b from class A will not be initialized as we assumed (initialized by the same value). compilers would have to keep track of the order in which the members were initialized for each object. if members were initialized in the order of their appearance in an initialization list. // Violation .b is declared before a . private: int a. just to ensure that the destructors would be called in the right order. b( a ) {} private: int b. MISRA-030 BENEFITS Prevents access to null pointer when memory is not allocated. See also: INIT-06. }.

(C) 2005 Pearson Education. AV Rule 75 4.b is declared before a REFERENCES 1. General Principles of Software Validation. }. Chapter: "Constructors. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. Final Guidance for Industry and FDA Staff Document issued on: January 11. a( y ) {} // OK .. int a. 2002 . Item 13 3. B::B( int y ) : b( 5 ). Third Edition. A( 1 )..10 Classes.a is declared before b class B : public A { public: B( int ). Inc. and Assignment Operators". Inc. b( a ) {} private: int a. // OK . Second Edition. Scott Meyers. (C) 2005 Pearson Education. a( y ) {} before b // Violation . Addison-Wesley. private: float b. Destructors.}. B::B( int y ) : b( 5 ). Addison-Wesley. Scott Meyers. "Effective C++: 55 Specific Ways to Improve Your Programs and Design". Chapter 1. Item 4 2. JOINT STRIKE FIGHTER.a is declared REPAIR class A { public: A( int x ) : a( x ). "Effective C++: 50 Specific Ways to Improve Your Programs and Design". int b. }. A( 1 ).

.

so C++ generates and calls the default assignment operator instead. A canonical assignment operator returns a class reference type and takes a const reference of the type. or 'delete' to deallocate its data member. If an assignment operator is not explicitly defined. MRM-38. First." See also: CODSTA-CPP-02. There are at least two problems with this state of affairs. CODSTA-CPP-21. OOP-30. BENEFITS "Bit-wise copying is only performed for member data having primitive . which uses 'new' to allocate its data member. "An assignment is not inherited like other operators. MRM-40. Second. MRM-04. CODSTA-CPP-24. which for pointers is just a bitwise copy.Declare an assignment operator for classes with dynamically allocated memory [JSF-76_a-2] DESCRIPTION This rule checks if a class. OOP-27. its destructor will delete the memory still pointed to by the other. 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. the memory that 'b' used to point to was never deleted. This default assignment operator performs memberwise assignment from the members of 'a' to the members of 'b'. has an explicitly defined canonical assignment operator. MRM-47.' (where 'a' and 'b' are pointers) there is no client-defined operator= to call. then one is automatically defined instead. When one of them goes out of scope. If you perform an assignment 'b = a. both 'a' and 'b' now contain pointers to the same character string. it is lost forever. This is a classic example of how a memory leak can arise.

" EXAMPLE class MyClass { // Violation public: MyClass( ). }. ~MyClass( ) { delete p. MyClass::MyClass( ) { p = new int. } private: int *p. 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. ~MyClass( ) { delete p. } . MyClass::MyClass( ) { p = new int. MyClass& operator=( const MyClass& ). If an object manages the allocation of the instance of an object pointed to by a pointer member. One consequence of this is that bit-wise copying is performed for member data having pointer types. }. } REPAIR class MyClass { // OK public: MyClass( ).types. } private: int *p.

Scott Meyers. Destruction.Rule 27 2. "C++ Coding Standards. (C) 2005 Pearson Education. Final Guidance for Industry and FDA Staff Document issued on: January 11. Herb Sutter.REFERENCES 1. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". C++ CODING STANDARDS Chapter 4. Andrei Alexandrescu. Chapter: "Construction.5 AssignmentOperators ." AddisonWesley.chris-lott. Chapter: "Constructors.html From: 7 Classes . and Assignment Operators". Inc. 2002 . Inc. (C) 2005 Pearson Education. Item 11 3. JOINT STRIKE FIGHTER. Addison-Wesley. Second Edition. General Principles of Software Validation..7. Ellemtel Coding Standards http://www. Rule 53 4.org/resources/cstyle/Ellemtel-rules-mm.10 Classes. Destructors. and Copying". AV Rule 76 5. AIR VEHICLE.

or 'delete' to deallocate its data member. } private: int *p. ~MyClass(){ delete p. 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). MRM-40. which uses 'new' to allocate its data member. MyClass::MyClass() { p = new int. } avoid surprises when an object same type. probably resulting . MRM-48.Declare a copy constructor for classes with dynamically allocated memory [JSF-76_b-2] DESCRIPTION This rule checks if a class. only the value of the pointer will be invocations of the destructor for the same object in a run-time error. 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. This can lead to two (on the heap). has an explicitly defined copy constructor." EXAMPLE class MyClass{ // Violation public: MyClass(). If an object manages object on the heap (the managing be created by the class' copied. }. OOP-27. See also: CODSTA-CPP-19. MRM-37. MRM-05. OOP-30.

JOINT STRIKE FIGHTER. Destruction. 2002 . }. Addison-Wesley. (C) 2005 Pearson Education. Herb Sutter. } REFERENCES 1. "Effective C++: 50 Specific Ways to Improve Your Programs and Design". Item 11 3. AV Rule 76 5. and Copying". } private: int *p.html From: 7 Classes .10 Classes.5 Constructors and Destructors . Second Edition. MyClass::MyClass() { p = new int. ~MyClass(){ delete p. Destructors. Andrei Alexandrescu. Ellemtel Coding Standards http://www. Scott Meyers.org/resources/cstyle/Ellemtel-rules-mm.Rule 25 2. "C++ Coding Standards." AddisonWesley. MyClass(MyClass&). AIR VEHICLE. Final Guidance for Industry and FDA Staff Document issued on: January 11. Chapter: "Construction..chris-lott.7. Rule 53 4. C++ CODING STANDARDS Chapter 4. Inc. Chapter: "Constructors. (C) 2005 Pearson Education.REPAIR class MyClass{ // OK public: MyClass(). Inc. General Principles of Software Validation. and Assignment Operators".

Base (int x) : base_member (x) { } Base (const Base& rhs) : base_member (rhs. class Derived : public Base { public: .base_member) {} private: int base_member. }." EXAMPLE class Base { public: Base().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." SINCE v7. including those in base classes. 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. Hence the copy constructor must copy all members.1 NOTES The rule does not report violations on variables of class/struct type.

derived_member_1 (y). int derived_member_2. class Derived : public Base { public: Derived (int x. int z) : Base (x). int derived_member_2. derived_member_2 (rhs.Derived (int x. Base (int x) : base_member (x) { } Base (const Base& rhs) : base_member (rhs. }. }. int y. int z) : Base (x). derived_member_1 (rhs. REPAIR class Base { public: Base().derived_member_2) { } private: int derived_member_1. int y.base_member) {} private: int base_member.derived_member_1). }. derived_member_1 (y). derived_member_2 (z) { } Derived(const Derived& rhs) { } // Violation private: int derived_member_1. // OK . derived_member_2 (z) { } Derived(const Derived& rhs) : Base(rhs).

REFERENCES 1.10 Classes. 2002 . C++ CODING STANDARDS Chapter 4. Final Guidance for Industry and FDA Staff Document issued on: January 11. General Principles of Software Validation. JOINT STRIKE FIGHTER. AV Rule 77 2. AIR VEHICLE.

int). int).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. }. for the class definition class X { X(const X&. If the user-declared constructor is later defined as X::X(const X& x. one is declared implicitly. */ } then any use of X's copy constructor is ill-formed because of the ambiguity. a copy constructor is implicitly-declared. A(const A&). Thus. int i =0) { /* ...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. EXAMPLE class A { A(const A&.1 BENEFITS If the class definition does not explicitly declare a copy constructor. SINCE v7. .

A::A(const A& x.1 2. int i=0). AV Rule 77.. C++ CODING STANDARDS Chapter 4. A(const A&). int i) // OK { /* . Final Guidance for Industry and FDA Staff Document issued on: January 11. A::A(const A& x.10 Classes. AIR VEHICLE. JOINT STRIKE FIGHTER. General Principles of Software Validation. int i =0) // Violation { /* . }. */ } REPAIR class A { A(const A&.. 2002 .}.. */ } REFERENCES 1..

only the base class' destructor will be invoked. If a class. EXAMPLE class Base // Violation { public: virtual void foo( ). OOP-31 BENEFITS Define a virtual destructor in order to prevent data corruption. is used as a base class.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. class Derived : public Base{}. }. See also: OOP-23. . If such a pointer is assigned to an instance of a derived class and if delete is then used on this pointer. OOP-24. having virtual functions but without virtual destructors. the program will fail. there may be a surprise if pointers to the class are used. If the program depends on the derived class' destructor being invoked. ~Base( ). REPAIR class Base // OK { public: virtual void foo( ).

}.10 Classes. class Derived : public Base{}. AV Rule 78 .virtual ~Base( ).7. AIR VEHICLE. REFERENCES 1.Rule 26 2. Ellemtel Coding Standards http://www.org/resources/cstyle/Ellemtel-rules-mm.html From: 7 Classes .5 Constructors and Destructors . C++ CODING STANDARDS Chapter 4.chris-lott. JOINT STRIKE FIGHTER.

then that resource should be wrapped in a class whose destructor automatically cleans up the resource. EXAMPLE #include <iostream> using namespace std. } ~File_ptr () { } private: // Violation . Moreover. especially in error cases. class File_ptr { public: File_ptr (const char *n. Releasing resources in a destructor provides a convenient means of resource management.1 BENEFITS Prevention of resource leaks. See also: MRM-33 SINCE v7. especially in regards to exceptional cases. const char * a) { p = fopen(n.a).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. if it is possible that a resource could be leaked.

}. }. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. General Principles of Software Validation.FILE *p. REPAIR #include <iostream> using namespace std. Final Guidance for Industry and FDA Staff Document issued on: January 11. 2002 .10 Classes. JOINT STRIKE FIGHTER. } ~File_ptr () { if (p) { fclose(p). REFERENCES 1.a). AV Rule 79 2. } } // OK private: FILE *p. class File_ptr { public: File_ptr (const char *n. const char * a) { p = fopen(n.

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.

void method17(). void method15(). void method8(). void method14(). void method12(). void method10(). void method2(). void method11(). void method16(). void method3(). EXAMPLE class Foo {// Violation public: void method1(). ." This metric measures the number of public methods per class. void method7(). Rule triggers if the number of public methods exceeds 20 per class. BENEFITS Rule improves readability and maintainability of code. void method18(). void method4(). void method9().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. void method13(). NOTES This rule applies only to the C++ programming language. void method6(). void method19(). void method5().

void method20(). pg. REFERENCES By Mark Schroeder "A Practical Guide to Object-Oriented Metrics" IT Professional. }. 33. November/December 1999. void method21(). REPAIR Limit the number of public methods to 20 per class. .

Ellemtel Coding Standards http://www.3.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. HIS Source Code Metriken. int b. 41 2. EXAMPLE void foo(int a. version 1.9. int e.org/resources/cstyle/Ellemtel-rules-mm. Motorola Coding Standards G-6 3.Rec.html From: 9 Function . This should be done to reduce the amount of coupling between functions.chris-lott. int f) // Violation { } REPAIR Limit the number of parameters to 5 per function. int c. a structure could be used to hold related data and a pointer could be passed. int d. REFERENCES 1. If more parameters are needed.1 Metrik "PARAM" . See also: METRICS-08 BENEFITS Rule improves readability and maintainability of code.1 Function Arguments .

EXAMPLE #define PLUS(a.f) (a+b+c+d+e+f) // Violation REPAIR Limit the number of parameters to 5 per macro. If a large number of parameters are passed to a macro.d. REFERENCES Recommended by ParaSoft .c.Macros should not use more than 5 parameters [METRICS-16-3] DESCRIPTION This rule checks that macros do not use more than 5 parameters. it may become hard to read and understand. If this occurs. BENEFITS Rule improves readability and maintainability of code. it may be beneficial to break the macro down into multiple macros or make it into a function.e.b.

i14. unions. i3. See also: METRICS-06 BENEFITS Rule improves readability and maintainability of code. i12. i5. i13. i16. i7. i18. i9. i23. i17. i10. i15. 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 }. i21. _tA// Violation i0. or classes with more than 20 fields [METRICS-17-5] DESCRIPTION This rule is purely informational and will report a message when a struct. i19. i4. i1. union or class declaration is found with more than 20 fields. i22. i2. i20. . i8. i6.Avoid structs. i11.

REPAIR Limit the number of fields to 20. REFERENCES Recommended by ParaSoft .

Rule's header should be also changed accordingly. To ignore switch statements having more than N cases in the computation of the Cyclomatic Complexity. METRICS-33. To ignore switch statements 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. 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. METRICS-34. METRICS-29. 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.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. See also: METRICS-28. modify the "Count" expression for the cases (Collector C) from "$$ > 0" to "$$ == 0". BENEFITS .

December 1976. 9 { } do // 10 { }while(0). default: break. HIS Source Code Metriken. T." IEEE Transactions on Software Engineering. case 2: // 2 break. REFERENCES McCabe. } if(a||b) // 4. case 3: // 3 break. 8.1 Metrik "v(G)" . version 1. 5 { } if((a||b)&&(a&&b)) // 6.Studies have found that methods with high Cyclomatic Complexity are errorprone. EXAMPLE void foo(int a. 7.. int b) // Violation .CC value: 11 { switch (a) { case 1: // 1 break.3. "A Complexity Measure. } REPAIR Keep a Cyclomatic Complexity value on the level lower than 10.

.

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. EXAMPLE void foo1(int y) {// Violation // // // // } void foo12() {// Violation /* */ } void foo3() {// Violation /**//**//**//**/ } void foo4() {// Violation } . BENEFITS Rule improves readability and maintainability.

REPAIR void foo1() {// OK // // // // } void foo2() {// OK /* */ } void foo3() {// OK /**//**//**//**/ } REFERENCES Recommended by ParaSoft .

" See also: METRICS-01. it can be difficult to comprehend. int a8. 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. such an error can be more exactly localized. int a5. int a7. If an error situation is discovered at the end of an extremely long function. Generally. METRICS-22 NOTES Rule triggers when the number of declarations and statements within function body exceeds 50. int a12. int a9. it can be said that a function should not be longer than two pages. . int a10. int a3. int a2. int a4. EXAMPLE void too_long_function() {// Violation int a1. since that is about how much that can be comprehended at one time. int a11. int a6.Avoid too long functions (declarations and statements) [METRICS-20-3] DESCRIPTION Long functions have disadvantages: "If a function is too long. METRICS-21. BENEFITS By always using short functions.

a39. a35. a28. a47. a19. a21. a46. a36. a15. a22. a24. a38. a27. . a14. a53. a42. a33. a37.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. a34. a51. a43. a48. a17. a20. a49. a25. a54. a52. a30. a26. a23. a45. a18. a29. a44. a32. a41. a16. a40. a50. a31.

REPAIR Number of declarations and statements within function body should be limited to 50.chris-lott.html From: 9 Functions .9.org/resources/cstyle/Ellemtel-rules-mm.7 General . REFERENCES Ellemtel Coding Standards http://www.Rec 47 .

Avoid too long functions (blocks) [METRICS-21-3] DESCRIPTION "Avoid long and complex functions. BENEFITS By always using short and simple functions. switch(i) { case 1: break. such an error can be more exactly localized and function testing is much easier. METRICS-20. EXAMPLE void func( int i ) { if (1) { } else { } do { } while(1). then there are 2**15 (or 32768) different branches to test in a single function. default: break." See also: METRICS-01. Complex functions are difficult to test. If a function consists of 15 nested if statements. METRICS-22 NOTES Rule triggers if function contains more than 10 blocks. } if (1) { } else { } if (2) { } else { } if (3) { // Violation .

html From: 9 Functions .7 General .} else { } } REPAIR Limit the number of blocks within function body to 10.Rec. 47 .9.chris-lott.org/resources/cstyle/Ellemtel-rules-mm. REFERENCES Ellemtel Coding Standards http://www.

"C++ Coding Standards. METRICS-21 BENEFITS Rule improves readability and maintainability of code. Chapter: "Coding Style". REPAIR Do not type functions longer than 75 lines of code." Addison-Wesley. // statements. types // . EXAMPLE class A { void foo( int x ) // Violation { // . REFERENCES Herb Sutter.. Rule 20 . (C) 2005 Pearson Education. and both are usually solved by better refactoring.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. declarations.." See also: METRICS-01. } }.. Inc. Andrei Alexandrescu. expressions. METRICS-20.. // more than 75 lines of constants.

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.for.try-catch construction . Following elements of code are recognized as levels: . For example. change the expression to "$$==10".switch statement . BENEFITS "Excessive block nesting depth (e." EXAMPLE int foo1(int i) { if(i > 1){ .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. while. and often needlessly so. if.if-else construction . The default "$$==5" expression imposes maximum nesting level of 5. 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. do-while loops . and try blocks) make functions more difficult to understand and maintain. to report violation if nesting level is higher than 10.g. while. for. The level is checked by expression in last "Count" node.

else if(i == 5) return i. if(i > 6){ ++i.violation already i. if(i == 6){ return 6. else if(i == 4) return i.6 level // OK .if(i > 2){ if(i > 3){ if(i > 4){ if(i > 5){ ++i. if(i > 7){ reported on level 6 return } } } else { ++i. // Violation . // OK . else if(i == 3) return i. } } } } } } } int foo2(int i) { if(i == 1) return i. else if(i == 7) 6 return i.6 level // OK .7 level .5 level // Violation .6 level // OK .7 level . else if(i == 2) return i.violation already reported on level // The above statement is in fact identical to following: . else if(i == 6) return i.5 level // Violation .

} else { if(i == 5) { // OK .6 level return i. } else { if(i == 4) { return i. } else { if(i == 2) { return i.if(i == 1) { return i.violation already reported on level 6 return i. } else { if(i == 6) { // Violation . . } } } } } } } } int foo3(int i) { { { { { { { } } } } } // OK .6 level return i. } else { if(i == 3) { return i.5 level // Violation . } else { if(i == 7) { // OK .5 level return i.7 level .

{ // 5 do { // 6 .1 level } catch(double) { // OK . same as if-else: try { // OK .1 level } catch(int) { // OK .1 level } catch(long) { // OK ..1 level } catch(.} } void foo4() { // try-catch is linear and introduces one level.) { // OK .1 level } } int foo5(int i) { while(i) { // 1 for(..1 level } catch(float) { // OK .) { // 2 if(i) { // 3 } else { // still 3 switch(i) { // 4 case 1: // still 4 ++i.Violation return i. } } } } } } #define MACRO(x) { { { { { { return x.. } } } } } } int foo6(int i) { // Code from macros might produce violations MACRO(i). } while(0).1 level } catch(char) { // OK . // Violation } .

"C++ Coding Standards. nested consecutive ifs where an && condition will do." AddisonWesley. Andrei Alexandrescu. Rule 20 . Inc. (C) 2005 Pearson Education. automatic cleanup via destructors over try blocks. Herb Sutter. and often better. algorithms: They're flatter than loops." REFERENCES 1.REPAIR Do not "Avoid Prefer Prefer nest statements more than 5 levels. Chapter: "Coding Style".

Violation /* code */ #line 501 int i = 0. Experience has shown that larger files are cumbersome to edit correctly and to maintain. REFERENCES Recommended by ParaSoft . BENEFITS Improves maintainability and readability of code.Avoid source files that are longer than 500 lines [METRICS-24-5] DESCRIPTION Source files should be no longer than 500 lines. // line: 501 REPAIR Limit source files to 500 lines. EXAMPLE // Source file .

L-SLOCs number = . y = y + p. // Violation // L-SLOCs number = 1 // .1 NOTES Logical line of code is a single declaration or statement terminated by semicolon. x++... y.. y--){ // L-SLOCs number = 100 x = y. // L-SLOCs number = 101 } // . BENEFITS Rule prevents using long functions which tend to be complex and therefore difficult to comprehend and test. x = x + p. EXAMPLE int sample_function(int p) { int x. y > 0.. Two semicolons in parenthesis after 'for' keyword are counted as one. 151 // L-SLOCs number = 150.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. // L-SLOCs number = 99 for(y = 10.

return x. // L-SLOCs number = 201 } REPAIR Do not use functions containing more than 200 logical source lines of code (L-SLOCs)... AV Rule 1 . REFERENCES 1. C++ CODING STANDARDS Chapter 3. JOINT STRIKE FIGHTER. AIR VEHICLE.2 Code Size and Complexity.// .

.............. .... SINCE v7................. /* Violation */ /* multiline comment ................................ Comments with 'parasoft-suppress' are not counted..................*/ i1 ......................g.................. White spaces at the end of line are counted in the same way as other characters...................white spaces at the end of line................ * . EXAMPLE int /* ....... 'lineLengthLimit = 100' means that the maximal allowed number of characters in a physical line is 100) BENEFITS The rule improves readability of code..... /* Violation */ int /* .............1 NOTES Tab is counted as one character.......... To change the default limit of characters modify the variable 'lineLengthLimit' at the begin of python method 'check'.Violation..........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..... ...................*/ i2 .(e.... Very long source lines can be difficult to read and understand.

.................................................. AV Rule 41 .. .................................There is no spaces at the end...............................................................................9 Style....... /* OK */ int /* ........................... AIR VEHICLE............ OK */ REFERENCES JOINT STRIKE FIGHTER..........................*/ i3 ...................................................... /* Violation */ /* multiline comment ...................................... ........OK..................*/ #define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx + \ xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* OK */ int /* ............ ........................... * ...*/ #define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* Violation */ REPAIR int /* .........*/ i2 ......................................................... C++ CODING STANDARDS Chapter 4...........*/ i1 ..Violation..................... /* parasoft-suppress ITEM .. .........................OK...... .............

int c. AV Rule 110 // OK // .13 Function. SINCE v7. int f. and maintain. int h) Violation { } REPAIR // Limit the number of parameters to 7 per function. void foo(int a. int e. int e. AIR VEHICLE. int b.1 BENEFITS Rule improves readability and maintainability of code. int d. int c. int f. C++ CODING STANDARDS 4. int g. int g) { } REFERENCES JOINT STRIKE FIGHTER. use. EXAMPLE void foo(int a. int b. Functions with too many parameters may indicate an under use of objects and abstractions.Functions with more than 7 parameters will not be used [METRICS-27-3] DESCRIPTION Functions having long argument lists can be difficult to read. int d.

modify the "Count" expression for the cases (Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for . To ignore switch statements in the computation of the Cyclomatic Complexity. METRICS-35 SINCE v7. modify the "Count" expression for the cases (Collector C) from "$$ > 0" to "$$ == 0". METRICS-34.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. To ignore switch statements having more than N cases in the computation of the 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. Rule's header should be also changed accordingly. See also: METRICS-18.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. METRICS-29. METRICS-33.

int k) { switch (i) { case 1: // 1 i++. int b. default: j++. default: i++. int j. } if(a||b) // 4. 9 { } do // 10 { }while(0).N. 8. BENEFITS Studies have found that methods with high Cyclomatic Complexity are errorprone. } switch (j) { case 1: // 2 j++. default: k++. // Violation . 7. 5 { } if((a||b)&&(a&&b)) // 6. } switch (k) { case 1: // 3 k++.CC value: 21 . EXAMPLE void foo2(int i. int a.

C++ CODING STANDARDS Chapter 3. 17. } REPAIR Keep a Cyclomatic Complexity value on the level lower than 20. } if(a||b) // 14. 15 { } if((a||b)&&(a&&b)) // 16.2 Code Size and Complexity. } switch (j) { case 1: // 12 j++. REFERENCES JOINT STRIKE FIGHTER. } switch (k) { case 1: // 13 k++. default: k++. 19 { } do // 20 { }while(0). AV Rule 3 . default: i++. default: j++.switch (i) { case 1: // 11 i++. 18. AIR VEHICLE.

.

METRICS-33. modify the "Count" expression for the cases (Collector C) from "$$ > 0" to "$$ == 0".Report Cyclomatic Complexity [METRICS-29-5] DESCRIPTION This rule reports the Cyclomatic Complexity value for each function. . To ignore switch statements in the computation of the Cyclomatic Complexity. METRICS-34.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. modify the "Count" expression for the cases (Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for N. 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-35 SINCE v7. To ignore switch statements having more than N cases in the computation of the Cyclomatic Complexity.

4. 2 { } if((a||b)&&(a&&b)) // 3.CC value: 8 { if(a||b) // 1. 6 { } do // 7 { }while(0). int b) // Violation . 5. EXAMPLE void foo(int a.BENEFITS Studies have found that methods with high Cyclomatic Complexity are errorprone. REFERENCES Recommended by ParaSoft . } REPAIR This rule is an informational rule and reports message on each function implementation.

expressions. // more than 60 lines of constants.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. It is much harder to understand a logical unit that spans multiple screens on a computer display or multiple pages when printed.." See also: METRICS-01. METRICS-21. METRICS-20. Lines containing only comment are not counted. Excessively long functions are often a sign of poorly structured code. METRICS-22 SINCE v7. } .. types // . BENEFITS "Each function should be a logical unit in the code that is understandable and verifiable as a unit. this means no more than about 60 lines of code per function.3 NOTES The rule counts non-empty lines inside body of function. Typically.." EXAMPLE void foo( int x ) // Violation { // . // statements.. declarations.

Rule 4 .Rules for Developing Safety Critical Code.REPAIR Refactor long functions into several smaller functions. REFERENCES The Power of Ten .

parameter values." The rule reports a violation if A < 2*F where A is the number of assertions and F is the number of defined functions. Because assertions are side-effect free. 'assert'." EXAMPLE /* Violation . SINCE v7. The odds of intercepting defects increase with assertion density. The rule checks one file at time.3 NOTES The rule detects all using of macros which names are ended by 'assert' e. return values of functions. . Assertions are used to check for anomalous conditions that should never happen in real-life executions.and post-conditions of functions. and loop-invariants.g.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. Use of assertions is often also recommended as part of a strong defensive coding strategy. 'checkAssert' etc. BENEFITS "Statistics for industrial coding efforts indicate that unit tests often find at least one defect per 10 to 100 lines of code written.2 functions defined and 1 assertion used */ #define c_assert(x) ((x) ? 1 : 0). 'c_assert'. they can be selectively disabled after testing in performance-critical code. Assertions can be used to verify pre.

void foo(int x) /* Some code c_assert(x).2 functions defined and 4 assertions used (density: 2) */ #define c_assert(x) ((x) ? 1 : 0). /* Use of assertion */ } int baz(). Rule 5 . } void bar(int x. /* Use of assertion */ /* Some code */ c_assert(x+y). /* Use of assertion */ /* Some code */ } void bar(int x. int y) { c_assert(x). /* Use of assertion */ c_assert(y). { */ /* Use of assertion */ int y) { */ REPAIR /* OK . /* Some code } int baz(). REFERENCES The Power of Ten .Rules for Developing Safety Critical Code. void foo(int x) { c_assert(x).

All lines are counted. Assertions can be used to verify pre. M and N are parameters that could be set inside rule in python method 'setValue'.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. 'assert'. e. parameter values. 'checkAssert' etc. including empty and commented out. return values of functions. Use of assertions is often also recommended as part of a strong defensive coding strategy. The first line of function is a line containing opening brace '{' and the last is line containing closing brace '}'. The odds of intercepting defects increase with assertion density. See also: METRICS-31 SINCE v7. BENEFITS "Statistics for industrial coding efforts indicate that unit tests often find at least one defect per 10 to 100 lines of code written. Because assertions are side-effect free." EXAMPLE .and post-conditions of functions. they can be selectively disabled after testing in performance-critical code. 'c_assert'.g. 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.3 NOTES As assertion the rule sees any use of macro with name that ends with 'assert'. and loop-invariants.

void foo(int x. int y) { // Violation .#define c_assert(x) ((x) ? 1 : 0). c_assert(x).21 lines. void foo(int x. 2 assertion used */ /* Use of assertion */ /* Use of assertion */ . /* * code * * * * * * * * int y) { // OK . /* Some code c_assert(x).21 lines. 1 assertion used /* Some code */ c_assert(x). /* Use of assertion */ /* * code * * * * * * * * * * code * * * * */ } REPAIR #define c_assert(x) ((x) ? 1 : 0).

Rule 5 .Rules for Developing Safety Critical Code.* code * * * * */ } REFERENCES The Power of Ten .

e.conditional expression 'a?b:c' inside 'if'. 'for'.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. 'while'. METRICS-35 SINCE v7.'if'. METRICS-29. The metric is calculated according to the formula: EC = Number of unstructured decisions + 1 By decision we mean every occurrence of: . See also: METRICS-18. 'do-while' condition . The Essential Complexity metric quantifies the extent to which software is unstructured. or 'return' inside 'while' which is in turn inside 'for'.logical operator '&&' and '||' inside 'if'. 'do-while' condition By unstructured decisions we mean conditional jumps into or out of other decisions." By comparing Essential Complexity with Cyclomatic Complexity it's possible . METRICS-28. 'for'. If a decision contains unstructured decision then it's a unstructured decision itself. METRICS-34.g. 'for'. 'case' . 'while'. 'while'.Report Essential Complexity [METRICS-33-5] DESCRIPTION This rule reports the Essential Complexity value for each function. 'goto' inside 'if' which is in turn inside 'switch'. 'do-while'.

x || y.to find functions that are complicated but well structured. case 2: // +1 do { x++. . } REPAIR */ This rule is an informational rule and reports Essential Complexity on each function implementation. break. } OUT: if (y) { ++y. } } if (y) { goto END. which means they can be refactored. } while (x && y && (x * y < 100)).) { // +2 switch (x*y) { case 1: // +1 while (--x > 0) { // +1 if (x % y) { // +1 return. } } if (x > y) { // +1 goto OUT. int y) /* Violation: Essential Complexity = 8 { for(. } END: return. } break. EXAMPLE void Example(int x.

gov/HHRFdata/Artifacts/ITLdoc/235/chaptera. SE-2. Structured Testing: A Testing Methodology Using the Cyclomatic Complexity Metric NIST Special Publication 500-235 Chapter 10 Essential Complexity http://hissa. VOL. McCabe 308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING.4. A Complexity Measure Thomas J.REFERENCES 1.htm#446037 .nist. NO. DECEMBER 1976 2.

conditional expression 'a?b:c' inside 'if'. 'for'. BENEFITS "Structured programming avoids unmaintainable "spaghetti code" by . If a decision contains unstructured decision then it's a unstructured decision itself. 'goto' inside 'if' which is in turn inside 'switch'. 'while'. 'while'. The Essential Complexity metric quantifies the extent to which software is unstructured.3 NOTES Rule does not consider exception handling ('catch') as a decision. e. METRICS-28. METRICS-35 SINCE v7.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.'if'. An error is reported if a function have the Essential Complexity higher than 4. 'for'. 'do-while'. See also: METRICS-18. 'while'. 'for'. METRICS-29. 'do-while' condition By unstructured decisions we mean conditional jumps into or out of other decisions.g. 'do-while' condition . The metric is calculated according to the formula: EC = Number of unstructured decisions + 1 By decision we mean every occurrence of: . METRICS-33. 'case' .logical operator '&&' and '||' inside 'if'. or 'return' inside 'while' which is in turn inside 'for'.

x || y.) { // +2 switch (x*y) { case 1: // +1 while (--x > 0) { // +1 if (x % y) { // +1 return." By comparing Essential Complexity with Cyclomatic Complexity it's possible to find functions that are complicated but well structured. EXAMPLE void Example(int x.restricting the usage of control structures to those that are easily analyzed and decomposed. } */ . which means they can be refactored. } while (x && y && (x * y < 100)). } break. } } if (y) { goto END. break. } END: return. } } if (x > y) { // +1 goto OUT. } OUT: if (y) { ++y. case 2: // +1 do { x++. int y) /* Violation: Essential Complexity = 8 { for(.

VOL.4. McCabe 308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING.REPAIR This rule is an informational rule and reports Essential Complexity on each function implementation. DECEMBER 1976 2. A Complexity Measure Thomas J. SE-2.htm#446037 . Structured Testing: A Testing Methodology Using the Cyclomatic Complexity Metric NIST Special Publication 500-235 Chapter 10 Essential Complexity http://hissa. REFERENCES 1.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera. NO.nist.

METRICS-28. e.conditional expression 'a?b:c' inside 'if'. 'while'. 'do-while' condition . 'do-while' condition By unstructured decisions we mean conditional jumps into or out of other decisions. An error is reported if a function have the Essential Complexity higher than 10. If a decision contains unstructured decision then it's a unstructured decision itself. 'do-while'. The Essential Complexity metric quantifies the extent to which software is unstructured. METRICS-33. See also: METRICS-18.g. METRICS-29. 'case' . or 'return' inside 'while' which is in turn inside 'for'.logical operator '&&' and '||' inside 'if'. 'for'. METRICS-34 SINCE v7.3 NOTES Rule does not consider exception handling ('catch') as a decision. 'goto' inside 'if' which is in turn inside 'switch'. 'while'.'if'. BENEFITS "Structured programming avoids unmaintainable "spaghetti code" by . 'while'.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. 'for'. 'for'. The metric is calculated according to the formula: EC = Number of unstructured decisions + 1 By decision we mean every occurrence of: .

} } break. } while (x && y && (x * y < 100)).restricting the usage of control structures to those that are easily analyzed and decomposed. } END: return.x || y. int y) /* Violation: Essential Complexity = 12 { for(. } */ .) { // +2 switch (x*y) { case 1: // +1 for(. which means they can be refactored." By comparing Essential Complexity with Cyclomatic Complexity it's possible to find functions that are complicated but well structured. break. } } if (x > y) { // +1 goto OUT.x && y && x < y. case 2: // +1 do { x++. } } if (y) { goto END.) { // +3 while (--x > 0) { // +1 if (y && x % y) { // +2 return. EXAMPLE void Example(int x. } OUT: if (y) { ++y.

DECEMBER 1976 2.nist. NO.4. REFERENCES 1.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera. A Complexity Measure Thomas J.REPAIR This rule is an informational rule and reports Essential Complexity on each function implementation. SE-2. Structured Testing: A Testing Methodology Using the Cyclomatic Complexity Metric NIST Special Publication 500-235 Chapter 10 Essential Complexity http://hissa. McCabe 308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING. VOL.htm#446037 .

3 EXAMPLE void foo(){} /* Violation */ void goo1(){ foo(). /* 5 } void goo6(){ foo(). /* 3 } void goo4(){ foo(). SINCE v7. All calls within the same function are counted as 1. /* 2 } void goo3(){ foo(). /* 4 } void goo5(){ foo().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. . The rule is limited to translation unit scope. /* 6 } */ */ */ */ */ */ REPAIR void foo(){} /* OK */ void goo1(){ foo(). /* 1 } void goo2(){ foo().

} REFERENCES HIS Source Code Metriken. foo(). version 1.foo(). foo().3.1 Metrik "CALLING" . foo(). foo().

goo6().3 EXAMPLE void void void void void void void void goo1(){} goo2(){} goo3(){} goo4(){} goo5(){} goo6(){} goo7(){} goo8(){} void foo2() { goo1(). SINCE v7. goo4(). goo7(). goo5(). All calls of the same function are counted as 1. goo3().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. goo8(). } REPAIR void void void void void goo1(){} goo2(){} goo3(){} goo4(){} goo5(){} /* Violation */ . goo2().

goo3(). goo5().1 Metrik "CALLS" .void goo6(){} void goo7(){} void goo8(){} void foo1() { goo1().3. } /* OK */ void foo2() { foo1(). goo8(). goo2(). goo7(). goo4(). version 1. goo6(). } /* OK */ REFERENCES HIS Source Code Metriken.

Counted statements are: asm. /* } for(e = 0. empty. /* if(i){ /* i++. /* return i. /* }else{ i--. break.. /* } switch (i){ /* case 0: i = 7. return.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. e++){ /* while(i < 4) /* i = i + 4. switch. for. do. goto. /* case 2: i = 50. e < 1. /* foo2(). foo().3 EXAMPLE void foo(){} /* Violation */ void foo2(){} /* Violation */ int goo1(int i){ /* Violation int e. if. /* default: return i. /* return 0. continue. SINCE v7. /* case 1: i = 30. while and the top level expressions..The number of statements within function should be in range 1 . /* */ 1 2 3 4 5 */ */ */ */ */ 6 */ 7 */ 8 */ 9 */ 10 */ 11 */ 12 */ 13 */ 14 */ 15 */ .while.

} . if(i){ i++. if(i){ i++. e while(i < i = i } /* 16 */ /* /* /* /* /* 17 18 19 20 21 */ */ */ */ */ /* 22 */ /* 23 */ < 1. return i. default: return i. e while(i < i = i } switch (i){ case 0: i = 7. for(e = 0. }else{ i--. case 2: i = 50. } for(e = 0. i--. e++){ /* 44 */ 4) /* 45 */ + 4. }else{ i--. foo(). return i. /* 26 */ /* 27 */ /* 28 */ /* 29 */ /* 30 */ /* 31 */ < 1. foo2(). e++) /* /* /* /* /* /* /* /* 32 33 34 35 36 37 38 39 */ */ */ */ */ */ */ */ /* /* /* /* 40 41 42 43 */ */ */ */ < 1. return 0. return 0. } for(e = 0. i--. e++){ /* 24 */ 4) /* 25 */ + 4. a: foo(). case 1: i = 30. /* 46 */ . e . foo2().} .

/* 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. do{ i = (i < 4) ? 2 : 5.3. }while(i < 5).1 Metrik "STMT" . goto a. REFERENCES HIS Source Code Metriken. return 10. version 1.i = i + 5 + 4 * (2 / 3).

/=. . . sizeof. ||. return(2). for.N1 (38). default. if (2). . []. * + (8).3 EXAMPLE /* operators: brace{}(1). (). -.keywords: asm. char. continue. * . . <<=. ~. static. %=. float. n1 (9) * operands: int(4). ^=. ==. 2 (6). union. Rule reports a violation if the value of VOCF metric is higher than 4. -=. !=. double. *. else. b (3). <<. foo(1). register.(comma). extern. do. struct. ?:. restrict. *=. enum. . >. 3 (3) . = (2). >= (2).(semicolon). int.. %. ++. * (5).all identifiers which are not keywords . typedef. 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: . . i(9). const. signed.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. +=. <=. while Tokens recognized as operands: .(dot) . parentheses()(10). long. >>=. a(3).type specifiers: void. ->. switch. !. 1 (2).. --. ^. break. case. inline.constants: numbers and strings SINCE v7. return. short. goto. >=. unsigned . <:. <. volatile. auto. &=. /. &. +. >>.operators: =. {}. |=. <%. |.(ellipsis). &&. if.(6).

if(i >= 2) return b. * . b = a * 2. n1 (9) * operands: int(4). /* OK */ a = i + (2 * (i + 1)) + (3 * (i + 2)). = (2). return(2). b (3).N2 (31). >= (2). if(i >= 3) return a. } REFERENCES HIS Source Code Metriken. 2 (4). 3 (2) * . version 1. if (2). * + (4). if(i >= 3) return a. * (3). .06 */ int foo1(int i){ int a. i(6).* . parentheses()(5).(6). b = (i + (2 * (i + 1)) + (3 * (i + 2))) * 2.06 */ int foo(int i){ int a.N1 (27). foo(1).1 Metrik "VOCF" .N2 (25). /* Violation */ a = i + (2 * (i + 1)) + (3 * (i + 2)). if(i >= 2) return b. n2 (8) * VOCF = (N1 + N2) / (n1 + n2) = (27 + 25) / (9 + 8) = 3.3. 1 (1). } REPAIR /* operators: brace{}(1). int b. a(4). int b. n2 (8) * VOCF = (N1 + N2) / (n1 + n2) = (38 + 31) / (9 + 8) = 4.

.

and maintain. and often needlessly so. The rule as a level detects a block of code enclosed with curly braces '{}' SINCE v7. } } } } } } } /* /* /* /* /* OK */ OK */ OK */ OK */ Violation .3 BENEFITS Rule improves easier code understanding.level 5 /* OK .Violation on REPAIR Do not use excessive block nesting depth (more than 4 levels) . 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.Statements within function should not be nested deeper than 4 levels [METRICS-40-3] DESCRIPTION Statements should not be nested deeper than 4 levels.

version 1.1 Metrik "LEVEL" .REFERENCES HIS Source Code Metriken.3.

3 BENEFITS Rule improves readability and maintainability. do.2 2 block */ ( unsigned short s ) { int i. switch.2 /* Violation */ Counted statements are: asm.function 'comm' contains 20 statements and 4 blocks of comments . if. if (s > 0) i = 3. continue. for.The number of blocks of comments before and inside function to the number of statements in function should be > 0.while. if (s > 0) . return. else i = 4. EXAMPLE /* 1 block */ /* 1 block */ int comm /* Violation .. break. while and the top level expressions. SINCE v7.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.COMF = 0. empty..2 (BCOM + BCOB)/STMT <= 0. goto.

5 2 block */ ( unsigned short s /* 3 block */ /* 4 block */ ) { int i. /* 4 block */ if (s > 0){ i = 3. return i. if (s > 0) i = 3. if (s > 0) i = 3.function 'comm' contains 20 statements and 10 blocks of comments . i = 5. if (s > 0) i = 3. if (s > 0) i = 3.COMF = 0. . else i = 4.i = 3. else /* 3 block */ i = 4. else i = 4. } else i = 4. else i = 4. } REPAIR /* 1 block */ /* 1 block */ int comm1 /* OK . else i = 4.

else i = 4. /* 9 block */ else i = 4.if (s > 0) i = 3. if (s > 0) i = 3. if (s > 0) /* 8 block */ /* 8 block */ /* 8 block */ i = 3. if (s > 0){ i = 3.3. version 1. else i = 4. } else i = 4. if (s > 0) i = 3. /* 5 block */ /* 6 block */ else /* 7 block */ i = 4.1 Metrik "COMF" . }/* 10 block */ REFERENCES HIS Source Code Metriken. return i. i = 5.

inter-object class couples should be kept to a minimum. Other types of uses (for example simply declaring variable of the other class. the higher the sensitivity to changes in other parts of the design. or using typedef declared in the other class) does not count as coupling. The more independent a class is. Only method calls and variable references are counted. only defined methods are taken into account. }. In order to improve modularity and promote reuse. and therefore maintenance is more difficult.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. . When computing CBO value for a class. // class is not coupled to it's parents } int bar2() { x = 0. class B : public A { // CBO = 0 public: void bar1() { foo(). SINCE v9. The larger the number of couples. // class is not coupled to it's parents return y.2 EXAMPLE class A { // CBO = 0 public: void foo() {} int x. the easier it is to reuse it in another application. High coupling between object classes means modules depend on each other too much and will be hard to reuse.

June 1994 . }..foo(). No.bar2(). REFERENCES 1.} int y. 6. a. // coupling to A a. Vol 20. Kemerer A Metrics Suite for Object Oriented Design IEEE Transactions on Software Engineering. Shyam R. // coupling to B } }. Chris F. Chidamber.x = 0. // coupling to A return b. class C { // CBO = 2 public: int bar(A a) { B b.

Shyam R.2 EXAMPLE class A { // ID = 0 }. SINCE v9. No. In cases involving multiple inheritance. the number of methods it more difficult to values below 2. The deeper a class is in the hierarchy. Chris F. 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. Kemerer A Metrics Suite for Object Oriented Design IEEE Transactions on Software Engineering. Chidamber.Follow the limit for Inheritance Depth [METRICS-ID-5] DESCRIPTION The ordinal distance from the class to the root of the inheritance tree. June 1994 . class D { // ID = 0 }. REFERENCES 1.. 6. class B : public A { // ID = 1 }. class E : public C. the maximum length from to class to the root of the tree is taken into account. however. which make predict its behavior. It is often difficult to understand a system with many inheritance layers. the greater and state variables it is likely to inherit. public D { // ID = 3 }. class C : public B { // ID = 2 }. Vol 20. there is a greater potential reuse of tested inherited methods. If there are a majority of ID represent poor exploitation of the advantages of OO inheritance.

.

SINCE v9.all methods work on the same set of fields and perform common task). classes. only defined methods are taken into account.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) + . and 1 means class is not cohesive (lack of cohesion is at maximum). Only fields which are accessed by at least one method. LCOM can take values between 0 and 1. more targeted.Follow the limit for Lack Of Cohesion [METRICS-LCOM-1] DESCRIPTION LCOM = (avg(m(a)) . and methods which access at least one field are included in the count. Value 0 means that every field is used by every method (class is cohesive . + m(an)) / n Metric calculates Lack of Cohesion in Methods (Henderson-Sellers "LCOM3" or "LCOM*" variant).number of methods which use at least one field m(a) .. When computing LCOM value for a class. 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).number of methods which use field "a" avg(m(a)) .. where 0 means class is cohesive (lack of cohesion is at minimum). Cohesion is a measure of relatedness in a class.2 EXAMPLE . These classes may be candidates for refactoring into separate. If a class has low cohesion it may perform various tasks which have little relation to one another.m)/(1-m) m .

5 void foo1() { x = 0.class A { // LCOM = 0 void foo1() { x = 0. class B { // LCOM = 1 void foo1() { x = 0. }. }. } void foo2() { x = y. . y = 0. } void foo2() { y = x. int y. } int x. } int x. } void foo2() { y = 0. }. class C { // LCOM = 0. } int x. }. For example: class B1 { // LCOM = 0 void foo1() { x = 0. more targetted. } int x. int y. int y. REPAIR Consider splitting classes into separate. classes.

142-147. }. Lack of Cohesion in Methods http://eclipsemetrics. pp. REFERENCES 1.net/descriptions/pages/cohesion/LackOfCohesionInMethod s.html . 2. Henderson-Sellers.sourceforge. } int y. B.class B2 { // LCOM = 0 void foo2() { y = 0. Object-oriented metrics: measures of complexity Prentice-Hall. 1996.

C(float f).Follow the limit for Number Of Constructors [METRICS-NOCT-3] DESCRIPTION Number of constructors declared explicitly in a class. . class C { // NOCT = 4 public: C().2 EXAMPLE class A { // NOCT = 0 }. C(int i). C(const C& o). }. class B { // NOCT = 1 public: B(). }. SINCE v9.

float f. class B { // NOF = 3 public: int i. struct C { // NOF = 2 int i. float f.2 EXAMPLE class A { // NOF = 1 public: static int I.Follow the limit for Number Of Instance Fields [METRICS-NOF-4] DESCRIPTION Number of non-static fields in a type. }. }. }. . SINCE v9. private: int _i. long l.

This includes both instance and static fields declared in a type. struct B { // NOFT = 3 int i.2 EXAMPLE class A { // NOFT = 2 public: static int I. float f. float f. }. }.Follow the limit for Number Of Fields [METRICS-NOFT-2] DESCRIPTION Number of fields in a type. private: int _i. SINCE v9. long l. . }. union C { // NOFT = 2 int i.

}. . void foo(). class B { // NOM = 4 public: B().2 EXAMPLE class A { // NOM = 1 public: void foo(). }. ~B(). class C { // NOM = 0 public: static void foo().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. private: void bar(). }. static void bar(). SINCE v9.

}. static void bar(). void foo(). class B { // NOO = 4 public: B(). This includes both instance and static methods declared in a class. .Follow the limit for Number Of Methods [METRICS-NOO-4] DESCRIPTION Number of methods declared explicitly in a class. private: void bar(). ~B(). }. }. SINCE v9.2 EXAMPLE class A { // NOO = 2 public: void foo(). class C { // NOO = 1 public: static void foo().

SINCE v9. class C { // NPRIF = 0 }. This includes both instance and static fields declared in a type. }. class B { // NPRIF = 3 private: int _i. static float _F.Follow the limit for Number Of "private" Fields [METRICS-NPRIF-2] DESCRIPTION Number of private fields in a type. . }.2 EXAMPLE class A { // NPRIF = 1 public: static int I. private: int _i. static long _L.

class B { // NPRIM = 3 private: void foo(). This includes both instance and static methods declared in a class.Follow the limit for Number Of "private" Methods [METRICS-NPRIM-2] DESCRIPTION Number of private methods in a class. static void foo(int i). .2 EXAMPLE class A { // NPRIM = 1 public: static int foo(). SINCE v9. }. class C { // NPRIM = 0 }. static float bar(). private: int bar(). }.

class B { // NPROF = 3 protected: int _i.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. protected: int _i.2 EXAMPLE class A { // NPROF = 1 public: static int I. }. static long _L. SINCE v9. class C { // NPROF = 0 }. static float _F.

}. static float bar().2 EXAMPLE class A { // NPROM = 1 public: static int foo(). static void foo(int i). This includes both instance and static methods declared in a class. SINCE v9. }.Follow the limit for Number Of "protected" Methods [METRICS-NPROM-2] DESCRIPTION Number of protected methods in a class. class C { // NPROM = 0 }. class B { // NPROM = 3 protected: void foo(). protected: int bar(). .

static float _F. private: int _i. class C { // NPUBF = 0 }. .2 EXAMPLE class A { // NPUBF = 1 public: static int I. }. class B { // NPUBF = 3 public: int _i.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. static long _L. }. SINCE v9.

This includes both instance and static methods declared in a class. class C { // NPUBM = 0 }. }. . protected: int bar(). static float bar(). class B { // NPUBM = 3 public: void foo(). }.Follow the limit for Number Of "public" Methods [METRICS-NPUBM-2] DESCRIPTION Number of public methods in a class. SINCE v9. static void foo(int i).2 EXAMPLE class A { // NPUBM = 1 public: static int foo().

float f. }. long L. float F.Follow the limit for Number Of Static Fields [METRICS-NSF-3] DESCRIPTION Number of static fields in a type. . // NSF = 3 int I.2 EXAMPLE class A { // NSF = 1 public: static int I. private: int _i. }. struct C { // NSF = 0 int i. SINCE v9. class B { public: static static static }.

private: int bar(). }. SINCE v9.Follow the limit for Number Of Static Methods [METRICS-NSM-3] DESCRIPTION Number of static methods in a class. class C { // NSM = 0 }. .2 EXAMPLE class A { // NSM = 1 public: static int foo(). // NSM = 3 int foo(). float bar(). long foo(int i). class B { public: static static static }.

float and double should not be used. int. 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] . short.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. long.

h header and setlocale function [MISRA-121_b-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.h header and setlocale function [MISRA-121_a-3] Do not use locale. 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.

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. if ((j < 10) && (j >= 0)) /* OK */ { m = k[j]. } } REFERENCES Origin: Misra Guidelines . int m. BENEFITS This rule prevents from getting/putting values which are out of range. int k[10]. int m. m = k[j]. /* Violation */ } REPAIR void moo() { int j.Rule 4 . EXAMPLE void foo() { int j. int k[10].

.

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. } /* Violation */ REPAIR Do not use left shifting of an integer. int j = 2. BENEFITS Prevents from overflow. EXAMPLE void main() { int i = 4. int k = j << i. effectively a kind of overflow. REFERENCES Origin: Misra Guidelines .Rule 4 .

\"' . even if the compiler supports a larger character set.the space character.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.?*+-/^&|~!=.the 10 decimal digits 0 1 2 3 4 5 6 7 8 9 . vertical tab..the following 29 graphic characters _{}[]#()<>%:. form feed and new line. Those . char c2 = '`'. EXAMPLE void foo() { char c1 = '$'.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 . Section 5.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 . BENEFITS Minimal required character set. } /* Violation */ /* Violation */ .1 of the ISO C standards defines 91 characters which are the minimum source character set for all compilers. or supports alternative character sets. and control characters representing horizontal tab.2. These are the only characters that should be used.

AIR VEHICLE. Origin: Misra Guidelines . C++ CODING STANDARDS Chapter 4.Rule 5 2.REPAIR Do not use characters no defined in the ISO C standard. REFERENCES 1.4 Environment. JOINT STRIKE FIGHTER. AV Rule 9 .

4 Environment. } REPAIR Define character types as subset of ISO 10646-1. AIR VEHICLE. AV Rule 10 . REFERENCES 1. EXAMPLE void foo() { const char * s[] = {"a".Rule 006 2. "\012" /* Violation */ }." Explicitly specified numeric value of character may not conform to chosen subset of ISO 10646-1. C++ CODING STANDARDS Chapter 4. BENEFITS Values of character types are defined and documented as subset of ISO 10646-1.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. JOINT STRIKE FIGHTER. Origin: Misra Guidelines . and the chosen subset shall be documented.

EXAMPLE #include <stddef. AIR VEHICLE. JOINT STRIKE FIGHTER. AV Rule 13 . Origin: Misra Guidelines .h> void foo() { wchar_t* x = L"Fred".h> void foo() { char* x = "Fred"./* OK */ } REFERENCES 1. C++ CODING STANDARDS Chapter 4.Do not use wide string literals [MISRA-008-3] DESCRIPTION Wide string literals shall not be used.Rule 8 2. BENEFITS Prevents from various undefined and implementation-defined behaviours associated with them and they shall not be used.4 Environment./* Violation */ } REPAIR #include <stddef.

See also: MISRA2004-6_3 EXCEPTIONS Rule does not report a violation for: .g." EXAMPLE typedef signed int my_int.extern variable declaration . signed char) or typedef name does not contain any digits indicating the size (e. It is safer if programmers work with types which they know to be of a given length. long.g. /* Violation (for return type) */ /* Violation */ /* Violation */ /* Violation */ /* Violation */ ."main" function return type . but does not guarantee portability because of the asymmetric behaviour of integral promotion. /* Violation .bit-field types. but specificlength equivalents should be typedef'd [MISRA-013-3] DESCRIPTION "The storage length of types can vary from compiler to compiler. return 1. short. float and double should not be used. my_int).not typedef */ short int foo( char* p_char.The basic types of char. int. 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. float& r_float) { double h. /* Violation . .no digits */ static signed char a. const int z = 1.typedef name which starts with 'bool' prefix.boolean and enum types ." Rule reports a violation message if basic numerical type is used (e.

typedef short int s16_t. int main() { return 0. typedef const int cs32_t. } /* Correct use of typedef: */ typedef signed int my_int32. }. Rule 3-9-2 . typedef float& float32ref. Section 3. enum ENUM { EV }. float32ref r_float) { float64 h. typedef signed char int8_t. cs32_t z = 1. typedef unsigned char BOOL. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. typedef double float64. Misra Guidelines .Rule 13 2. bool b. s16_t foo( char_t* p_char.} REPAIR /* Exceptions: */ typedef char char_t. prefix */ struct STRUCT { unsigned int i:2. } /* 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. Chapter 6. return 1. extern signed char a.

then a violation is reported only on a typedef declaration. // OK unsigned char foo(unsigned char) // OK { . // Violation // Violation REPAIR typedef unsigned char CHAR. CHAR var2.Violation is reported on a typedef declaration char (*fptr1)().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. void (*fptr2)(char). (and more portable) to always specify whether the signed or unsigned. EXAMPLE typedef char CHAR." NOTES If a type of variable is a typedef to char. } // Violation x 2 // Violation // OK . // Violation char foo(char) { char var1. BENEFITS Complying with this rule leads to safer and more readable code.

Origin: Misra Guidelines .Port.chris-lott.Rule 14 2. // OK // OK REFERENCES 1. // OK // OK } unsigned char (*fptr1)(). CHAR var2. Ellemtel Coding Standards http://www.18. Rec. 4 .unsigned char var1.html From: 18 Portable Code . void (*fptr2)(unsigned char).org/resources/cstyle/Ellemtel-rules-mm.2 Sizes of Types .

/* /* /* /* Violation Violation Violation Violation } REPAIR void foo() { int* pi.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. (int*)pd. double* pd. (long*)pf. float* pf. double* pd. long * pl. } /* OK */ /* OK */ */ */ */ */ . float* pf. pf = (float*)pd. short int* ps. pi pi ps pl = = = = (int*)pf. ps = (short*)pi. EXAMPLE void foo() { int* pi. (short*)pf. short int* ps. BENEFITS Prevents from casting with possible data losing.

JOINT STRIKE FIGHTER.17 Types.REFERENCES 1. AIR VEHICLE. Origin: Misra Guidelines . AV Rule 147 . C++ CODING STANDARDS Chapter 4.Rule 16 2.

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.Rule 18 . /* OK */ REFERENCES Origin: Misra Guidelines .Use type suffix for numeric constants [MISRA-018_a-5] DESCRIPTION Numeric constants should be suffixed to indicate type.

/* OK */ 32767. . 32767. 65535. /* OK */ 32768. 4294967295 }. 32768. Rule checks only value between 65536 and 2147483647./* Violation */ 2147483648.Use type suffix for numeric constants [MISRA-018_b-5] DESCRIPTION Numeric constants should be suffixed to indicate type. /* OK */ 2147483547L./* OK */ 1. 65536. EXAMPLE unsigned long arrL[] = { 0. /* Violation */ 2147483547. 1./* OK */ 4294967295/* OK */ }./* OK */ 2147483648. where an appropriate suffix is available. BENEFITS Rule improves readability and maintainability./* OK */ 65536L. /* OK */ 65535. REPAIR unsigned long arrL[] = { 0.

REFERENCES Origin: Misra Guidelines .Rule 18 .

/* Violation */ REPAIR unsigned long lVar = 32768U. /* OK */ unsigned long lVar3 = 32767. BENEFITS Rule improves readability and maintainability.Rule 18 . /* OK */ unsigned long lVar4 = 65536. EXAMPLE unsigned long lVar = 32768. where an appropriate suffix is available.Use type suffix for numeric constants [MISRA-018_c-5] DESCRIPTION Numeric constants should be suffixed to indicate type. /* OK */ REFERENCES Origin: Misra Guidelines . Rule checks only value between 32768 and 65535.

EXAMPLE unsigned long arrL[] = { 0. /* OK */ 65535U./* OK */ 2147483648. 32767. where an appropriate suffix is available.Use type suffix for numeric constants [MISRA-018_d-5] DESCRIPTION Numeric constants should be suffixed to indicate type. /* Violation */ 65536. . /* OK */ 32768U. BENEFITS Rule improves readability and maintainability./* OK */ 1. 32768. 4294967295 }./* OK */ 4294967295/* OK */ }. 2147483648. /* OK */ 2147483547. REPAIR unsigned long arrL[] = { 0. /* Violation */ 65535. /* OK */ 32767. 1. Rule checks only value between 32768 and 65535./* OK */ 65536. 2147483547.

Rule 18 .REFERENCES Origin: Misra Guidelines .

the compiler will have to make assumptions about the function prototype.function undeclared */ /* Violation .h----------------void foo1_h(). This may lead to undefined behavior. EXAMPLE void goo() { foo1(). which can result in hard-to-find errors at runtime. void foo2_h(){} //--------file. and will not verify if actual parameter types match types specified in function declaration.h" void foo1(). } void foo2(). If undeclared function is found. foo2(). NOTES This rule active for C code only.c----------------#include "file. A declaration provides information to the compiler about the type of function. BENEFITS The rule prevents undefined behaviours.function declared after use */ REPAIR //--------file. /* Violation . .All functions shall be declared before use [MISRA-020-3] DESCRIPTION Rule requires that all functions must be declared before they are used.

Misra Guidelines .void foo2(){} void goo() { foo1(). foo1(). } /* /* /* /* OK OK OK OK - function function function function declared before use */ defined before use */ declared in header */ defined in header */ REFERENCES 1. foo2().Rule 20 2. Multiplatform Porting to 64 Bits http://www.com/showArticle.jsessionid=GJEIYBMN14LMIQSNDBCSKHSCJU MEKJVN?articleID=184406427 . foo2().ddj.jhtml.

Ellemtel Coding Standards http://www. ISO/DIS 26262 point 8.org/resources/cstyle/Ellemtel-rules-mm. 57 3.15 Declarations and Definitions.4.Declare objects at function scope [MISRA-022-5] DESCRIPTION Declarations of objects should be at function scope unless a wider scope is necessary.4 .Rec. Misra Guidelines . AV Rule 136 4.chris-lott. C++ CODING STANDARDS Chapter 4.Rule 22 2. BENEFITS Prevents using global variables. // Violation REPAIR void foo( ) { int localVar. AIR VEHICLE. JOINT STRIKE FIGHTER. EXAMPLE int globalVar.html From: 16 Memory Allocation . } // OK REFERENCES 1.

/* Violation */ REPAIR static int g2. Origin: Misra Guidelines .Make declarations at file scope static where possible [MISRA-023-5] DESCRIPTION All declarations at file scope should be static where possible. JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4.15 Declarations and Definitions.Rule 23 2. /* OK */ REFERENCES 1. /* Violation */ void foo1() {}. /* OK */ static void foo2(){}. AIR VEHICLE. BENEFITS Prevents from accidentally overwriting of functions or variables EXAMPLE int g1. AV Rule 137 .

C++ CODING STANDARDS Chapter 4. static unsigned short y. REFERENCES 1. EXAMPLE static unsigned short x.Rule 24 2. // Violation } } REPAIR Do not declare variables simultaneously with internal and external linkage in the same translation unit. Origin: Misra Guidelines . void foo( ) { extern unsigned short x.15 Declarations and Definitions. // Violation { extern unsigned short y. AIR VEHICLE.Use consistent linkage for identifiers [MISRA-024-3] DESCRIPTION Identifiers shall not simultaneously have both internal and external linkage in the same translation unit. // Violation extern unsigned short y. JOINT STRIKE FIGHTER. AV Rule 138 . BENEFITS Rule prevents variable-name hiding which can be confusing.

REPAIR /* misra_027.Rule 27 2. AIR VEHICLE.h" extern int a. C++ CODING STANDARDS Chapter 4.h" int a. */ extern int a. /* OK */ /* misra_027.h */ extern int a.c */ #include "misra_027. EXAMPLE /* misra_027.h */ /* Do not declare external object in more than one file. /* Violation */ /* misra_027. AV Rule 139 .15 Declarations and Definitions. clarity of code and prevents errorneous code. This rule will inform about multiple declarations of symbols.c */ #include "misra_027. BENEFITS Rule improves readability. Origin: Misra Guidelines . REFERENCES 1. JOINT STRIKE FIGHTER.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.

.

15 Declarations and Definitions.Do not use register storage class [MISRA-028-5] DESCRIPTION The register storage class specifier shall not be used. EXAMPLE void foo() { register int a. Origin: Misra Guidelines .Rule 28 2. JOINT STRIKE FIGHTER. } // Violation REPAIR Do not use the 'register' storage class specifier. AV Rule 140 . BENEFITS Prevents from dependencies on compiler. REFERENCES 1. C++ CODING STANDARDS Chapter 4. AIR VEHICLE.

'char *' initialiser does not match type of field _x: */ REPAIR struct tagSTRUCT { int _x. /* Violation . BENEFITS Rule improves readability. struct tagSTRUCT s = { 123 }.The use of a tag shall agree with its declaration [MISRA-029-3] DESCRIPTION The use of a tag shall agree with its declaration.initialiser of type int matches type of field _x: */ REFERENCES Origin: Misra Guidelines . This rule will report violation when tag initializers do not agree with the structure declared for that tag. struct tagSTRUCT t = { "abc" }. clarity of code and prevents error prone code. EXAMPLE struct tagSTRUCT { int _x. This rule is active for C code only. }.Rule 29 . /* OK . }.

b++. EXAMPLE void foo( ) { int b. This does not necessarily require initialisation at declaration. b++.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. "Effective C++: 55 Specific Ways to Improve . 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. } // Violation REPAIR void foo( ) { int b = 0. Scott Meyers. BD-PB-NOTINIT NOTES The rule assumes that local variable might be initialized by passing its non-const pointer to an external function. INIT-14. } // OK REFERENCES 1. INIT-10. BENEFITS Prevents reading from uninitialized variables.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.1 4. AV Rule 142 6. (C) 2005 Pearson Education.Your Programs and Design". Ellemtel Coding Standards http://www. AIR VEHICLE.16 Initialization. Rule 8-5-1 . Section 9.chris-lott. Section 8..Rule 30 3. Inc. Chapter 6.Rule 40 5. Item 4 2. Misra Guidelines . rule 9. JOINT STRIKE FIGHTER.org/resources/cstyle/Ellemtel-rules-mm. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Chapter 1. C++ CODING STANDARDS Chapter 4.html#11 From: 11 Variables . Addison-Wesley. Third Edition.

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.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). uint16_t. 8. Rule makes assumptions about size of types: char has 8 bits. // 16. uint32_t. it32. BENEFITS Rule makes the code more readable and less confusing. { it8. // it8. long has 64 bit. short has 16 bit.// Violation Violation Violation Violation } REPAIR #ifndef uint8_t typedef unsigned char uint8_t. int has 32 bit. it16. . // 32.

it8 << 7. if (it8 > 0 it16 >> // OK // OK // OK && it8 < sizeof( it8 )) it8. { it8. uint32_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. it32. // OK } REFERENCES Origin: Misra Guidelines . it16 << 15. it16. it32 >> 31.Rule 38 .

int k. Origin: Misra Guidelines . BENEFITS Prevents unexpected loss of data/precision. there must be comment on the previous line.Rule 41 . /* OK . This rule checks that. /* Violation . int j=3. int k.Document integer division [MISRA-041-5] DESCRIPTION The implementation of integer division in the chosen compiler should be determined. k=j/i. wherever there is an integer division in the code. } REFERENCES 1.no comment before division*/ } REPAIR void boo() { int i=2. int j=3. documented and taken into account. EXAMPLE void foo() { int i=2.comment before integer division */ k=i/j.

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

"C").h> and the setlocale function shall not be used. BENEFITS Prevents changing the locate from the standard C locate.Do not use locale. } REPAIR Do not use 'setlocale' functions.Rule 121 .h> /* Violation */ void foo(void) { /* Set the locale back to the default environment */ setlocale(LC_ALL. EXAMPLE #include <locale. REFERENCES Origin: Misra Guidelines .h header and setlocale function [MISRA-121_b-3] DESCRIPTION <locale.

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] . 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.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.

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] .

?:) [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] . || 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 (&&. =. !. ==.The operands of logical operators (&&. !=. ||.

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] .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.. 'break'. 'continue'.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'..

'do. and no other code [MISRA2004-15_0_a-3] A switch statement shall only contain switch labels and switch clauses..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.. 'while'.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'. 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. either directly or indirectly [MISRA2004-16_2-3] .. and no other code [MISRA2004-15_0_b-3] A switch statement shall only contain switch labels and switch clauses.. then that error information shall be tested [MISRA2004-16_10-3] Functions shall not call themselves.

>=. <= 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] .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] >. <.

exit.h shall not be used [MISRA2004-20_12-3] Reserved identifiers. shall not be defined. #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. 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. atoi and atol from library stdlib. getenv and system from library stdlib.h shall not be used [MISRA2004-20_10-3] The library functions abort. 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] . redefined or undefined [MISRA2004-20_1_a-3] Do not redefine reserved words [MISRA2004-20_1_b-3] The names of standard library macros.h shall not be used [MISRA2004-20_11-3] The time handling functions of library time. macros and functions in the standard library.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.

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. 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..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 /* . in library stddef. 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.. 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] .h.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. */ 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.

its type shall be explicitly stated [MISRA2004-8_2_a-3] Whenever an object is declared or defined. unless all items are explicitly initialised [MISRA2004-9_3-3] . the "=" construct shall not be used to explicitly initialise members other than the first. 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. its size shall be stated explicitly or defined implicitly by initialisation [MISRA2004-8_12-3] Whenever a function is declared or defined.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.

s32b." EXAMPLE void Conv1_int( ) { unsigned int u32a.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. signed int s32a. /* Violation */ /* Violation */ } REPAIR void Conv1_int( ) { unsigned int u32a. u32b.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. s32a = u32a. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. s32b. u32b. s32a = (signed int)u32a. /* OK */ . signed int s32a." Rule checks if implicit conversions between signed and unsigned types are used. s32b = s32a + u32a. SINCE v7.

Section 5.4.s32b = s32a + (signed int)u32b. Rule 5-0-4 3. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 10 2. /* OK */ } REFERENCES 1. ISO/DIS 26262 point 8. Chapter 6.4 .

unsigned int u32a." Rule checks if implicit conversions between integer and floating types are used. /* Violation */ /* Violation */ /* Violation */ . f32a = u32a. f32a = f32a + u32a. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.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. } REPAIR void Conv1_int( ) { float f32a. SINCE v7. 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." EXAMPLE void Conv1_int( ) { float f32a.5f.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. f32a = u32a + 2. unsigned int u32a.

Chapter 6.4. /* OK */ /* OK */ /* OK */ } REFERENCES 1. Section 5. Section 10 2. f32a = (float)u32a + 2. f32a = f32a + (float)u32a.4 . ISO/DIS 26262 point 8.5f. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.f32a = (float)u32a. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 5-0-5 3.

The word 'notionally' is used because. The expression u16a + u16b + u32c is not compliant . 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. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.u16b." EXAMPLE void Conv1_int( ) { unsigned short u16a. in practice. 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 first addition is notionally performed in type U16 and the second in type U32. u32b.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.both additions will notionally be performed in type U32." "The intention when restricting implicit conversion of complex expressions is to require that in a sequence of arithmetic operations within an expression. the type in which arithmetic will be conducted will depend on the implemented size of an int. The expression u32a + u16b + u16c is compliant .0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." Rule checks if implicit conversions of complex expressions are used. unsigned int u32a. . SINCE v7.

u16b. /* Violation */ /* Violation */ } REPAIR void Conv1_int( ) { unsigned short u16a. u32a = u32b + u16b + u16a. u32a = u16b + (u16a + u32b).u32a = u16b + u16a + u32b. Section 5.4 . /* OK */ /* OK */ } REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. u32a = u32b + (u16a + u16b). ISO/DIS 26262 point 8. Rule 5-0-3 3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.4. Section 10 2. u32b. unsigned int u32a.

SINCE v7. 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. (char." . bit-field and enum) are always converted to type int or unsigned int before an arithmetic operation. Integral promotion describes a process whereby arithmetic operations are always conducted on integer operands of type int or long (signed or unsigned).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. short. BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. 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.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. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. Operands of any other integer type.

unsigned int u32a. unsigned int u32a. u8a = (unsigned char)u32a.EXAMPLE void Conv1_int( ) { unsigned char u8a. unsigned short u16a. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. /* OK */ /* OK */ } REFERENCES 1. u16a = (unsigned short)u32a. unsigned short u16a. u16a = u32a. Section 10 2. /* Violation */ /* Violation */ } REPAIR void Conv1_int( ) { unsigned char u8a. Chapter 6. u8a = u32a. Section 5. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 5-0-6 .

Integral promotion describes a process whereby arithmetic operations are always conducted on integer operands of type int or long (signed or unsigned). bit-field and enum) are always converted to type int or unsigned int before an arithmetic operation. short. Operands of any other integer type." Rule checks if implicit conversions of function return expressions are used. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. /* Violation */ } REPAIR unsigned int Conv_ret1( signed char a ) .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. (char." EXAMPLE unsigned int Conv_ret1( signed char a ) { return a.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. SINCE v7. 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.

4.4 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 10 2. ISO/DIS 26262 point 8.{ return (unsigned int)a. /* OK */ } REFERENCES 1.

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. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.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.u16b. Rule does not report any violations if an expression is more complex.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." "The intention when restricting implicit conversion of complex expressions is to require that in a sequence of arithmetic operations within an expression." Rule checks if implicit conversions of complex expressions are used. . SINCE v7." DRAWBACKS Rule checks only the simple expressions. unsigned int u32a. all operations should be conducted in exactly the same arithmetic type. EXAMPLE void Conv1_int( ) { unsigned short u16a.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. /* Violation */ } REPAIR void Conv1_int( ) { unsigned short u16a.u16b. u32a = (unsigned int)(u16b + u16a). MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.4.4 . Section 10 2. Section 5. /* OK */ } REFERENCES 1. Rule 5-0-3 3.u32a = u16b + u16a. Chapter 6. ISO/DIS 26262 point 8. unsigned int u32a.

SINCE v7. bit-field and enum) are always converted to type int or unsigned int before an arithmetic operation. takes_signed_double(si). /* Violation */ } . Operands of any other integer type. short. 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. void foo(signed int si. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. /* Violation */ takes_unsigned_int(uc).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. void takes_unsigned_int(unsigned int). unsigned int ui) { unsigned char uc." EXAMPLE void takes_signed_double(double). Integral promotion describes a process whereby arithmetic operations are always conducted on integer operands of type int or long (signed or unsigned). void takes_signed_int(signed int)." Rule checks if implicit conversions of function arguments are used.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. /* Violation */ takes_signed_int(ui). (char.

void takes_unsigned_int(unsigned int). MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. void takes_signed_int(signed int). void foo(signed int si. takes_signed_int((int) ui). } /* OK */ /* OK */ /* OK */ REFERENCES 1.4 . ISO/DIS 26262 point 8. Section 10 2. takes_signed_double((double) si).4. takes_unsigned_int(ui).REPAIR void takes_signed_double(double). unsigned int ui) { unsigned char uc.

} /* OK */ . SINCE v7. signed int s32a = u32a." EXAMPLE void Conv1_int( ) { unsigned int u32a. signed int s32a = (signed int)u32a. 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.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. } /* Violation */ REPAIR void Conv1_int( ) { unsigned int u32a. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion." Rule checks if implicit conversions between signed and unsigned types are used when variables are initialized.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.

4. Chapter 6. Section 10 2. ISO/DIS 26262 point 8. Rule 5-0-4 3.4 . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 5.

it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.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. SINCE v7.u16b. 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. unsigned int u32a = u16b + u16a." Rule checks if implicit conversions of complex expressions are used. } /* Violation */ . all operations should be conducted in exactly the same arithmetic type." DRAWBACKS Rule checks only the simple expressions. EXAMPLE void Conv1_int( ) { unsigned short u16a.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type. Rule does not report any violations if an expression is more complex." "The intention when restricting implicit conversion of complex expressions is to require that in a sequence of arithmetic operations within an expression.

u16b. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.4 . Section 5. Section 10 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.4. Rule 5-0-3 3. ISO/DIS 26262 point 8. } /* OK */ REFERENCES 1.REPAIR void Conv1_int( ) { unsigned short u16a. Chapter 6. unsigned int u32a = (unsigned int)(u16b + u16a).

unsigned int u32a. u32b. } REPAIR unsigned short goo_float( ) { double f64a. float f32a. f32b + f32a + f64b. f64b.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.s32b. signed int s32a. f32b. f32b. f64a." EXAMPLE unsigned short goo_float( ) { double f64a. unsigned int u32a. u32b. float f32a. // // // // Violation Violation Violation Violation . it is possible to avoid programmer confusion and some of the dangers associated with integral promotion. signed int s32a. u32b s32b f32a f64a = = = = f32a. f32a.s32b.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." SINCE v7. f64b.

Rule 5-0-5 4. C++ CODING STANDARDS Chapter 4. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. (signed int)f32a. MISRA-C:2004 Guidelines for the use of the C language in critical systems 2. Rule 5-0-6 5. AV Rule 184 3. Chapter 6. ISO/DIS 26262 point 8. (float)f64b. f64b + f32b + f32a. Chapter 6.4. AIR VEHICLE. // // // // OK OK OK OK } REFERENCES 1.u32b s32b f32a f64a = = = = (unsigned int)f32a. Section 5. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.23 Type Conversions.4 . Section 5. JOINT STRIKE FIGHTER.

0.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. // Violation // Violation // Violation . unsigned short u16a = 1. void goo_float( ) { double f64a. unsigned int u32a = f32a. float f32a.0 BENEFITS "By observing the principle whereby all operations are performed in a consistent (underlying) type." EXAMPLE typedef float float32_t. float32_t f32bt = f64a. void goo_float( ) { double f64a. float f32a. } REPAIR typedef float float32_t." SINCE v7. it is possible to avoid programmer confusion and some of the dangers associated with integral promotion.

Section 5. Section 5. AIR VEHICLE. // OK unsigned int u32a = (unsigned int)f32a. Rule 5-0-5 4.4 . Chapter 6. // OK } REFERENCES 1. JOINT STRIKE FIGHTER. ISO/DIS 26262 point 8. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. C++ CODING STANDARDS Chapter 4.float32_t f32bt = (float)f64a.23 Type Conversions. AV Rule 184 3.4. Chapter 6.0. MISRA-C:2004 Guidelines for the use of the C language in critical systems 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 5-0-6 5. // OK unsigned short u16a = (unsigned short)1.

" BENEFITS The rule prevents behaviours inconsistent with developer expectations.e. /* wider type */ d = (double)(ui1 * ui2). /* unsigned type */ si1 = (signed int)(ui1 / ui2). double d. "The term 'complex expression' is defined to mean any expression that is not: . /* signed type */ ui1 = (unsigned int)(us1 . signed int si1.us2).cast from unsigned to Violation . unsigned short us1. us2.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. si2.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. /* floating type */ } Violation .a constant expression . ui2.cast from signed to Violation .an lvalue (i.cast from integer to .cast from narrower to Violation . ui1 = (unsigned int)(si1 + si2). EXAMPLE void myFunction() { unsigned int ui1. an object) .

Chapter 6. Rule 5-0-8 4.(unsigned int)us2. /* /* /* /* OK OK OK OK */ */ */ */ } REFERENCES 1. double d. = (signed int)ui1 / (signed int)ui2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. (double)ui1 * (double)ui2. Section 5.REPAIR void myFunction() { unsigned int ui1. Section 5. Rule 5-0-7 3. signed int si1. Rule 5-0-9 . unsigned short us1. Section 5. ui2. us2. Chapter 6. = (unsigned int)us1 . Section 10 2. si2. Chapter 6. ui1 si1 ui1 d = = (unsigned int)si1 + (unsigned int)si2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.

f32b. float64_t f64a. /* Violation */ } REPAIR typedef float typedef double typedef long double float32_t. float32_t f32a. the type of cast that may be applied is severely restricted. void goo( ) { float128_t f128a. f32b. Conversions on complex expressions are often a source of confusion and it is therefore wise to be cautious." BENEFITS Prevents loss of data. float64_t. float64_t. float64_t f64a. (float32_t)(f64a + f64b). f64b. f128b.cast to narrow float type */ . float32_t f32a. void goo( ) { float128_t f128a. } /* OK .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. float128_t. float128_t. (float64_t)(f32a + f32b). EXAMPLE typedef float typedef double typedef long double float32_t. f128b. f64b.

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

uint8_t result_8. A similar problem exists when the << operator is used on small integer types and high order bits are retained. */ result_16 = ((port << 4) & mode) >> 6. result_8 = (~port) >> 4. 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). uint16_t mode. /* Violation /* Violation .If the bitwise operators ~ and << are applied to an operand of underlying type unsigned char or unsigned short. void foo() { uint8_t port = 0x5aU. EXAMPLE typedef unsigned char uint8_t. uint16_t result_16." BENEFITS Rule prevents high order bits retaining. typedef unsigned short uint16_t. the operations are preceded by integral promotion. */ } REPAIR typedef unsigned char uint8_t. and the result may contain high order bits which have not been anticipated. typedef unsigned short uint16_t.

uint16_t mode. } /* OK */ /* OK */ /* OK */ REFERENCES 1.void foo() { uint8_t port = 0x5aU. Section 10 2. uint8_t result_8. uint16_t result_16. result_8 = ((uint8_t)(~port)) >> 4 . result_16 = ( (uint16_t) (~(uint16_t)port) ) >> 4 . result_16 = ((uint16_t)((uint16_t)port << 4) & mode) >> 6. Chapter 6. Section 5. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 5-0-10 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.

MISRA-018_c.The implemented sizes of the integer types . EXAMPLE /* the type depends from the implemented size of the various integer types */ long lVar = 2147483648. See also: MISRA-018_a.The magnitude of the constant . however its presence is a valuable contribution towards clarity.The number base in which the value is expressed (i. When applied to larger values. MISRA2004-10_1_h BENEFITS Rule improves readability and maintainability. MISRA-018_b.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. the suffix may be redundant (in the sense that it does not influence the type of the constant). decimal." The rule checks if integer constant of unsigned type has 'U' or 'u' suffix. /* OK */ . Consistent signedness is an important principle in constructing well formed expressions. because it is dependent on a complex combination of factors including: .e.The presence of any suffixes . If a constant is of an unsigned type. MISRA200410_1_a. /* Violation */ REPAIR long lVar = 2147483648U. MISRA-018_d. it is helpful to avoid ambiguity by applying a “U” suffix. octal or hexadecimal) Signedness of constants should be explicit.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.REFERENCES 1. Origin: Misra Guidelines .Rule 18 . Section 10 2.

fp1 = t2. No other conversion involving function pointers are permitted. int* ptr_int. As integral types the rule detects the following types: bool. wchar_t and typedefs to mentioned types. short. EXAMPLE /* Examples of incorrect code */ typedef int (*func_t1)(). t1 = t2. t1 = (func_t2)t1. } /* /* /* /* /* Violation Violation Violation Violation Violation */ */ */ */ */ . char. func_t1 t1 . func_t2 t2 . typedef short (*func_t2)(). int. ptr_int = t1." This rule allows conversions between two pointers to function if these pointers have exactly the same type. void foo() { int (*fp1)(char* c). long. This means that a function pointer can be converted to or from and integral type. t1 = fp1.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. BENEFITS Prevents undefined behaviour and loss of data. long long.

int func (). void foo() { func_t1 t1 . typedef int (*func_t2)(). i = t1.REPAIR /* Examples of correct code */ typedef int (*func_t1)(). int i. /* OK */ /* OK */ /* OK */ } REFERENCES MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. func_t2 t2 . t1 = t2. t1 = func. Section 11 .

int_p = (int*)fl. REFERENCES .conversion between pointer to object and pointer to function type */ int_p = incomplete_type_ptr. 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. void foo(int* int_p. struct A. EXAMPLE typedef int (*FunctionPointer)(void).conversion between pointer to object and floating type */ funct_ptr = (FunctionPointer)int_p.Conversions shall not be performed between a pointer to object and any type other than an integral type. /* Violation .conversion between pointer to object and pointer to incomplete type */ } REPAIR Do not perform illegal conversions. MISRA2004-11_2_c BENEFITS Rule prevents undefined conversions. /* Violation . float fl. /* Violation . FunctionPointer funct_ptr) { struct A *incomplete_type_ptr.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 11 .

void someFunction(int *). See also: MISRA2004-11_2. struct A. MISRA2004-11_2_c BENEFITS Rule prevents undefined conversions. /* Violation .conversion between pointer to object and pointer to incomplete type */ someFunction(funct_ptr). EXAMPLE typedef int (*FunctionPointer)(void). someFunction(incomplete_type_ptr).Conversions shall not be performed between a pointer to object and any type other than an integral type.conversion between pointer to object and pointer to function type */ } REPAIR . /* Violation . void foo(FunctionPointer funct_ptr) { struct A *incomplete_type_ptr. 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.

Do not perform illegal conversions. Section 11 . REFERENCES MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.

struct A.conversion between pointer to object and pointer to incomplete type */ /* Violation . } } /* Violation . 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. int flag) { struct A *incomplete_type_ptr.Conversions shall not be performed between a pointer to object and any type other than an integral type. See also: MISRA2004-11_2. if(flag) { return incomplete_type_ptr. }else{ return funct_ptr.conversion between pointer to object and pointer to function type */ . EXAMPLE typedef int (*FunctionPointer)(void). int* someFunction(FunctionPointer funct_ptr. MISRA2004-11_2_b BENEFITS Rule prevents undefined conversions.

Section 11 . REFERENCES MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.REPAIR Do not perform illegal conversions.

These types are integral types that scale to the size of a pointer for both 32-bit and 64-bit Windows. 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. EXAMPLE void foo( ) { int* pi. Casting between a pointer and an integer type should be avoided where possible. int i.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. REFERENCES 1. i = (int) pi. } // Violation REPAIR Do not cast pointers to non-pointers. BENEFITS Prevents undefined or implementation-defined behaviour. MISRA-C:2004 Guidelines for the use of the C language in critical systems .

com/system/64BitOSAndPortingIssues. http://msdn2.codeproject.18. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.chris-lott.4.Chapter 6. C++ CODING STANDARDS Chapter 4. AV Rule 182 7. Ellemtel Coding Standards http://www.html#18.Port. JOINT STRIKE FIGHTER. 7 4.24 Flow Control Structures. Rule 5-2-9 8.asp 6.3 From: 18 Portable Code .aspx 5.3 Type Conversions .org/resources/cstyle/Ellemtel-rules-mm.com/en-gb/library/aa489560. Section 5. http://www. Section 11 2. AIR VEHICLE.4 . Misra Guidelines rule 45 3. Chapter 6. ISO/DIS 26262 point 8.microsoft. Rec.

AIR VEHICLE. Origin: Misra Guidelines rule 45 2. EXCEPTIONS The rule allows to cast integer constant '0' to pointer type.24 Flow Control Structures. EXAMPLE void foo( ) { int* pi. pi = (int*)i. ISO/DIS 26262 . REFERENCES 1. C++ CODING STANDARDS Chapter 4. BENEFITS Rule prevents undefined or implementation-defined behaviour.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. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. AV Rule 182 4. Section 11 3. JOINT STRIKE FIGHTER. int i. Problems can arise when an arbitrary integer is converted to a pointer. } // Violation REPAIR Do not cast non-pointers to pointers.

point 8.4.4 .

Conversions of this type may be invalid if the new pointer type requires a stricter alignment.Pointer to function . BENEFITS Prevents incorrect pointer alignment.Pointer to object . signed char* sc.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. ui = (unsigned int*) &sc. /* Examples of incorrect code */ ui = (unsigned int*) sc. EXAMPLE void foo( ) { unsigned int* ui. Pointer types can be classified as follows: .Pointer to void . } REPAIR /* Violation */ /* Violation */ .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.

ISO/DIS 26262 point 8. /* OK */ /* OK */ } REFERENCES 1. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. ui = (unsigned int* const) ui_t. Section 11 2. /* Examples of correct code */ ui = (unsigned int*) ui_t. Origin: Misra Guidelines rule 45 3. Section 5.4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.4 . uint32_t* ui_t. Rule 5-2-7 4.typedef unsigned int uint32_t. void foo( ) { unsigned int* ui. Chapter 6.

Notice that the qualification referred to here is not the same as any qualification that may be applied to the pointer itself. EXAMPLE typedef unsigned short uint16_t. /* pointer const uint16_t * * ppci. /* pointer pi = (uint16_t *)pci." BENEFITS Rule prevents undefined behaviour. uint16_t * const * pcpi. /* pointer const uint16_t * pci. ppi = (uint16_t * *)pcpi. pi = (uint16_t *)pvi. /* /* /* /* 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. /* pointer volatile uint16_t * pvi.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. REFERENCES . **ppi. void foo( ) { uint16_t *pi. ppi = (uint16_t * *)ppci.

1. Section 11 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Rule 5-2-5 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Chapter 6. Section 5.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 12 2. Chapter 6. y. x = 0. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 5. y = 0. y. y = 0. and the same effect can be achieved by other means. } // Violation REPAIR void foo() { int x." See also: misra-042 BENEFITS Rule improves readability and maintainability. Rule 5-18-1 . EXAMPLE void foo() { int x. x = 0.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. } // OK REFERENCES 1.

BENEFITS Prevents implementation-defined behaviour. and therefore no floating-point manipulations shall be made which rely directly on the way the values are stored. // OK }. // OK }.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. // Violation }. union U { int f:6. // Violation }. should be used. union U { float f:6. which hide the storage details from the programmer. EXAMPLE struct S { float f:6. . REPAIR struct S { int f:6." NOTES In many cases floating point bit fields will be flagged as syntax errors. The in-built operators and functions.

REFERENCES 1. Chapter 6. Rule 3-9-3 . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 5. Section 12 2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.

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. x++. x = y + x. x = --y + x++. } /* Violation */ REPAIR void foo() { int x. it should be the only side-effect in the statement. y.It can significantly impair the readability of the code . y. The use of increment and decrement operators in combination with other arithmetic operators is not recommended because: .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. } /* OK */ /* OK */ . Reduces risk of potential undefined behaviour caused by additional side effects EXAMPLE void foo() { int x." BENEFITS Improves readability and maintainability. --y.

C++ CODING STANDARDS Chapter 4. AIR VEHICLE. Section 12 2. AV Rule 204 3. JOINT STRIKE FIGHTER.25 Expressions. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.REFERENCES 1. Rule 5-2-10 . Section 5. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.

However. and this approach helps to avoid such errors. b." Parentheses are required for the right-hand operand because the right-hand side itself contains an assignment expression. b. BENEFITS Rule improves readability and maintainability. MISRA-C:2004 Guidelines for the use of the C language in critical . It is easy to make a mistake with the rather complicated precedence rules of C.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. EXAMPLE void foo() { int a. and helps to make the code easier to read. b = (a = 0). parentheses should also be used to emphasise it.// Violation } REPAIR void foo() { int a. do not add too many parentheses so as to clutter the code and make it unreadable.// OK } REFERENCES 1. b = a = 0.

28 Portable Code. AV Rule 213 3. Rule 5-0-2 4. JOINT STRIKE FIGHTER. C++ CODING STANDARDS Chapter 4. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 5. Chapter 6. Origin: Misra Guidelines .systems Chapter 6. AIR VEHICLE.Rule 47 . Section 12 2.

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. and helps to make the code easier to read. b. It is easy to make a mistake with the rather complicated precedence rules of C." NOTES Macro's body is excluded from checking. BENEFITS Rule improves readability and maintainability. and this approach helps to avoid such errors. b.// OK b = (a + 0). b = (a = 0). EXAMPLE void foo() { int a. parentheses should also be used to emphasise it." "No parentheses are required for the right-hand operand of an assignment operator unless the right-hand side itself contains an assignment expression. do not add too many parentheses so as to clutter the code and make it unreadable.// Violation } REPAIR void foo() { int a. However. .

28 Portable Code. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.// OK } REFERENCES 1. AV Rule 213 3. Section 12 2.b = (a = 0). Origin: Misra Guidelines . Chapter 6. C++ CODING STANDARDS Chapter 4. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 5. Rule 5-0-2 4.Rule 47 . JOINT STRIKE FIGHTER. AIR VEHICLE.// OK b = a + 0.

and helps to make the code easier to read. b. 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. parentheses should also be used to emphasise it. } // Violation REPAIR void foo( ) { int a. MISRA-C:2004 Guidelines for the use of the C language in critical . b. b = a * (-1).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. and this approach helps to avoid such errors. EXAMPLE void foo( ) { int a. b = a * -1. } // OK REFERENCES 1. BENEFITS Rule improves readability and maintainability. It is easy to make a mistake with the rather complicated precedence rules of C. However.

JOINT STRIKE FIGHTER. AIR VEHICLE.28 Portable Code. AV Rule 213 3. C++ CODING STANDARDS Chapter 4. Origin: Misra Guidelines .Rule 47 . Rule 5-0-2 4. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.systems Chapter 6. Section 5. Section 12 2.

parentheses may be used to control the order of operation. parentheses should also be used to emphasise it. EXAMPLE #ifdef _MSC_VER typedef unsigned __int16 uint16. Similarly. However.g." "If all operators are the same. Some operators (e. and helps to make the code easier to read.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. It is easy to make a mistake with the rather complicated precedence rules of C.0 BENEFITS Rule increases safety in arithmetic operations. . 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. do not add too many parentheses so as to clutter the code and make it unreadable. integer operations involving mixed types (prohibited by several rules) may produce different results because of the integral promotions. addition and multiplication) that are associative in algebra are not necessarily associative in C. and this approach helps to avoid such errors.

/* Violation d is 65526. uint32 d. #endif void fooPlus( ) { uint16 a = 10. typedef u_int32_t uint32. /* OK d is 65545 */ void fooMultiply( ) { . uint16 b = 65535. #endif void fooPlus( uint16 a = uint16 b = uint32 c = uint32 d. uint32 c = 0. typedef u_int32_t uint32. /* Violation d is 9.typedef unsigned __int32 uint32. d = (a + b) + c. uint16 b = 65535. #elif __GNUC__ #include <sys/types. uint32 d. d = (a * b) * c. d = a + (b } ) { 10. uint32 c = 0.h> typedef u_int16_t uint16. #elif __GNUC__ #include <sys/types. a + b wraps modulo 65536 */ } void fooMultiply( ) { uint16 a = 10. a * b wraps modulo 65536 */ } REPAIR #ifdef _MSC_VER typedef unsigned __int16 uint16. 0. typedef unsigned __int32 uint32. + c).h> typedef u_int16_t uint16. 65535.

Chapter 6.28 Portable Code. AV Rule 213 3. AIR VEHICLE. C++ CODING STANDARDS Chapter 4. Section 5. d = a * (b 10. Rule 5-0-2 4.uint16 a = uint16 b = uint32 c = uint32 d. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. /* OK d is 655350 */ } REFERENCES 1. 0. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Origin: Misra Guidelines . 65535.Rule 47 . JOINT STRIKE FIGHTER. * c). Section 12 2.

b = (a * a) + a. do not add too many parentheses so as to clutter the code and make it unreadable. b. b = a * a + a.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 helps to make the code easier to read. } // Violation REPAIR void foo( ) { int a. However. and this approach helps to avoid such errors. b. EXAMPLE void foo( ) { int a. } // OK ." 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. Use parentheses unless all operators in the expression are the same.

C++ CODING STANDARDS Chapter 4. AV Rule 213 3. AIR VEHICLE. JOINT STRIKE FIGHTER.28 Portable Code. Section 12 2. Origin: Misra Guidelines . Rule 5-0-2 4.Rule 47 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.REFERENCES 1. Chapter 6. Section 5.

parentheses should also be used to emphasise it. and helps to make the code easier to read.c. It is easy to make a mistake with the rather complicated precedence rules of C. a=(((((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8)/(b+d))+3.d." 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.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. b. However.if the nesting level exceeds 10 rule reports a violation message. BENEFITS Rule improves readability and maintainability. 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. and this approach helps to avoid such errors. do not add too many parentheses so as to clutter the code and make it unreadable. Note: Nested parentheses level is set on 10 but can be changed. The rule checks the number of nested parentheses . EXAMPLE void foo( ) { int a. // Violation .

h = (((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8. Origin: Misra Guidelines . Rule 5-0-2 4. int h. AV Rule 213 3. AIR VEHICLE. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. JOINT STRIKE FIGHTER. b. C++ CODING STANDARDS Chapter 4. Section 12 2.} REPAIR void foo( ) { int a.28 Portable Code. a =(h*(b+d))+3. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.Rule 47 . } // OK // OK REFERENCES 1.d. Section 5.c.

?: and . a = b[a] + a++. See also: MISRA2004-12_4_a. // Violation } REPAIR void foo( ) { int a. (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. This will give different results depending on whether b[i] is evaluated before i++ or vice versa.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 (). ||. EXAMPLE void foo( ) { int a. As an example of what can go wrong. and in particular no reliance can be placed on the order in which side effects occur. MISRA2004-12_4_b BENEFITS Rule prevents evaluation of expression dependent on compiler version. This means that no reliance can be placed on the order of evaluation of sub-expressions. &&. b[10]. 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. b[10]. consider x = b[i] + i++. .

Section 5. JOINT STRIKE FIGHTER.Rule 46 3.Guidelines for the use of the C++ language in critical systems. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. a++. // OK // OK } REFERENCES 1.25 Expressions. AV Rule 204 4. C++ CODING STANDARDS Chapter 4. Section 12 2.a = b[a] + a. MISRA C++:2008 . Rule 5-0-1 . Chapter 6. AIR VEHICLE. Origin: Misra Guidelines .

// Violation Transmogrify(count++.count).int). // Violation . EXCEPTIONS Only one level of function calls is checked. Rule checks calls of functions that have at least two arguments. BENEFITS Rule prevents writing source code which might produce different results between compilers. int Bump(int& x) {return ++x.} void foo() { int count = 5. This means that if arguments contain side effects then the order in which side effects take place is unspecified. modifying an object or calling a function that does any of those operations. A function call can give different results depending on which of the function's arguments is evaluated first. A violation is reported if * a volatile object is read or modified. EXAMPLE void Transmogrify(int. Transmogrify(Bump(count). By side effect we understand accessing a volatile object.Bump(count)). 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.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.

Chapter: "Functions and Operators".} void foo() { int count = 5. // OK Transmogrify(count. Transmogrify(temp1. // OK count++.Bump(count)).Rule 46 3.Guidelines for the use of the C++ language in critical systems. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6." AddisonWesley. Chapter 6. int temp1 = Bump(count). MISRA C++:2008 . } REFERENCES 1.int). Inc. C++ CODING STANDARDS Chapter 4. AV Rule 204 5. "C++ Coding Standards. AIR VEHICLE. Herb Sutter. Section 5.} REPAIR void Transmogrify(int. Andrei Alexandrescu. (C) 2005 Pearson Education. Rule 5-0-1 . int Bump(int& x) {return ++x. Origin: Misra Guidelines .count). Rule 31 4.25 Expressions. Section 12 2. JOINT STRIKE FIGHTER.

as this is not a precedence issue. p->task_start_fn( p++ ). ||. 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”. Note that the order of evaluation problem is not solved by the use of parentheses. EXAMPLE struct S { void (*task_start_fn)( struct S* ). }. and in particular no reliance can be placed on the order in which side effects occur.3.3 and 6." "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++). 6. } // Violation .6 of ISO 9899:1990 [2].1.2. void foo() { struct S* p. ?: and . Sequence points and side effects are described in sections 5. This means that no reliance can be placed on the order of evaluation of sub-expressions.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 (). &&." BENEFITS Rule prevents evaluation of expression dependent on compiler version. (comma)) the order in which sub-expressions are evaluated is unspecified and can vary.

Origin: Misra Guidelines . } // OK REFERENCES 1. void foo() { struct S* p. Chapter 6. MISRA C++:2008 . p->task_start_fn( p ).Guidelines for the use of the C++ language in critical systems. p++.REPAIR struct S { void (*task_start_fn)( struct S* ).Rule 46 3. Rule 5-0-1 . Section 12 2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. }. Section 5.

and in particular no reliance can be placed on the order in which side effects occur. This means that no reliance can be placed on the order of evaluation of sub-expressions. Functions may have additional effects when they are called (e. (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. &&. 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. making use of a temporary variable for the value. ?: and . ||.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 ()." 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. Dependence on order of evaluation could be avoided by invoking the function prior to the expression that uses it.g. BENEFITS Rule prevents evaluation of expression dependent on compiler version. and in the same expression the variable is used in some other way. modifying some global data). EXAMPLE int foo(int* ptr) { .

(*ptr)++. Chapter 6. return 0. } int bar(int local_param) { return local_param.Guidelines for the use of the C++ language in critical systems. int j) { i = foo(&j) + bar(j).Rule 46 3. } // Violation REPAIR int foo(int* ptr) { (*ptr)++. // OK } REFERENCES 1. } void foo_t(int i. i = temp + bar(j). Origin: Misra Guidelines . MISRA C++:2008 . } int bar(int local_param) { return local_param. int j) { int temp = foo(&j). Rule 5-0-1 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. } void foo_t(int i. Section 5. return 0. Section 12 2.

.

EXAMPLE void foo( int x. // Violation } REPAIR void foo( int x." BENEFITS Rule prevents evaluation of expression dependent on compiler version. MISRA-C:2004 Guidelines for the use of the C language in critical . // OK x = y. int y. 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. int z ) { x = y = z / 3. and in particular no reliance can be placed on the order in which side effects occur. ||. (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. // OK } REFERENCES 1. This means that no reliance can be placed on the order of evaluation of sub-expressions. int z ) { y = z / 3. ?: and . int y.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 (). &&.

Chapter 6. Rule 5-0-1 .systems Chapter 6. Origin: Misra Guidelines . Section 12 2. Section 5.Rule 46 3.Guidelines for the use of the C++ language in critical systems. MISRA C++:2008 .

which then means there may be dependence on order of evaluation. a read of a volatile has a side effect (changing the value of the volatile). In addition. C compilers will not optimise out reads of a volatile.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). as far as a C program is concerned. void foo() { volatile int v. See also: MISRA2004-12_2_b SINCE v7.MISRA2004-12_2_b } . void goo(int. If an object of volatile qualified type is accessed this may change its value. It will usually be necessary to access volatile data as part of an expression. // Violation . int). Where possible though it is recommended that volatiles only be accessed in simple assignment statements.0 NOTES Rule does not report violation if in a function call are used as arguments more than one volatile. goo(v. In this case should be used rule MISRA2004-12_2_b." The rule reports a violation if in one expression is used more than one volatile. v).

Section 5. Origin: Misra Guidelines .BENEFITS Rule prevents evaluation of expression dependent on compiler version. // Violation } REPAIR void foo( ) { volatile int x. } REFERENCES 1. y = x * x. Rule 5-0-1 . MISRA C++:2008 . Chapter 6.Guidelines for the use of the C++ language in critical systems. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.Rule 46 3. EXAMPLE void foo( ) { volatile int x. // OK y = y * y. y = x. int y. int y. Section 12 2.

||. ." 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. making use of a temporary variable for the value. BENEFITS Rule prevents evaluation of expression dependent on compiler version. modifying some global data).g. EXAMPLE int global.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 . and in particular no reliance can be placed on the order in which side effects occur. EXCEPTIONS Only one level of function calls is checked. (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. Functions may have additional effects when they are called (e. This means that no reliance can be placed on the order of evaluation of sub-expressions. int modify_global() { global++. Dependence on order of evaluation could be avoided by invoking the function prior to the expression that uses it.

Section 12 2. int modify_global() { global++. Chapter 6. } int use_global() { return global. MISRA C++:2008 .return global. } void expr1() { int a = modify_global() + use_global(). a += use_global(). MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 5. } // OK REFERENCES 1. } int use_global() { return global. Rule 5-0-1 .Rule 46 3. } void expr1() { int a = modify_global().Guidelines for the use of the C++ language in critical systems. Origin: Misra Guidelines . } // Violation REPAIR int global. return global.

.

" "The operations that cause side effects are accessing a volatile object. EXCEPTIONS An operand of the form sizeof(i) where i is volatile is permitted. However the expression is not evaluated: sizeof only acts on the type of the expression. To avoid this error. modifying a file. as the side effects will not occur.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. which cause changes in the state of the execution environment of the calling function. BENEFITS Prevents error that are caused by believing that operand of sizeof is evaluated." NOTES Rule checks only three nested level of function calls. int fun_with_se(){ glob++. modifying an object. // side-effect return glob. } void foo1(int i){ . sizeof shall not be used on expressions that contain side effects. or calling a function that does any of those operations. EXAMPLE int glob.

volatile objects are permitted REFERENCES 1. j = sizeof(k). n = sizeof(int). } void foo1(int i){ int j. o. m. Rule 5-3-4 . // examples of correct code m = sizeof(fun_without_se()). sizeof(k = 2). } // OK // OK // OK // OK // OK .21 Operators. MISRA C++:2008 .int j = l = m = j. AV Rule 166 4. k. i++. Section 12 2. Chapter 6. o = sizeof(vol). m. C++ CODING STANDARDS Chapter 4. l.k is not set to 2 sizeof(i++). l. // Violation . Section 5. AIR VEHICLE. n. // Violation . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.Rule 40 3. Origin: Misra Guidelines . volatile int vol. JOINT STRIKE FIGHTER.i is not incremented sizeof(fun_with_se()). k. k = 2.glob is not incremented } REPAIR int fun_without_se(){ // no side-effect return 1. l = sizeof(i). // Violation .Guidelines for the use of the C++ language in critical systems.

EXAMPLE void foo( ) { int i. modifying a file. if ((j == i) || (0 == i++)) ." See also: MISRA2004-12_2_a. MISRA2004-12_4_b NOTES Rule checks only three nested level of function calls. 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. or calling a function that does any of those operations. modifying an object. If these sub-expressions contain side effects then those side effects may or may not occur. depending on the values of other sub expressions. // Violation } .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. BENEFITS Rule prevents conditional evaluation of the right-hand operand that can easily cause problems if the developer relies on a side effect occurring. int j. which cause changes in the state of the execution environment of the calling function. The operations that cause side effects are accessing a volatile object.

int j. Section 5. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Rule 5-14-1 5. AV Rule 157 4. Section 12 2.4 .21 Operators. Origin: Misra Guidelines . Chapter 6. // OK } REFERENCES 1.4.Rule 33 3. MISRA C++:2008 . if ((j == i) || (0 == i)) i++. C++ CODING STANDARDS Chapter 4.Guidelines for the use of the C++ language in critical systems. AIR VEHICLE.REPAIR void foo( ) { int i. ISO/DIS 26262 point 8. JOINT STRIKE FIGHTER.

int j. either the second or third operands are evaluated but not both.developer expects 2nd and 3rd // operand to be evaluated } . MISRA2004-12_4_a NOTES Rule checks only two nested level of function calls." See also: MISRA2004-12_2_a. and is therefore less likely to lead to mistakes. In the case of the ?: operator. If these sub-expressions contain side effects then those side effects may or may not occur. depending on the values of other sub-expressions. EXAMPLE int i. 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. // Violation .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. The operators which can lead to this problem are &&. || and ?:. The ?: operator is specifically provided to choose between two subexpressions. int foo( ) { return (i > j) ? j++ : i++.

REPAIR int i. JOINT STRIKE FIGHTER. AV Rule 204 3.4 . ISO/DIS 26262 point 8. int j. AIR VEHICLE. return j++. } else { ++j. int foo( ) { if (i > j) { ++i. C++ CODING STANDARDS Chapter 4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. return i++.25 Expressions. } } // OK REFERENCES 1.4. Section 12 2.

The operands of a logical && or || shall be primary-expressions [MISRA2004-12_5-3] DESCRIPTION ""Primary expressions" are defined in ISO 9899:1990. Essentially they are either a single identifier. // OK if ( x && ( !y ) ). } . z ) && x ). int y. } x. int z ) y && z ). 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. or a parenthesised expression. z ) ) && x ). Where an expression consists of either a sequence of only logical && or a sequence of only logical ||. or a constant. // Violation !y ). // Violation x. y. 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. int z ) { if ( x || ( y && z ) ). y. // Violation REPAIR int foo( int x.1. // OK if ( ( foo( x. // OK return 0.3. extra parentheses are not required" See also: MISRA2004-12_1_e. int y. section 6." EXAMPLE int foo( int { if ( x || if ( x && if ( foo( return 0.

Section 12 2.Rule 34 . Misra Guidelines . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.REFERENCES 1.

logical operators (!.Boolean-by-construct values . || and !) should be effectively Boolean [MISRA200412_6_a-3] DESCRIPTION "The operands of logical operators (&&.enum that name begins with 'bool' (ignoring case) and that contains exactly 2 enum constant in body .equality operators (== and !=) . parameter or expression of type: . >. Rule prevents confusion between logical and bitwise operators. EXAMPLE ." Rule does not report violation if as an operand of logical operator is used: .relational operators (<. Boolean-by-construct values are produced by the following operators: . and would then be used for any objects that are Boolean.typedef to char/short/int/enum which name begins with 'bool' (ignoring case) .The operands of logical operators (&&.bool.variable. !) should be 'effectively Boolean'. .typedef to bool. . An 'effectively Boolean' expression which is either 'Boolean-by-construct' or 'Boolean-by-enforcement' as defined below. && and ||) . A Boolean type could be associated with a specific typedef.integer or enum constant defined as '0' or '1' . ||. <= and >=) Boolean-by-enforcement values can be introduced by implementing a specific type enforcement mechanism using a tool.boolean constant .reference to above types BENEFITS Rule improves readability and maintainability.

Origin: Misra Guidelines . z = (x > y) || goo(). Section 12 2. z. // Violation // Violation // Violation } REPAIR int goo(). z = (x > y) && goo(). z z x z = = = = (x > y) && (goo() != 0). // OK // OK // OK } REFERENCES 1. y. z. y. void foo() { int x. (x > y) || (goo() != 0). void foo() { int x. z = !(x = y). (x == 0). MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.Rule 36 . y.int goo().

!=. =. !=.Expressions that are effectively Boolean should not be used as operands to operators other than (&&. ?:) is used: . EXAMPLE int goo().typedef to bool. parameter or expression of type: .logical operators (!. and would then be used for any objects that are Boolean. !." Rule reports violation if as an operand of operator other than (&&. .variable. A Boolean type could be associated with a specific typedef. && and ||) .boolean constant . =. ?:) [MISRA2004-12_6_b-3] DESCRIPTION "Expressions that are effectively Boolean should not be used as operands to operators other than (&&.reference to above types BENEFITS Rule improves readability and maintainability. Boolean-by-construct values are produced by the following operators: .enum that name begins with 'bool' (ignoring case) and that contains exactly 2 enum constant in body . An 'effectively Boolean' expression which is either 'Boolean-by-construct' or 'Boolean-by-enforcement' as defined below. .typedef to char/short/int/enum which name begins with 'bool' (ignoring case) . ?:).equality operators (== and !=) . ==. Rule prevents confusion between logical and bitwise operators.bool.Boolean-by-construct values . ==.relational operators (<. ||. ==. ||. =. ||. >. !. !=. !. <= and >=) Boolean-by-enforcement values can be introduced by implementing a specific type enforcement mechanism using a tool. void foo() .

// Violation z = ~(x == y). Chapter 6. z = (x > y) & (goo()).{ int x. z = ~tmp. // Violation z = x | (goo() != 0). MISRA C++:2008 . // OK } REFERENCES 1. z = x | tmp. y. Section 4. Rule 4-5-1 . Section 12 2.Rule 36 3. Origin: Misra Guidelines . // OK tmp = x == y. int tmp. z. z = tmp & goo().Guidelines for the use of the C++ language in critical systems. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. tmp = x > y. // OK tmp = goo() != 0. // Violation } REPAIR int goo(). y. z. void foo() { int x.

<<. for example. /* OK */ return (unsigned int)x | 5u. int y ) { x = y >> 2. int y ) { /* Caller must make sure x and y are not negative */ x = (unsigned int)y >> 2u. or a left shift moves a numeric bit into the sign bit. EXAMPLE int foo( int x. /* OK */ } REFERENCES . /* OK */ x = (unsigned int)y & 0x0Fu. &. // Violation x = y & 0x0F. // Violation return x | 5." BENEFITS Rule makes the code more readable and less confusing. ^ and |) are not normally meaningful on signed integers. 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. >>. // Violation } REPAIR int foo( int x. a right shift moves the sign bit into the number.Bitwise operators shall not be applied to operands whose underlying type is signed [MISRA2004-12_7-3] DESCRIPTION "Bitwise operations (~. Problems can arise if.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Origin: Misra Guidelines .Rule 37 .1. Section 12 2.

for example. EXAMPLE typedef unsigned char typedef unsigned short void foo( uint16_t p ) uint8_t.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. Use of an unsigned integer type will ensure that the operand is non-negative. the left-hand operand of a left-shift or right-shift is a 16-bit integer. There are various ways of ensuring this rule is followed. . BENEFITS Rule makes the code more readable and less confusing. so then only the upper limit needs to be checked (dynamically at run-time or by review). The simplest is for the right-hand operand to be a constant (whose value can then be statically checked).the operand is a non-const variable and it's value is not checked by specific pattern." 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 . uint16_t. 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). Otherwise both limits will need to be checked. then it is important to ensure that this is shifted only by a number between 0 and 15 inclusive.

JOINT STRIKE FIGHTER. Chapter 6. AIR VEHICLE. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 12 2. u8a = (uint8_t) (u8a << 9). /* OK */ if (p >= 0 && p <= 8) { u8a = (uint8_t) (u8a << p).p range checked */ } u8a = (uint8_t) (u8a << 4). uint16_t u16a. AV Rule 164 3. Section 5.Guidelines for the use of the C++ language in critical systems. /* OK . /* Violation */ } REPAIR typedef unsigned char typedef unsigned short void foo( uint16_t p ) { uint8_t u8a.constant value in range */ } REFERENCES 1. MISRA C++:2008 . uint8_t.21 Operators. /* OK . C++ CODING STANDARDS Chapter 4. /* Violation */ u8a = (uint8_t) (u8a << p).{ uint8_t u8a. u16a = (uint16_t) ((uint16_t) u8a << 9). uint16_t. Rule 5-8-1 .

Section 12 .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. } // Violation REPAIR void foo() { unsigned char ui1. signed short si2. but this is not good practice. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Applying unary minus to an operand of smaller unsigned integer type may generate a meaningful signed result due to integral promotion. EXAMPLE void foo() { unsigned char ui1. signed short si2. si2 = -ui1. si2 = -(signed short) ui1." BENEFITS Prevents unexpected result due to integral promotion. } // OK REFERENCES 1.

AV Rule 165 4. C++ CODING STANDARDS Chapter 4. AIR VEHICLE. MISRA C++:2008 . Rule 5-3-2 .2. Section 5.Guidelines for the use of the C++ language in critical systems. Chapter 6.Rule 39 3. Origin: Misra Guidelines .21 Operators. JOINT STRIKE FIGHTER.

This precludes the use of both simple and compound assignment operators in the operands of a Boolean-valued expression. int y. This helps to avoid getting "=" and "==" confused.the controlling expression of an if statement . z = !(x = y). Boolean values are expected in the following contexts: . However. and assists the static detection of mistakes. // Violation . EXAMPLE void foo() { int x.the controlling expression of an iteration statement .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.the first operand of the conditional operator ? BENEFITS Rule prevents getting "=" and "==" confused. it does not preclude assigning a Boolean value to a variable." 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. int z. If assignments are required in the operands of a Boolean-valued expression then they must be performed separately outside of those operands.

// Violation // Violation } REPAIR void foo() { int x.if ((x > y) && (x = 4)). int z. C++ CODING STANDARDS Chapter 4. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. // OK } REFERENCES 1. Section 6. Chapter 6. AV Rule 160 4. // OK if (!(x == y)). int y. JOINT STRIKE FIGHTER. Misra Guidelines .21 Operators. Rule 6-2-1 . Section 13 3. if (!(x = y)). AIR VEHICLE. MISRA C++:2008 .Rule 35 2. z = !(x == y). // OK if ((x > y) && (x == 4)).Guidelines for the use of the C++ language in critical systems.

" Rule does not report violation if as an operand of logical operator is used: . >. ." An 'effectively Boolean' expression which is either 'Boolean-by-construct' or 'Boolean-by-enforcement' as defined below. .typedef to bool. && and ||) . even though in C this will in practice be an integer.Tests of a value against zero should be made explicit. .bool.integer or enum constant defined as '0' or '1' . <= and >=) Boolean-by-enforcement values can be introduced by implementing a specific type enforcement mechanism using a tool.relational operators (<.boolean constant . A Boolean type could be associated with a specific typedef. Boolean-by-construct values are produced by the following operators: .variable.Boolean-by-construct values .enum that name begins with 'bool' (ignoring case) and that contains exactly 2 enum constant in body . 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.typedef to char/short/int/enum which name begins with 'bool' (ignoring case) . and would then be used for any objects that are Boolean.logical operators (!. parameter or expression of type: .equality operators (== and !=) .reference to above types NOTES Rule does not report violations on constant expressions. The exception to this rule is when data represents a Boolean value.

and makes clear the distinction between integers and logical values. Misra Guidelines .Rule 49 ." EXAMPLE int goo() { return 1. int y ) { if (goo() != 0) {}// OK if (y != 0) {} // OK } REFERENCES 1. Section 13 2. int y ) { if (goo()) {}// Violation if (y) {} // Violation } REPAIR int goo() { return 1. } void foo( int x. } void foo( int x. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.BENEFITS "This rule is in the interests of clarity.

" 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 ) ) { /* . and may well vary from one implementation to another. */ } 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. if (x == y). In addition the behaviour of such a comparison cannot be predicted before execution.. if (x == 0.0f). } // Violation // Violation . " EXAMPLE void foo() { float x. y. The library should take into account the floating-point granularity (FLT_EPSILON) and the magnitude of the numbers being compared.. The recommended method for achieving deterministic floating-point comparisons is to write a library that implements the comparison operations.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.

Section 6. Misra Guidelines .epsilon <= y && y <= x + epsilon). AIR VEHICLE. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. // OK // OK } REFERENCES 1. y.Guidelines for the use of the C++ language in critical systems. Chapter 6. Rule 6-2-2 .25 Expressions. if (-epsilon <= x && x <= epsilon). if (x . Section 13 2.Rule 50 3. C++ CODING STANDARDS Chapter 4. AV Rule 202 4. JOINT STRIKE FIGHTER.REPAIR void foo( float epsilon ) { float x. MISRA C++:2008 .

for (y = 0. causing significant inaccuracies in the loop variable." BENEFITS Rule prevents unpredictable behaviour. y++). y < max. and may be unpredictable. } // Violation REPAIR void foo( int max ) { int y. y++).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. } // OK REFERENCES MISRA-C:2004 Guidelines for the use of the C language in critical systems . For example the number of times the loop is performed may vary from one implementation to another. y < max. and possibly giving unexpected results when the test is performed. for (y = 0. EXAMPLE void foo( float max ) { float y. Rounding and truncation errors can be propagated through the iterations of the loop. whose value is tested to determine termination of the loop. Floating-point variables shall not be used for this purpose.

Section 13 .Chapter 6.

and optionally other loop control variables (flag) . which makes the code both error-prone and hard to read. but do not seem to be concerned with loop control.Shall include testing the loop counter (i). j.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. variables are initialized within the for statement even though they have nothing to do with stop condition of the loop.First expression . for ( x = 5. } REPAIR void foo( ) { // Violation // Violation .Third expression . x < 2 . Often. j < 2 . In extreme cases entire for statement blocks can be moved into the for statement.The three expressions of a for statement shall be concerned only with loop control [MISRA2004-13_5-3] DESCRIPTION "When present. j++ ). for ( x = 5. BENEFITS Complying with this rule leads to safer and more readable code. the three expressions of a for statement shall be used only for these purposes: . x++ ).Initialising the loop counter (i in the following example) .Second expression . EXAMPLE void foo( ) { int x.

Origin: Misra Guidelines . j.Rule 66 .int x. Section 13 2. // OK } REFERENCES 1. x < 2. x++). MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. for ( x = 5.

which is then tested in the for statement. for ( i = 0. i++ ) { i = i + 3. or prior to." NOTES A - loop-counter is a loop-control-variable that is: Initialized in. for example a flag to indicate that something has been completed. for ( i = 0. and an operand to a relational operator in condition. and modified in expression. i < 5. EXAMPLE void foo( ) { int i. i < 5. BENEFITS Modification 'for' loop counter within a body of the loop can lead to errors and confusion. } } /* Violation */ REPAIR void foo( ) { int i. i = i + 3 ) {} /* OK */ } . However other loop control variables representing logical values may be modified in the loop.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. for-init-statement.

Section 6. Rule 6-5-3 .Guidelines for the use of the C++ language in critical systems. Section 13 2. C++ CODING STANDARDS Chapter 4. Origin: Misra Guidelines . MISRA C++:2008 . JOINT STRIKE FIGHTER.Rule 67 3. AV Rule 201 4.24 Flow Control Structures.REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Chapter 6. AIR VEHICLE.

MISRA C++:2008 Guidelines for the use of the C++ language in critical . if((a < 5)&&(a > 2)). MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. if((a >= 2)&&(a <= 5)). BENEFITS "If a Boolean operator yields a result that can be proven to be always 'true' or always 'false'. if((a >= 2)&&(a <= 1)). if((a < 1)&&(a > 2)). if((a > 2)&&(a < 1))." EXAMPLE void myFunction(int a) { if((a <= 1)&&(a >= 2)). it is highly likely that there is a programming error. if((a > 2)&&(a < 5)). } // // // // Violation Violation Violation Violation // // // // OK OK OK OK REPAIR void myFunction(int a) { if((a <= 5)&&(a >= 2)). Section 13 2.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'. } REFERENCES 1.

Chapter 6. Rule 0-1-2 .systems. Section 0.

NOTES Rule does not report violation if the variable used in both 'if' condition is volatile or modified between statements.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. int b) { if(b >= 2) if(b < 7) /* OK */ a++. BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false"." EXAMPLE void foo(int a. } REPAIR void foo(int a. } . it is highly likely that there is a programming error. Rule assumes that the variable passed to function could be modified. int b) { if(b >= 2) if(b < 2) /* Violation */ a++.

MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Rule 0-1-2 . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 0. Section 13 2.REFERENCES 1. Chapter 6.

" EXAMPLE void foo(int a. } REPAIR void foo(int a.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. Rule assumes that the variable passed to function could be modified. int b) { if(b < 2) if(b >= 2) /* Violation */ a++. it is highly likely that there is a programming error. } . BENEFITS "If a Boolean operator yields a result that can be proven to be 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. int b) { if(b < 2) if(b >= 1) /* OK */ a++.

Section 13 2. Rule 0-1-2 . MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Section 0. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6.REFERENCES 1.

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." EXAMPLE void foo(int a. BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false". Rule assumes that the variable passed to function could be modified. } . } REPAIR void foo(int a. int b) { if(b <= 2) if(b < 3) /* Violation */ a++. int b) { if(b <= 2) if(b < 1) /* OK */ a++. it is highly likely that there is a programming error.

MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 13 2. Rule 0-1-2 . Section 0. Chapter 6.REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.

it is highly likely that there is a programming error. 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. 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++. } . BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false".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." EXAMPLE void foo(int a.

REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 0. Rule 0-1-2 . Section 13 2. Chapter 6.

Rule assumes that the variable passed to function could be modified. } REPAIR void foo(int a. NOTES Rule does not report violation if the variable used in both 'if' condition is volatile or modified between statements. int b) { if(2 > b) if(b < 5) /* Violation */ a++. int b) { if(2 > b) if(b < 1) /* OK */ a++." EXAMPLE void foo(int a. BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false".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. } . it is highly likely that there is a programming error.

Section 13 2.REFERENCES 1. Section 0. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Chapter 6. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Rule 0-1-2 .

int b) { if(2 >= b) if(b < 5) /* Violation */ a++. } REPAIR void foo(int a.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. Rule assumes that the variable passed to function could be modified." EXAMPLE void foo(int a. it is highly likely that there is a programming error. BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false". int b) { if(2 >= b) if(b < 1) /* OK */ a++. NOTES Rule does not report violation if the variable used in both 'if' condition is volatile or modified between statements. } .

Chapter 6. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Rule 0-1-2 .REFERENCES 1. Section 0. Section 13 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.

int b) { if(2 < b) if(b > 1) /* Violation */ a++. Rule assumes that the variable passed to function could be modified.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. int b) { if(2 < b) if(b > 5) /* OK */ a++. } ." EXAMPLE void foo(int a. it is highly likely that there is a programming error. NOTES Rule does not report violation if the variable used in both 'if' condition is volatile or modified between statements. } REPAIR void foo(int a. BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false".

Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 0.REFERENCES 1. Rule 0-1-2 . Section 13 2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6.

" EXAMPLE void foo(int a. int b) { if(2 <= b) if(b > 5) /* OK */ a++.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. it is highly likely that there is a programming error. } REPAIR void foo(int a. BENEFITS "If a Boolean operator yields a result that can be proven to be 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. int b) { if(2 <= b) if(b > 1) /* Violation */ a++. Rule assumes that the variable passed to function could be modified.

Section 13 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems.REFERENCES 1. Chapter 6. Section 0. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Rule 0-1-2 .

Section 0. Section 13 2. if (a >= 0) // Violation a++. } REPAIR void myFunc() { unsigned int a. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false"." EXAMPLE void myFunc() { unsigned int a.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. } REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. it is highly likely that there is a programming error. if (a >= 2) // OK a++. Chapter 6. Rule 0-1-2 .

.

// Violation // Violation } REPAIR void myFunc() { unsigned char a. if (a < 256) a++. if (b >= 128) b++. signed char b. BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false".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." EXAMPLE void myFunc() { unsigned char a. if (b >= 127) b++. signed char b. if (a < 255) a++. } // OK // OK . it is highly likely that there is a programming error.

REFERENCES 1. Section 0. Rule 0-1-2 . MISRA C++:2008 Guidelines for the use of the C++ language in critical systems. Section 13 2. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. Chapter 6.

signed short b. if (a < 65536) a++.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. if (a < 65535) a++. if (b <= 32767) b++. it is highly likely that there is a programming error. if (b <= 32766) b++. // Violation // Violation } REPAIR void myFunc() { unsigned short a. } // OK // OK . BENEFITS "If a Boolean operator yields a result that can be proven to be always "true" or always "false"." EXAMPLE void myFunc() { unsigned short a. signed short b.

Chapter 6. Section 0. Section 13 2. Rule 0-1-2 .REFERENCES 1. MISRA-C:2004 Guidelines for the use of the C language in critical systems Chapter 6. MISRA C++:2008 Guidelines for the use of the C++ language