C++test 92 Rules PDF
C++test 92 Rules PDF
BD-MISC
Miscellaneous
RULES
Always close transactions [BD-MISC-TRANS-1]
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)
{
};
};
}
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]
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)
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*);
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;
}
}
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
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;
}
}
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
Parameterization:
"public"
"public, protected"
"any visibility"
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:
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;
REPAIR
Avoid null pointer dereferencing.
REFERENCES
N/A
{
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
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
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
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
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;
}
}
{
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]
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
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.
// 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
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
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");
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]
Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables
The
Any
*
*
*
REPAIR
The following code will not trigger a violation:
#include <stdio.h>
int example(int array[100])
{
int i;
scanf("%d", &i);
if (i < 0 || i >= 100) {
return -1; // wrong input
}
return array[i]; // NO VIOLATION
}
REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131
http://cwe.mitre.org/top25/#CWE-131
v7.3
NOTES
N/A
SECURITY RELEVANCE
Integer overflow is a serious security threat because it can be used to
cause application crashes
and denial of service.
PARAMETERS
This rule can be parameterized so that data from the following data
sources are considered tainted
(in addition to those previously listed in the DESCRIPTION section):
*
*
*
*
*
*
The
Any
*
*
*
Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables
rule can be parameterized with a list of validating functions.
validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.
namespace, or
a global function declared outside of any type or namespace.
* The 'Function name' column should contain name of the described
function.
* The '+ definitions in subclasses' column is used to indicate whether the
current row will
apply to functions with the given name defined in subclasses of the given
class. Note that this
applies to both instance and non-instance functions.
Other columns allow to describe which of the data are affected by a given
function:
* The '"this" object is validated' column is used to specify that the
function cleans the object on which
it is called.
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger violations:
#include
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>
#define BUFFER_SIZE 64
char buffer[BUFFER_SIZE];
#define MAX_LEN 1000000L
char decode(char c)
{
/* Decode character */
return c;
}
char* readMessage(int socket, char* header, int len)
{
int i, header_len;
long msg_len, total_len;
char* msg;
recv(socket, buffer, BUFFER_SIZE, MSG_NOSIGNAL);
msg_len = atol(buffer);
header_len = strlen(header);
total_len = header_len;
total_len += msg_len;
msg = (char*)malloc(total_len); /* VIOLATION, USAGE OF OVERFLOWED VALUE */
if (!msg) {
return 0;
}
strcpy(msg, header);
recv(socket, msg + msg_len, msg_len, MSG_NOSIGNAL);
for (i = header_len; i < total_len; i++) { /* VIOLATION, USAGE OF
OVERFLOWED VALUE */
msg[i] = decode(msg[i]);
}
return msg;
}
REPAIR
The following code will not trigger a violation:
#include
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>
#define BUFFER_SIZE 64
char buffer[BUFFER_SIZE];
#define MAX_LEN 1000000L
char decode(char c)
{
/* Decode character */
return c;
}
char* readMessage(int socket, char* header, int len)
{
int i, header_len;
long msg_len, total_len;
char* msg;
recv(socket, buffer, BUFFER_SIZE, MSG_NOSIGNAL);
msg_len = atol(buffer);
header_len = strlen(header);
total_len = header_len;
total_len += msg_len;
if ((total_len < 0) || (total_len > MAX_LEN)) { /* check that total_len is
within an acceptable range */
return 0;
}
msg = (char*)malloc(total_len); /* NO VIOLATION */
if (!msg) {
return 0;
}
strcpy(msg, header);
Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
* Console
* Environment variables
The
Any
*
*
*
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])
{
int size;
scanf("%d", &size);
memcpy(dest, src, size); // VIOLATION ("size" is an arbitrary value
possibly < 0 or > 100)
}
REPAIR
The following code will not trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])
{
int size;
scanf("%d", &size);
if (size >= 0 && size <= 100) {
memcpy(dest, src, size); // NO VIOLATION
}
}
REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131
http://cwe.mitre.org/top25/#CWE-131
Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
* Console
* Environment variables
The
Any
*
*
*
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])
{
int size;
scanf("%d", &size);
memcpy(dest, src, size); // VIOLATION ("size" is an arbitrary value
possibly < 0 or > 100)
}
REPAIR
The following code will not trigger a violation:
#include <stdio.h>
#include <string.h>
void example(int src[100], int dest[100])
{
int size;
scanf("%d", &size);
if (size >= 0 && size <= 100) {
memcpy(dest, src, size); // NO VIOLATION
}
}
REFERENCES
http://www.owasp.org/index.php/Buffer_Overflow (security relevance)
CWE/SANS Top 25 Most Dangerous Software Errors: CWE-120
http://cwe.mitre.org/top25/#CWE-120
*
*
*
*
*
The
Any
*
*
*
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables
rule can be parameterized with a list of validating functions.
validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.
#include
#include
#include
#include
<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>
<stdio.h>
<stdlib.h>
<string.h>
<sys/types.h>
<sys/socket.h>
Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
* Console
* Environment variables
The
Any
*
*
*
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
Also, there is an option that determines whether numerical data should be
considered tainted.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Consider an application that stores some user-specific data in files on a
server (for
instance, a library with user stories) using the story name given by the
user as the file name.
The following code may be used to create a specific file and add the
story contents:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
void saveStory(int socket)
{
char storyName[50];
char storyContent[200];
/* Receive story from socket */
Files
Pipes
Stream-oriented APIs (std::istream, CArchive and CFile from MFC)
Low-level input (Windows API, POSIX)
Console
Environment variables
rule can be parameterized with a list of validating functions.
validating function can be defined as:
returning benign data, and/or;
making its parameter(s) benign, and/or;
making this-object benign.
function:
* The '"this" object is validated' column is used to specify that the
function cleans the object on which
it is called.
* The 'returns validated data' column is used to specify that the function
cleans its return value.
* The 'Numbers of the parameters that are validated (1-based)' column is
used to specify that
the function cleans some of its parameters. List parameters' indexes
separated by a comma
or use '*' to specify that all parameters are affected.
Also, there is an option that determines whether numerical data should be
considered tainted.
"Report unvalidated violations" is a parameter common to a large set of
BugDetective rules and is
described in the "Data Flow Static Analysis with BugDetective ->
Customizing BugDetective
Static Analysis -> Configuring Rule Parameters" section of Parasoft
C++test User's Guide.
BENEFITS
N/A
DRAWBACKS
N/A
EXAMPLE
Consider an example where an application reads the user name and
password from a file and then, for authentication purposes, tries to find
that user
information in a database. The code supporting this might look as
follows:
#include <sql.h>
#include <stdio.h>
const int BUFFER_SIZE = 1000;
const char* requestBeginning = "SELECT user_id, user_class, rights FROM
#include
#include
#include
#include
<sql.h>
<sqltypes.h>
<sqlext.h>
<stdio.h>
http://cwe.mitre.org/top25/#CWE-89
BD-TRS
Threads & Synchronization
RULES
Avoid double locking [BD-TRS-DLOCK-1]
Do not abandon unreleased locks [BD-TRS-LOCK-1]
Do not use blocking functions while holding a lock [BD-TRS-TSHL-1]
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <pthread.h>
pthread_mutex_t* mutex;
bool preconditionHolds();
void exclusivelyCompute()
{
pthread_mutex_lock(mutex);
if (preconditionHolds()) {
/* perform some computations */
exclusivelyCompute(); // VIOLATION: recursive call will cause
double locking
}
pthread_mutex_unlock(mutex);
}
void run()
{
mutex = new pthread_mutex_t;
pthread_mutex_init(mutex, (const pthread_mutexattr_t*)0);
exclusivelyCompute();
}
REPAIR
The example can be repaired by separating locking and computation in
different functions
(but ensuring that the function performing unlocked computation is only
called from functions
performing appropriate locking):
#include <pthread.h>
pthread_mutex_t* mutex;
bool preconditionHolds();
static void nonexclusivelyCompute()
{
if (preconditionHolds()) {
unlocking
functions. When such wrappers are involved, it is recommended to define
them as
separate multithreading APIs in the Test Configurations> Static>
BugDetective Options>
Multithreading tab. However, if this is not done but source code of the
wrappers
is included into the analysis scope and a relevant value of the "Locked
object may be
unlocked from callers up to specified level" parameter is used, then cases
where
custom wrapping APIs are used to lock a mutex but not unlock it will be
detected
automatically-- even without extending BugDetective's multithreading API
knowledge
base with the custom API. This is why the parameter of the value is set to
2 by
default; this ensures the detection of most bugs related to direct uses of
standard
locking functions as well as the use of custom wrappers around them-without
producing unnecessary false positives.
To demonstrate this, let's assume the following wrapper functions:
void mutex_lock()
{
pthread_mutex_lock(mutex);
// do something else
}
void mutex_unlock()
{
pthread_mutext_unlock(mutex);
// do something else
}
With the value of parameter set to 0, BugDetective will see the call to
pthread_mutex_lock inside the wrapper function "mutex_lock" and no
corresponding
call to pthread_mutex_unlock inside the function. Consequently, it will
report a
violation which is in fact a false positive because mutex_lock is not
meant to
pthread_mutex_t mutex;
void
void
void
void
void
void
lockLevel1() {
unlockLevel1()
lockLevel2() {
unlockLevel2()
lockLevel3() {
unlockLevel3()
pthread_mutex_lock(&mutex); }
{ pthread_mutex_unlock(&mutex); }
lockLevel1(); }
{ unlockLevel1(); }
lockLevel2(); }
{ unlockLevel2(); }
bool preconditionHolds();
void exclusivelyCompute()
{
lockLevel3();
if (preconditionHolds()) {
/* perform some computations */
unlockLevel3();
}
}
REPAIR
Example 1. The example can be repaired by performing unlocking on all the
branches:
#include <pthread.h>
pthread_mutex_t* mutex;
bool preconditionHolds();
void exclusivelyCompute()
{
pthread_mutex_lock(mutex);
if (preconditionHolds()) {
/* perform some computations */
}
pthread_mutex_unlock(mutex);
}
Example 2.
#include <pthread.h>
pthread_mutex_t mutex;
void
void
void
void
void
void
lockLevel1() {
unlockLevel1()
lockLevel2() {
unlockLevel2()
lockLevel3() {
unlockLevel3()
pthread_mutex_lock(&mutex); }
{ pthread_mutex_unlock(&mutex); }
lockLevel1(); }
{ unlockLevel1(); }
lockLevel2(); }
{ unlockLevel2(); }
bool preconditionHolds();
void exclusivelyCompute()
{
lockLevel3();
if (preconditionHolds()) {
/* perform some computations */
}
unlockLevel3();
}
REFERENCES
N/A
DRAWBACKS
N/A
EXAMPLE
Here is an example that will trigger a violation:
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t* mutex;
static void testLock()
{
pthread_mutex_lock(mutex);
sleep(10);
/* do something */
pthread_mutex_unlock(mutex);
}
REPAIR
Removing the call to sleep() repairs the code:
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t* mutex;
static void testLock()
{
pthread_mutex_lock(mutex);
/* do something */
pthread_mutex_unlock(mutex);
}
REFERENCES
N/A
CDD
Code Duplication Detection
RULES
Avoid duplication of #include directives [CDD-001-4]
Avoid code duplication [CDD-002-2]
Avoid string literal duplication [CDD-003-2]
Avoid function duplication [CDD-004-2]
SINCE
v9.2
BENEFITS
Rule improves readability and maintainability. Simplifies the code and
decreases preprocessing time.
EXAMPLE
// --- header1.h --#include "header2.h"
// --- file.cpp --#include "header1.h"
#include "header2.h" /* OK: not checked against includes in other files */
#include "header1.h" /* Violation: "header1.h" was included previously */
#define HEADER "header1.h"
#include HEADER
/* OK: we don't do macro replacement */
#include HEADER
/* Violation: HEADER was included previously */
#include <header1.h> /* OK: <header1.h> is different than "header1.h" */
#include "./header1.h" /* OK: "./header1.h" is different than "header1.h"
*/
#if 0
#include "header1.h" /* Violation: "header1.h" was included in outer
conditional inclusion scope */
#include "header3.h"
#else
#include "header3.h" /* OK - previous inclusion was inside other
conditional
inclusion scope*/
#endif
#include "header3.h" /* OK - previous inclusion was inside other
conditional
inclusion scope*/
REPAIR
Remove duplicated #include directives if they are not needed.
REFERENCES
Recommended by Parasoft
// 7 tokens
// 3 tokens
// 1 token
set to 20.
int foo(int a, int b)
{
int r;
if (a < b) {
// duplicated code
r = b - a;
// duplicated code
} else {
// duplicated code
r = a - b;
// duplicated code
}
// duplicated code
return r;
}
int bar(int p, int q, bool v)
{
int result;
if (v) {
if (p < q) {
// duplicated code
result = q - p;
// duplicated code
} else {
// duplicated code
result = p - q;
// duplicated code
}
// duplicated code
} else {
return p + q;
}
return result;
}
REPAIR
int foo(int a, int b)
{
int r;
if (a < b) {
r = b - a;
} else {
r = a - b;
}
return r;
}
int bar(int p, int q, bool v)
{
int result;
if (v) {
result = foo(p, q);
} else {
result = p + q;
}
return result;
}
return "pass";
}
if (a < b) {
return "pass";
}
if (a == b) {
return "pass";
}
if (a + b > 0) {
return "pass";
}
return "fail";
// duplicated string
// duplicated string
// duplicated string
// duplicated string
}
REPAIR
const char* foo(int a, int b)
{
const char* pass = "pass";
if (a > 0) {
return pass;
}
if (b > 0) {
return pass;
}
if (a < b) {
return pass;
}
if (a == b) {
return pass;
}
if (a + b > 0) {
return pass;
}
return "fail";
}
// 7 tokens
// 3 tokens
// 1 token
BENEFITS
Rule improves readability and maintainability. Simplifies and reduce code
size.
Copying and pasting code will increase the cost of code maintenance
because
each time a modification is required, multiple instance of the same code
will need to be identified and then modified. Reducing or eliminating the
amount
of duplicated code can prevent this problem.
EXAMPLE
Parameters: Ignore identifiers turned on, minimum duplicated tokens size
set to 20.
int foo(int a, int b)
{
int r;
if (a < b) {
r = b - a;
} else {
r = a - b;
}
return r;
}
int bar(int p, int q)
{
int result;
if (p < q) {
result = q - p;
} else {
result = p - q;
}
return result;
}
REPAIR
One of these functions can be removed and all references
can be switched to second one.
CODSTA
Coding Conventions
RULES
Array elements shall be accessed by the array operator [ ] [CODSTA-01-3]
Do not declare member variables as bit-fields [CODSTA-02-5]
Do not define constants via #define [CODSTA-03-3]
Do not declare local variables with the 'static' keyword [CODSTA-04-5]
Pointers to pointers should be avoided whenever possible [CODSTA-05-3]
Avoid using the '?:' operator [CODSTA-06-3]
If a function has no parameters, use ( ) instead of ( void ) [CODSTA-07-3]
Do not use break in for loops [CODSTA-08-2]
Do not cast pointers to functions to pointers to primitive types [CODSTA09-3]
Storage type modifiers shall be associated with the type, not the variable
or the function [CODSTA-10-3]
Assert liberally to document internal assumptions and invariants [CODSTA11-5]
Avoid using shift operations instead of arithmetic operations [CODSTA-123]
Avoid pointer arithmetic [CODSTA-13-3]
Never convert consts to non-consts [CODSTA-14-3]
Do not declare the size of an array when the array is passed into a
function as a parameter [CODSTA-15-2]
Do not declare the size of an array when the array is initialized [CODSTA16-2]
Do not compare a pointer to NULL or assign NULL to a pointer; use 0
instead [CODSTA-17-3]
Prefer while statements over do statements [CODSTA-18-5]
Use the ctype.h facilities for character test [CODSTA-19-3]
EOS should be used to terminate a string rather than NULL [CODSTA-20-2]
When using enum, the values of each member should be explicitly declared
[CODSTA-21-5]
Local variable or parameter names and class member variable or parent
class/struct member variable names shall differ by more than a single
character [CODSTA-22-1]
All 'if' statements should have an 'else' clause [CODSTA-23-3]
If FALSE is to be defined, and is not already defined, #define FALSE
should be 0 [CODSTA-24-5]
If FALSE is to be defined, and is not already defined, enum value FALSE
should be 0 [CODSTA-25-5]
Avoid magic numbers [CODSTA-26-3]
Avoid functions that modify global variables [CODSTA-27-3]
Define fields for union declarations [CODSTA-28-5]
53-3]
Every switch statement will have at least two cases and a potential
default [CODSTA-54-3]
Enumeration types shall be used instead of integer types (and constants)
as case labels [CODSTA-55-2]
All 'case' and 'default' labels of 'switch' statement should have an
explicit 'break' or a 'return' statement, or 'fall through' comment
[CODSTA-56-3]
Suspicious use of semicolon [CODSTA-57-4]
Cast to void is not allowed [CODSTA-58-4]
Hardcoded array declarations and 'malloc' calls should not be used
[CODSTA-59-4]
Avoid comparing values with TRUE macro/enum constant using equality
operators ("==", "!=") [CODSTA-60-3]
The final clause of a switch statement shall be the default-clause
[CODSTA-61-3]
A cast shall not convert a pointer to a function to any other pointer
type, including a pointer to function type [CODSTA-62-3]
Bitwise operators shall only be applied to operands of unsigned underlying
type [CODSTA-63-3]
An unconditional throw or break statement shall terminate every non-empty
switch-clause [CODSTA-64-3]
An object with integer type or pointer to void type shall not be converted
to an object with pointer type [CODSTA-65-3]
Non-constant operands to a binary bitwise operator shall have the same
underlying type [CODSTA-66-3]
The types used for an object, a function return type, or a function
parameter shall be token-for-token identical in all declarations and redeclarations [CODSTA-67-3]
A "U" suffix shall be applied to all octal or hexadecimal integer literals
of unsigned type [CODSTA-68-3]
Expressions with type (plain) char and wchar_t shall not be used as
operands to built-in operators other than =, ==, != and the unary &
operator [CODSTA-69-3]
Expressions with type enum shall not be used as operands to built-in
operators other than [ ], =, ==, !=, <, <=, >, >=, and the unary &
operator [CODSTA-70-3]
Named bit-fields with signed integer type shall have a length of more than
one bit [CODSTA-71-3]
Assembler instructions shall only be introduced using the asm declaration
[CODSTA-73-3]
Bit-fields shall not have enum type [CODSTA-74-3]
Bit-fields shall be either bool type or an explicitly unsigned or signed
integral type [CODSTA-75-3]
The identifier main shall not be used for a function other than the global
function main [CODSTA-76-3]
The goto statement shall jump to a label declared later in the same
function body [CODSTA-77-3]
Any label referenced by a goto statement shall be declared in the same
block, or in a block enclosing the goto statement [CODSTA-78-3]
For any iteration statement there shall be no more than one break or goto
statement used for loop termination [CODSTA-79-3]
The continue statement shall only be used within a well formed for loop
[CODSTA-80-3]
If a function has internal linkage then all redeclarations shall include
the static storage class specifier [CODSTA-81-3]
Avoid infinite loops [CODSTA-82-3]
All loops must have a fixed upper or lower bound [CODSTA-83-3]
Avoid exit points within infinite loops [CODSTA-85-3]
The validity of parameters must be checked inside each function [CODSTA86-3]
Use no more than one level of dereferencing [CODSTA-87-3]
Function pointers are not permitted [CODSTA-88-3]
The declaration should not contain more than one level of pointer
indirection [CODSTA-89-3]
Each operand of a logical '&&' or '||' shall be a postfix-expression
[CODSTA-90-3]
A function shall have at most one exit point [CODSTA-91-3]
The names of standard library macros and objects shall not be reused
[CODSTA-92-3]
The names of standard library functions shall not be overridden [CODSTA93-5]
Do not declare pointer or array type [CODSTA-94-3]
Do not declare pointer type [CODSTA-95-3]
CODSTA-CPP
Coding Conventions for C++
RULES
Prefer iostream.h to stdio.h [CODSTA-CPP-01-5]
Have assignment operator returns a reference to *this; make assignment
operator's return type a non-const reference to it's class' type [CODSTACPP-02-3]
Bitwise operators, comparison operators, logical operators, comma operator
should be const [CODSTA-CPP-03-3]
Constructors allowing for conversion should be made explicit [CODSTA-CPP04-1]
Do not use user-defined conversion functions [CODSTA-CPP-05-1]
Avoid returning handles to class data from member functions [CODSTA-CPP06-3]
Postfix increment and decrement should be implemented in terms of their
prefix counterparts [CODSTA-CPP-07-3]
Avoid overloading &&, || or , (comma) [CODSTA-CPP-08-3]
Avoid using reinterpret_cast [CODSTA-CPP-09-3]
Do not define structs that contain member functions [CODSTA-CPP-10-3]
Prefer C++-style casts [CODSTA-CPP-11-3]
Put classes that are used as base classes and classes that are used as
member variables into separate include files [CODSTA-CPP-12-3]
Put classes that are used as function return type into separate include
files [CODSTA-CPP-13-3]
Put classes that are used as argument types in function prototypes into
separate include files [CODSTA-CPP-14-3]
Put functions that are used in the body of inline member function into
separate include file [CODSTA-CPP-15-3]
When two operators are opposites (such as == and !=), it is appropriate to
define both [CODSTA-CPP-16-3]
Do not use the 'struct' keyword to declare a variable in C++ [CODSTA-CPP17-3]
Encapsulate global variables and constants, enumerated types, and typedefs
in a class [CODSTA-CPP-18-5]
Declare at least one constructor to prevent the compiler from doing so
[CODSTA-CPP-19-2]
If you'd like to support mixed-mode operations make operators a non-member
functions [CODSTA-CPP-20-3]
Assignment operator must return const reference [CODSTA-CPP-21-5]
Prefer non-member non-friend functions to member functions [CODSTA-CPP-223]
Whenever a global function is referenced, use the :: operator [CODSTACPP-23-5]
Avoid making any assignment operator virtual. Do not return const T& from
assignment operator [CODSTA-CPP-24-3]
Consider making virtual functions nonpublic, and public functions
nonvirtual [CODSTA-CPP-25-3]
Keep types and functions in separate namespaces unless they're
specifically intended to work together [CODSTA-CPP-26-3]
Keep a type and its nonmember function interface in the same namespace
[CODSTA-CPP-27-3]
When binary arithmetic operators are defined ( + , - , * , / , ^ , % , |
, & , >> , << ), assignment versions should be provided too [CODSTA-CPP28-3]
Prefer the canonical forms of arithmetic and assignment operators [CODSTACPP-29-3]
Prefer non-member operators than member ones to support mixed-mode
arithmetic [CODSTA-CPP-30-3]
Do not use the keyword 'explicit' for a constructor [CODSTA-CPP-31-5]
Member functions shall not be defined within the no-template class
definition [CODSTA-CPP-32-3]
Member functions shall not be defined within the template class definition
[CODSTA-CPP-33-3]
Avoid using static_cast on pointers [CODSTA-CPP-34-3]
Avoid dynamic_casts [CODSTA-CPP-35-3]
Avoid using global variables, global functions, and class in file outside
namespaces [CODSTA-CPP-36-3]
Do not define class/struct/union inside function implementation [CODSTACPP-37-3]
Conversion operator, operator->, operator(), operator[] should be const
[CODSTA-CPP-38-3]
Don't write namespace usings in a header file or before an #include
[CODSTA-CPP-39-3]
Limiting the number of objects of a class [CODSTA-CPP-40-5]
Do not use the 'enum' keyword to declare a variable in C++ [CODSTA-CPP-413]
Do not declare member variables with the 'mutable' keyword [CODSTA-CPP-423]
Declare reference parameters as const references whenever possible
[CODSTA-CPP-43-3]
Have the non-const version call the const version of member function
instead of duplicating the const version definition [CODSTA-CPP-44-3]
In the private section of a class items shall be declared in the following
order: Constructors, Destructor, Member Functions, Member Operator
Function, Enumerations and others [CODSTA-CPP-45-3]
Order of scopes in class: public before all others [CODSTA-CPP-46-3]
The loop-counter shall be modified by one of: --, ++, -=n, or +=n; where n
remains constant for the duration of the loop [CODSTA-CPP-71-3]
A loop-control-variable other than the loop-counter shall not be modified
within condition or expression [CODSTA-CPP-72-3]
A loop-control-variable other than the loop-counter which is modified in
statement shall have type bool [CODSTA-CPP-73-3]
There shall be no unnamed namespaces in header files [CODSTA-CPP-74-3]
using-directives shall not be used [CODSTA-CPP-75-3]
Multiple declarations for an identifier in the same namespace shall not
straddle a using-declaration for that identifier [CODSTA-CPP-76-3]
Const member functions shall not return non-const pointers or references
to class-data [CODSTA-CPP-77-3]
If a member function can be made static then it shall be made static,
otherwise if it can be made const then it shall be made const [CODSTA-CPP78-3]
BENEFITS
Prevents using instances of stdio.h functions (such as scanf/printf).
EXAMPLE
#include <stdio.h>
int main( ) {
printf("%s\n", "Hello World"); // Violation
return 0;
}
REPAIR
#include <iostream>
using namespace std;
int main( ) {
cout<<"Hello World"<<endl; // OK
return 0;
}
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Shifting from C to C++",
Item 2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Have assignment operator returns a reference to *this; make assignment operator's return
type a non-const reference to it's class' type [CODSTA-CPP-02-3]
DESCRIPTION
This rule makes sure your assignment operator's return type is non-const
reference to it's class' type and that it returns a reference to its lefthand
argument, *this. Having operator= return a reference to *this protects you
from not knowing where the temporary gets destroyed and allows you to
declare
the operator='s parameter as a reference to const, which is safer than
just
declaring it to be a reference.
See also: CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37, MRM-40, MRM-47,
OOP-27,
OOP-30, OOP-34
BENEFITS
Returning reference to *this in operator= functions protects you from not
knowing where the temporary gets destroyed and allows you to declare
the operator='s parameter as a reference to const, which is safer than
just
declaring it to be a reference.
EXAMPLE
class A {
public:
A( ) { }
void operator=( A& a ) {
return;
}
};
class C {
public:
C( ) { }
C operator=( C& c ) {
C *cp;
return *cp;
}
// Violation
// Violation
};
REPAIR
class A {
public:
A( ) { }
A& operator=( A& a ) {
return *this;
}
};
class C {
public:
C( ) { }
C& operator=( C& c ) {
return *this;
}
};
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 15
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 15
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 82
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Bitwise operators, comparison operators, logical operators, comma operator should be const
[CODSTA-CPP-03-3]
DESCRIPTION
Bitwise operators, comparison operators, logical operators,
comma operator should be const.
See also: CODSTA-CPP-38, CODSTA-CPP-43, CODSTA-CPP-44,
MISRA-104, MISRA2004-16_7, OPT-21
BENEFITS
C++ powerful const property should be enforced as appropriate,
to provide additional checks on the correct behavior of the code.
The semantics of operators "&", "^", "|", "~", "!=", "<=", "<",
"==", ">=", ">", "!", "&&", "||" ,and ","
presumes that they do not change the internals of the object they
are called on. Therefore, it is a good practice to declare them const.
EXAMPLE
class A {
public:
A& operator^( int x );
A& operator==( int x );
A& operator&&( int x );
A& operator,( int x );
};
//
//
//
//
Violation
Violation
Violation
Violation
REPAIR
class A {
public:
A& operator^( int x ) const;
A& operator==( int x ) const;
A& operator&&( int x ) const;
A& operator,( int x ) const;
};
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Generally improves runtime performance and predictability of program
behavior. May detect severe coding defects masked by the compiler.
EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
virtual ~A( ) {}
private:
int _i;
};
// Violation
int main( ) {
return 0;
}
REPAIR
/* One argument constructors that are not meant for type conversion should
be declared explicit. Conversions should be performed by conversion
functions rather than relying on implicit constructor calls. */
class A {
public:
explicit A( int i ) : _i( i ) {}
virtual ~A( ) {}
private:
int _i;
};
// OK
int main( ) {
return 0;
}
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 5
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 40
BENEFITS
Generally improves runtime performance and predictability of program
behavior. May detect severe coding defects masked by the compiler.
EXAMPLE
class A {
public:
operator const char*( ) const;
};
// Violation
void foo(){
A a;
const char* ch_ptr = a; // implicit conversion
}
REPAIR
class A {
public:
const char* asPointerToConstChar( ) const; // OK
};
void foo(){
A a;
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 5
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 177
SINCE
v7.2
NOTES
Handle to class-data is:
- reference to member variable
- pointer to member variable
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.
BENEFITS
The rule increases encapsulation, helps const member functions act const,
and minimizes the creation of dangling handles.
EXAMPLE
class Test
{
public:
{
Child c;
i1 = c.GetI1(); // Pointer to internal object saved
}
int & i2 = Child().GetI2(); // Reference to internal object saved
// Now "ptr", "i2" and "i3" are dangling pointers/references
}
REPAIR
Avoid returning handles to class-data.
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Postfix increment and decrement should be implemented in terms of their prefix counterparts
[CODSTA-CPP-07-3]
DESCRIPTION
"The prefix and postfix forms of these operators return different types.
In particular, prefix forms return a reference, postfix forms return
a const object. Let us make one more observation about the prefix and
postfix
increment operators. Except for their return values, they do the same
thing:
they increment a value. That is, they're supposed to do the same thing.
How can you be sure the behavior of postfix increment is consistent with
that of prefix increment? What guarantee do you have that their
implementations
won't diverge over time, possibly as a result of different programmers
maintaining and enhancing them? Unless you've followed the design
principle
embodied by the code below, you have no such guarantee. That principle is
that
postfix increment and decrement should be implemented in terms of their
prefix
counterparts. You then need only maintain the prefix versions,
because the postfix versions will automatically behave in a consistent
fashion."
SINCE
v7.0
BENEFITS
This rule prevents errorneous code and increase power and flexibility of
code.
EXAMPLE
class A {
public:
explicit A( int i = 0 ) : _i( i ) {}
~A( ) {}
A operator++( )
reference
{
++_i;
return *this;
}
A operator++( int )
const
{
A temp = *this;
++(*this);
return temp;
}
private:
int _i;
};
REPAIR
class A {
public:
explicit A( int i = 0 ) : _i( i ) {}
~A( ) {}
A& operator++( ) {
// OK
++_i;
return *this;
}
const A operator++( int ) {
// OK
A temp = *this;
++(*this);
return temp;
}
private:
int _i;
};
Prefix
increment operator
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 6
BENEFITS
Overloading these operators changes the way the compiler reads the
semantics of an expression, resulting in unpredictable program behavior.
EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
~A( );
int value( ) { return _i; }
private:
int _i;
};
int operator&&( A& lhs, A& rhs ) {
return lhs.value( ) && rhs.value( );
}
// Violation
REPAIR
Do not overload operator &&, || or ,(comma).
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
BENEFITS
Prevents assumptions how data is represented, which may dramatically
affect
the safety and reliability of code.
EXAMPLE
class A{};
class B{};
void foo( ) {
A *a;
B *b = reinterpret_cast<B*>( a );
}
// Violation
REPAIR
class A{};
class B{};
void foo( ) {
A *a;
void *pv = a;
B *b = static_cast<B*>( pv );
}
// OK
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 92
BENEFITS
Readability. It is generally expected that types with member functions
are classes, and many programmers still think of structs in terms
of their original meaning in C.
EXAMPLE
struct A
{
public:
int foo( );
};
// Violation
REPAIR
class A
{
public:
int foo( );
};
REFERENCES
// OK
Recommended by ParaSoft
BENEFITS
"Programs that use the new casts are easier to parse
(both for humans and for tools), and they allow compilers
to diagnose casting errors that would otherwise go undetected."
EXAMPLE
void foo1(){
int i, j;
double d = (double)i/j;
}
// Violation
class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = (Derived*)b;
// Violation
REPAIR
void foo1(){
int i, j;
double d = static_cast<double>(i)/j;
}
// OK
class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = dynamic_cast<Derived*>(b);
}
// OK
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Basics", Item 2
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 95
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 185
Put classes that are used as base classes and classes that are used as member variables into
separate include files [CODSTA-CPP-12-3]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- classes that are used as base classes,
- classes that are used as member variables,
See also: CODSTA-CPP-15, CODSTA-CPP-14, CODSTA-CPP-13
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class A {};
class B : public A {
A* a;
};
// Violation
// Violation
REPAIR
// header.h
class A {};
// source.cpp
#include "header.h"
class B : public A {
A* a;
};
// OK
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 8
Put classes that are used as function return type into separate include files [CODSTA-CPP-133]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- classes that appear as return types
See also: CODSTA-CPP-15, CODSTA-CPP-14, CODSTA-CPP-12
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class A {};
A* moo( );
class B {
A* foo( );
};
// Violation
// Violation
REPAIR
// header.h
class A {};
// source.cpp
#include "header.h"
A* moo( );
class B {
A* foo( );
};
// OK
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 8
Put classes that are used as argument types in function prototypes into separate include files
[CODSTA-CPP-14-3]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- classes that appear as argument types in function/member
function prototypes.
See also: CODSTA-CPP-15, CODSTA-CPP-13, CODSTA-CPP-12
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class A {};
void moo( A* a );
class B {
void foo( A* a );
};
// Violation
// Violation
REPAIR
// header.h
class A {};
// source.cpp
#include "header.h"
void moo( A* a );
class B {
void foo( A* a );
};
// OK
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
Put functions that are used in the body of inline member function into separate include file
[CODSTA-CPP-15-3]
DESCRIPTION
"When the following kinds of definitions are used (in implementation files
or in
other include files), they must be included as separate include files:
- function prototypes for function/member function used in inline member
function are defined in the file."
See also: CODSTA-CPP-14, CODSTA-CPP-13, CODSTA-CPP-12
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void moo( );
class A
{
inline void foo( )
{
moo( );
}
};
// Violation
REPAIR
// header.h
void moo( );
// source.cpp
#include "header.h"
class A
{
inline void foo( )
{
moo( );
}
};
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 8
When two operators are opposites (such as == and !=), it is appropriate to define both
[CODSTA-CPP-16-3]
DESCRIPTION
"When a client of a class is allowed to apply an operator against a class,
it also expects to be able to apply the negation of that operator against
a class. A good example is the operator==; its semantic opposite is the
operator!=, which should also be defined if operator== was defined."
Rule prevents using:
- '==' operator without '!=' operator
- '<=' operator without '>=' operator
- '<' operator without '>' operator
- '++' operator without '--' operator
- '+' operator without '-' operator
- '<<' operator without '>>' operator
- '&&' operator without '||' operator
BENEFITS
Rule improves readability and maintainability of code and
prevents misunderstanding the meaning of an overloaded operator.
EXAMPLE
class C { // Violation
public:
bool operator<=( C& c );
};
REPAIR
class C { // OK
public:
bool operator<=( C& c );
bool operator>=( C& c );
};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.7 Operator Overloading - Rec. 36
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 85
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Not using the struct keyword to declare a variable improves code
readability.
EXAMPLE
struct Position_t {};
struct Position_t Pos;
// Violation
REPAIR
struct Position_t {};
Position_t Pos;
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Encapsulate global variables and constants, enumerated types, and typedefs in a class
[CODSTA-CPP-18-5]
DESCRIPTION
"Encapsulate global variables and constants, enumerated types, and
typedefs
in a class. Static variables in a class should be used instead of global
variables and constants, enumerated data types, and typedefs."
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
enum Days {yesterday};
typedef int myint;
myint glob;
// Violation
// Violation
// Violation
REPAIR
class A {
public:
enum Days {yesterday};
typedef int MyInt;
static MyInt glob;
};
// OK
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 5 Assigning Names - Rec. 19
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 207
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Declare at least one constructor to prevent the compiler from doing so [CODSTA-CPP-19-2]
DESCRIPTION
If you do not write at least one constructor in a class, the compiler will
write a public constructor for you by default. This rule detects if you
do not declare at least one constructor.
See also: MRM-05, MRM-38, MRM-40, MRM-48, OOP-27, OOP-30, OOP-34
BENEFITS
Readability. If you follow this rule, you will make class initialization
explicit and prevent the compiler from initializing members improperly,
especially pointer members.
EXAMPLE
class A {
};
// Violation
REPAIR
class A {
A(){}
};
// OK
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 5
BENEFITS
Differentiating among functions leads to more object-oriented code
with behavior that is more intuitive to use and maintain.
EXAMPLE
#include <iostream>
using namespace std;
class A{
public:
A(int x=0);
A& operator+(A& a); // Violation (could be global)
};
class B{
public:
istream& operator>>(istream& input);
// Violation
// should be
global
ostream& operator<<(ostream& output) { as = "aaaa"; }; // Violation
// should be
friend
private:
char* as;
};
REPAIR
class A{
public:
A(int x=0);
};
A& operator+(A& a, A& b); // OK
class B{
public:
friend ostream& operator<<(ostream& output, B& out);
private:
char* as;
};
istream& operator>>(istream& input,const B& in);
ostream& operator<<(ostream& output, B& out) {
out.as = "aaaa";
return output;
};
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Design and Declaration", Item 19
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
The rule became obsolete because of new standard (Herb Sutter,Andrei
Alexandrescu, "C++ Coding Standards," Addison-Wesley, (C) 2005 Pearson
Education, Inc. Chapter: "Construction, Destruction, and Copying", Rule 55
)
which is implemented in CODSTA-CPP-24
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class MyClass {
public:
void operator=( const MyClass& );
};
// Violation
REPAIR
class MyClass {
public:
const MyClass& operator=( const MyClass& ); // OK
};
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 7 Classes - 7.6 Assignment Operators - Rec. 34
SINCE
v7.0
BENEFITS
Rule ensures greater flexibility and safety of code.
EXAMPLE
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
void clearEverything();
};
void WebBrowser::clearEverything()
{
// Violation
clearCache();
clearHistory();
removeCookies();
}
REPAIR
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
};
void clearEverything(WebBrowser& wb)
{
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 23
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Readability and maintainability. Using the :: operator helps the
maintainer of
code clearly identify used function.
EXAMPLE
namespace N {
void globalFoo1( );
}
void globalFoo1( ) {
}
void globalFoo2( ) {
globalFoo1( );
N::globalFoo1( );
}
// Violation
// Violation
REPAIR
namespace N {
void globalFoo1( );
}
void globalFoo1( ) {
}
void globalFoo2( ) {
::globalFoo1( );
// OK
::N::globalFoo1( ); // OK
}
REFERENCES
Recommended by ParaSoft
Avoid making any assignment operator virtual. Do not return const T& from assignment
operator [CODSTA-CPP-24-3]
DESCRIPTION
"Avoid making any assignment operator virtual."
If you need virtual assignment, prefer to provide a named function
instead (e.g. virtual void Assign(const &T)). "Don't return const T&.
Although this has the benefit of preventing odd code like (a=b)=c, it has
the
drawback that you wouldn't be able to put T objects into standard
library containers; the containers require that assignment return plain
T&."
See also: CODSTA-CPP-02, CODSTA-CPP-21, MRM-04, MRM-37, MRM-40, MRM-47,
OOP-27,
OOP-30, OOP-34
BENEFITS
Rule prevents lack of error safety and improves good programming style.
EXAMPLE
class A {
public:
virtual int& operator=(const int&); // Violation
const A& operator=(const A&);
// Violation
};
template<class T> class B {
public:
virtual T& operator=(const T&);
const B<T>& operator=(B<T>&);
};
// Violation
// Violation
REPAIR
class A {
public:
const int& operator=(const int&);
A& operator=(const A&);
};
template<class T> class B {
public:
T& operator=(const T&);
B<T>& operator=(B<T>&);
};
template<class T> class C {
public:
C<T>& operator=(const C<T>&);
T& operator=(T&);
};
// OK
// OK
// OK
// OK
// OK
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 55
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Consider making virtual functions nonpublic, and public functions nonvirtual [CODSTA-CPP25-3]
DESCRIPTION
"Prefer to make public functions nonvirtual.
Prefer to make virtual functions private,
or protected if derived classes need to be able to call the base
versions."
EXCEPTIONS
"Rule doesn't apply to destructors because of their special
order of execution."
BENEFITS
Rule helps keeping good class encapsulation, makes the base class robust
in the face of change, allows each interface to take its natural shape.
EXAMPLE
class A{
public:
virtual void foo(); // Violation
void goo();
};
REPAIR
class B{
public:
void goo();
private:
virtual void foo(); // OK
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 39
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Keep types and functions in separate namespaces unless they're specifically intended to work
together [CODSTA-CPP-26-3]
DESCRIPTION
"We've all had those days, and the odds are decent that the mystery
culprit was
some form of the aforementioned problem, where ADL pulled in names from
other
namespaces inappropriately just because types from those namespaces were
being
used nearby.
This problem is not unique to uses of the standard library. It can and
does
happen in C++ with the use of any type that is defined in the same
namespace
as functions - especially templated functions, and most especially
operators that aren't specifically related to that type. Don't do that.
The easiest way to avoid this whole category of problems is to in general
avoid
putting nonmember functions that are not part of the interface of a type X
into
the same namespace as X, and especially never ever put templated functions
or
operators into the same namespace as a user-defined type."
SINCE
v7.0
BENEFITS
This rule prevents from mysterious and incomprehensible compiler errors,
mainly when the standard library is used.
EXAMPLE
namespace NS1 {
class Class {};
void foo01( );
// Violation
REPAIR
namespace NS1 {
class Class {};
void foo03( Class x );
void foo04( Class* x );
}
namespace NS2 {
void foo01( );
void foo02( int x );
}
// OK
// OK
// OK
// OK
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 58
Keep a type and its nonmember function interface in the same namespace [CODSTA-CPP-273]
DESCRIPTION
"Nonmember functions that are designed to be a part of the interface of
a class X (operators and helper functions) must be defined in the same
namespace as the X in order to be called correctly."
BENEFITS
Rule improves efficiency and readability of code.
EXAMPLE
namespace N{
class X{
public:
void foo();
};
}
N::X operator+(const N::X&, const N::X&); // Violation
REPAIR
namespace N{
class X{
public:
void foo();
X operator+(const X&);
};
}
// OK
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 57
When binary arithmetic operators are defined ( + , - , * , / , ^ , % , | , & , >> , << ), assignment
versions should be provided too [CODSTA-CPP-28-3]
DESCRIPTION
When binary arithmetic operators are defined
( + , - , * , / , ^ , % , | , & , >> , << ), assignment versions
should be provided too.
This rule warns you whenever it finds binary operator without
canonical assignment version.
See also: CODSTA-CPP-29
BENEFITS
Assignment versions of operator are more efficient than standalone versions.
EXAMPLE
class A{};
A operator+( A& a, A& b );
class B{
B operator+( B& a );
};
REPAIR
class A{};
A operator+( A& a, A& b ); // OK
A operator+=( A& a, A& b ); // OK
class B{
B operator+( B& a );
B operator+=( B& a );
};
// OK
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-
Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 27
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
If operator@ is made a nonmember function, it will have the desirable
property
of accepting the same implicit conversions on its left-hand side and
right-hand
side parameters. By having operator@ accepting its first parameter by
value,
you arrange for compiler itself to perform the copy for you implicitly,
and this
can give the compiler more leeway in applying optimizations.
Making the operator@ returning a const value has the advantage that it
disables
nonsensical code such as a + b = c, but it does so at the cost of
disabling some
EXAMPLE
class A{
public:
A( const A& );
A operator+=( A& a ){}
A operator-=( A& a ){}
A& operator-( A& a ){}
global
A operator*=( A& a ){}
should
be a reference to class
- The last operation of "*="
function
//
};
A operator+( A& a, A& b ){
// Violation - No return statement...
return a.operator+=( a );//
- Declare and initialize
temporary
//
local variable by first
parameter
};
A operator*( A& a, A& b ){
example
A tmp(a);
return tmp += b;
return tmp *= b;
};
REPAIR
class A{
public:
// OK
// OK
// OK
// OK
// OK
// OK
// OK
// OK
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 27
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Prefer non-member operators than member ones to support mixed-mode arithmetic [CODSTACPP-30-3]
DESCRIPTION
"Declare non-member functions when type conversions should apply to all
parameters."
SINCE
v7.0
BENEFITS
Declaration of non-member functions allows compilers to perform implicit
type
conversions on all arguments and supports mixed mode arithmetic.
EXAMPLE
class complex {
double re, im;
public:
complex( double r, double i ) : re( r ), im( i ) {}
complex operator+ ( complex );
complex operator+=( complex );
};
REPAIR
class complex {
double re, im;
public:
complex( double r, double i ) : re( r ), im( i ) {}
complex& operator+=( complex a );
};
complex operator+( complex a, complex b ) {
complex r = a;
return r += b;
// OK
// Violation
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 24
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Prevents using the keyword `explicit'.
EXAMPLE
class A {
public:
explicit A( int );
explicit A( double ) {}
};
REPAIR
class A {
public:
A( int );
A( double ) {}
};
// OK
// OK
REFERENCES
Recommended by ParaSoft
// Violation
// Violation
Member functions shall not be defined within the no-template class definition [CODSTA-CPP32-3]
DESCRIPTION
Functions defined within the class definition are implicitly inline;
however,
defining member functions within a class definition also makes the class
definition less compact and harder to read. This rule detects if you
define
member functions in the class definition.
See also: CODSTA-CPP-33
BENEFITS
This rule ensure better data hiding by separating interface and
implementation.
EXAMPLE
class A {
public:
int foo( ) {};
inline int bar( );
};
// Violation
REPAIR
class A {
public:
int foo( );
inline int bar( );
};
int A::foo( ) {};
inline int A::bar( ) {
return 0;
// OK
};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 21
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 109
Member functions shall not be defined within the template class definition [CODSTA-CPP-333]
DESCRIPTION
Functions defined within the class definition are implicitly inline;
however,
defining member functions within a class definition also makes the class
definition less compact and harder to read. This rule detects if you
define
member functions in the class definition.
See also: CODSTA-CPP-32
BENEFITS
This rule ensure better data hiding by separating interface and
implementation.
EXAMPLE
template <class T>
class A {
public:
void foo( ) {}
};
// Violation
REPAIR
template <class T>
class A {
public:
void foo( );
};
template <class T> void A<T>::foo( ) {}
REFERENCES
Recommended by ParaSoft
// OK
BENEFITS
Rule improves safety and reliability of code.
EXAMPLE
class B {};
class D : public B {};
void foo( B* pb, D* pd ) {
B* pb2 = static_cast<B*>( pd );
}
// Violation
REPAIR
class B {};
class D : public B {};
void foo( B* pb, D* pd ) {
B* pb2 = dynamic_cast<B*>( pd );
}
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 93
2. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
NOTES
Rule disallows usage of dynamic_casts.
BENEFITS
"(...) Many implementations of dynamic_cast can be quite slow. For
example,
at least one common implementation is based in part on string comparisons
of class names. If you're performing a dynamic_cast on an object in
a single-inheritance hierarchy four levels deep, each dynamic_cast under
such an implementation could cost you up to four calls to strcmp to
compare
class names."
EXAMPLE
#include <vector>
#include <boost/tr1/memory.hpp>
using namespace std;
class Window {
virtual void onResize( );
};
class SpecialWindow : public Window {
public:
virtual void onResize( );
void blink( );
};
void foo( )
{
typedef vector<std::tr1::shared_ptr<Window> > VPW;
VPW winPtrs;
for (VPW::iterator iter = winPtrs.begin( ); iter != winPtrs.end( );
++iter)
{
if (SpecialWindow *psw =
dynamic_cast<SpecialWindow*>( iter->get( ) ))
//
Violation
psw->blink( );
}
}
REPAIR
#include <vector>
#include <boost/tr1/memory.hpp>
using namespace std;
class Window {
virtual void onResize( );
};
class SpecialWindow : public Window {
public:
virtual void onResize( );
void blink( );
};
void foo( ) {
typedef std::vector<std::tr1::shared_ptr<SpecialWindow> > VPSW;
VPSW winPtrs;
for (VPSW::iterator iter =
winPtrs.begin( ); iter != winPtrs.end( );++iter)
(*iter)->blink( );
// OK
}
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 27
Avoid using global variables, global functions, and class in file outside namespaces
[CODSTA-CPP-36-3]
DESCRIPTION
This rule detects the use of global variables, classes,
and global functions outside of namespaces.
BENEFITS
Prevents the use of global variables, classes, and global functions
outside namespaces. All data and functions in a file should be inside
one or more namespaces.
EXAMPLE
int var = 0;
// Violation
// 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
BENEFITS
If you define a struct/class in a function (as opposed
to declaring it), then it becomes a local type, which
- cannot be reused by the compiler
- can result in non-compatible definitions for the same declared type.
EXAMPLE
void foo(){
class A { // Violation
// ...
};
// ...
}
REPAIR
class A { // OK
// ...
};
void foo(){
// ...
}
REFERENCES
Recommended by ParaSoft
BENEFITS
C++ powerful const property should be enforced as appropriate,
to provide additional checks on the correct behavior of the code.
The semantics of operators "()", "[]", "->", and cast operators
presumes that they do not change the internals of the object they
are called on. Therefore, it is a good practice to declare them const.
EXAMPLE
class A
{
public:
A& operator()( int x ); // Violation
A& operator[]( int x ); // Violation
A& operator->( );
// Violation
operator int( );
// Violation
};
REPAIR
class A
{
public:
A& operator()( int x ) const;
A& operator[]( int x ) const;
A& operator->( ) const;
operator int( ) const;
};
REFERENCES
//
//
//
//
OK
OK
OK
OK
EXCEPTIONS
This rule doesn't apply to writing class member using declarations to
bring
in base class member names as needed.
BENEFITS
Prevents writing usings directives in header files which are meant
to be included in an unbounded number of implementation files.
Rule also prevents messing with the meaning of code in someone else's
header.
EXAMPLE
// file1.cpp
#include <stdio.h>
using namespace std;
#include <stddef.h>
// file.h
#include <stdio.h>
using namespace std;
// file2.cpp
#include "file.h"
#include <stddef.h>
// Violation
// Violation
REPAIR
// file.cpp
#include <stdio.h>
#include <stddef.h>
using namespace std;
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 59
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Limiting the number of objects in a class can reduce code complexity.
EXAMPLE
class Base {
// Violation
public:
class X {}; // exception definition
Base( ) {
// limit missing
// constructor stuff here
++numObjects;
}
~Base( ) {
--numObjects;
// destructor stuff here
}
private:
static int numObjects;
};
REPAIR
class Base {
// OK
public:
class X {}; // exception definition
Base( ) {
if (numObjects >= 1) throw X( );
// constructor stuff here
++numObjects;
}
~Base( ) {
--numObjects;
// destructor stuff here
}
private:
static int numObjects;
};
REFERENCES
Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Techniques", Item 26
BENEFITS
Readability.
EXAMPLE
enum Colors { RED, BLUE, GREEN };
enum Colors c;
// Violation
REPAIR
enum Colors { RED, BLUE, GREEN };
Colors c;
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Prevents using the keyword `mutable'.
EXAMPLE
class Date{
public:
int getMonth( ) const;
private:
mutable int month;
// Violation
int year;
int day;
};
int Date::getMonth( ) const {
month++;
return month;
}
REPAIR
Do not declare member variables with the 'mutable' keyword
REFERENCES
Recommended by ParaSoft
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
REPAIR
struct Foo {
int x;
int y;
};
int Bar( const Foo &f ) {
return f.x;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Have the non-const version call the const version of member function instead of duplicating
the const version definition [CODSTA-CPP-44-3]
DESCRIPTION
"When const and non-const member functions have essentially identical
implementations, code duplication can be avoided by having the non-const
version call the const version."
See also: CODSTA-CPP-03, CODSTA-CPP-38, CODSTA-CPP-43,
MISRA-104, MISRA2004-16_7, OPT-21
SINCE
v7.0
BENEFITS
"Decrease compilation time, maintenance, and code-bloat headaches."
EXAMPLE
#include <iostream>
#include <string.h>
using namespace std;
class TextBlock {
public:
const char& operator[]( size_t position ) const
// do bounds checking
// log access data
// verify data integrity
return text[ position ];
}
char& operator[]( size_t position ) {
// do bounds checking
// log access data
// verify data integrity
return text[ position ];
}
private:
{ // OK
// Violation
string text;
};
REPAIR
#include <iostream>
#include <string.h>
using namespace std;
class TextBlock {
public:
const char& operator[]( size_t position ) const { // OK
// some code
return text[ position ];
}
char& operator[]( size_t position ) {
// OK
return const_cast<char&>(
static_cast<const TextBlock&>(*this)[ position ] );
}
private:
string text;
};
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
In the private section of a class items shall be declared in the following order: Constructors,
Destructor, Member Functions, Member Operator Function, Enumerations and others
[CODSTA-CPP-45-3]
DESCRIPTION
Following the above ordering convention makes it easier for those
unfamiliar
with a class to figure out its functionality.
See also: CODSTA-CPP-46, CODSTA-CPP-47, CODSTA-CPP-48, CODSTA-CPP-49
BENEFITS
Rule makes source code more readable.
EXAMPLE
class A
// Violation
{
private:
A( );
int foo( );
~A( );
};
REPAIR
class A
// OK
{
private:
A( );
~A( );
int foo( );
};
REFERENCES
Recommended by ParaSoft
BENEFITS
Readability and maintainability.
EXAMPLE
class Test {
protected:
void foo2(
private:
void foo3(
public:
void foo1(
};
// Violation
);
);
);
REPAIR
class Test {
public:
void foo1(
protected:
void foo2(
private:
void foo3(
};
// OK
);
);
);
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class Test {// Violation
public:
void foo1( );
private:
void foo3( );
protected:
void foo2( );
};
REPAIR
class Test {// OK
public:
void foo1( );
protected:
void foo2( );
private:
void foo3( );
};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
In the protected section of a class items shall be declared in the following order:
Constructors, Destructor, Member Functions, Member Operator Function, Enumerations and
others [CODSTA-CPP-48-3]
DESCRIPTION
Following the above ordering convention makes it easier for those
unfamiliar
with a class to figure out its functionality.
See also: CODSTA-CPP-45, CODSTA-CPP-46, CODSTA-CPP-47, CODSTA-CPP-49
BENEFITS
Rule makes source code more readable.
EXAMPLE
class A
// Violation
{
protected:
A( );
int foo( );
~A( );
};
REPAIR
class A
// OK
{
protected:
A( );
~A( );
int foo( );
};
REFERENCES
Recommended by ParaSoft
In the public section of a class items shall be declared in the following order: Constructors,
Destructor, Member Functions, Member Operator Function, Enumerations and others
[CODSTA-CPP-49-3]
DESCRIPTION
Following the above ordering convention makes it easier for those
unfamiliar
with a class to figure out its functionality.
See also: CODSTA-CPP-45, CODSTA-CPP-46, CODSTA-CPP-47, CODSTA-CPP-48
BENEFITS
Readability.
EXAMPLE
class A { // Violation
public:
A( );
int foo( );
~A( );
};
REPAIR
class A { // OK
public:
A( );
~A( );
int foo( );
};
REFERENCES
Recommended by ParaSoft
Do not use static keyword except inside functions and classes [CODSTA-CPP-50-3]
DESCRIPTION
Do not use static keyword except inside functions and classes (C++ only).
Note that static keyword is perfectly legal in C files at the file scope.
"By deprecating a feature, the standards committee expresses the wish that
the feature would go away. However, the committee does not have a mandate
to
remove a heavily used feature however redundant or dangerous it may be.
Thus, a deprecation is a strong hint to the users to avoid the feature.
The keyword s t a t i c , which usually means statically allocated,
can be
used to indicate that a function or an object is local to a translation
unit.
For example:
// file1:
static int glob ;
// file2:
static int glob ;
This program genuinely has two integers called g l o b . Each g l o b is
used
exclusively by functions defined in its translation unit. The use of
static to
indicate "local to translation unit" is deprecated in C++. Use unnamed
namespaces instead."
SINCE
v7.0
BENEFITS
Rule prevents using deprecated language structures.
EXAMPLE
static int glob;
// Violation
// Violation
// Violation
// Violation
// Violation
REPAIR
namespace{
static int glob;
}
// OK
class A {
static void foo( ); // OK
};
void zoo( ) {
static int c;
}
class B {
public:
static struct S {
int a;
static int b;
} S_var;
};
// OK
// OK
// OK
REFERENCES
1. Stroustroup C++ Programming Language 3rd Edition. 9.2, p200.
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
EXCEPTIONS
Static inline functions and inline functions defined in anonymous
namespace
are permitted.
BENEFITS
Rule helps to prevent unpredictable behaviour of program.
EXAMPLE
inline int foo( ) {
return 10;
}
class LocalClass {
public:
int bar( ) {
return 20;
}
};
// Violation
// Violation
int test( ) {
LocalClass lc;
return foo() + lc.bar();
}
REPAIR
static inline int foo( ) {
return 10;
}
namespace {
class LocalClass {
public:
int bar( ) {
return 20;
}
};
}
// OK
// OK
int test( ) {
LocalClass lc;
return foo() + lc.bar();
}
REFERENCES
1. Stroustroup C++ Programming Language 3rd Edition. 9.2, p199.
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Consider using the natural relationship between the assignment version of an operator and
the stand-alone version [CODSTA-CPP-52-3]
DESCRIPTION
"A good way to ensure that the natural relationship between the assignment
version of an operator (e.g., operator+=) and the stand-alone version
(e.g., operator+) exists is to implement the latter in terms of the
former.
For example:"
class Rational {
public:
Rational& operator+=(const Rational& rhs);
};
const Rational operator+(const Rational& lhs,
const Rational& rhs)
{
return Rational(lhs) += rhs;
}
SINCE
v7.0
BENEFITS
"In this example, operators += is implemented (elsewhere) from scratch,
and
operator+ calls them to provide their own functionality. With this design,
only
the assignment version of these operator need to be maintained.
Furthermore,
assuming the assignment versions of the operators are in the class's
public
interface, there is never a need for the stand-alone operators to be
friends
of the class."
See also: OOP-11, CODSTA-CPP-29
EXAMPLE
class A {
public:
A operator+=( A& b );
A operator-=( A& b );
A operator*=( A& b );
friend A operator*( A& a, A& b );
};
// Violation
// Violation
// Violation
// OK
REPAIR
class A {
public:
A operator+=( A& b );
A operator-=( A& b );
A operator*=( A& b );
// OK - removed friend declaration
};
A operator+( A& a, A& b ){
return A( a ) += b;
}
// OK
// OK
// OK
return A( a ) *= b;
}
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 22
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
NOTES
For parameters and variables of pointer type the const qualifier
should be applied to the pointer, not to the pointed object.
BENEFITS
It's safe, it's checked at compile time, and it's integrated
with C++'s type system. It also prevents future revisions
from unintentional changing the caller's data.
EXAMPLE
int foo1(int param1,
int* param2,
const int* param3)
// Violation
// Violation
// Violation - const is applied to the
// pointed object, not to the pointer
{
int var1 = 0;
// Violation
return param1 + *param2 + *param3 + var1;
}
int foo2(int param1,
// OK - param1 is modified
int* param2,
const int* param3)
// OK - param2 is modified
// OK - param3 is modified
{
int var1 = 0;
// OK - var1 is modified
param1++;
param2++;
param3++;
var1 = param1 + *param2 + *param3;
return var1;
}
REPAIR
// Fixed violations - const added
int foo1(const int param1,
int* const param2,
const int* const param3)
// OK
// OK - const is applied to the pointer
// OK - const is applied to the pointed
// object and to the pointer
{
const int var1 = 0;
// OK
return param1 + *param2 + *param3 + var1;
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc., Chapter: "Coding Style", Rule 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.1
BENEFITS
"Writing const appropriately helps you gain a better understanding of your
design and makes your code sturdier and safer."
EXAMPLE
class A
{
int foo(int a)
{
return a;
}
};
// Violation
REPAIR
class A
{
int foo(int a) const
{
// OK
return a;
}
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 15
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 69
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
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:
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 97
A class, structure, or enumeration will not be declared in the definition of its type [CODSTACPP-56-3]
DESCRIPTION
A class, structure, or enumeration will not be declared in the definition
of its type.
SINCE
v7.1
BENEFITS
Rule improves readability.
EXAMPLE
enum
{
up,
down
} direction;
// Violation
REPAIR
enum direction_e
{
up,
down
};
direction_e direction; // OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 141
Namespaces will not be nested more than two levels deep [CODSTA-CPP-57-3]
DESCRIPTION
Namespaces will not be nested more than two levels deep.
SINCE
v7.1
BENEFITS
Simplicity and clarity.
Deeply nested namespaces can be difficult to comprehend and use correctly.
EXAMPLE
namespace A
{
namespace B
{
namespace C
{
namespace D // Violation
{
}
}
}
}
REPAIR
namespace A
{
namespace B
{
namespace C // OK
{
}
namespace D // OK
{
}
}
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.11 Namespaces, AV Rule 99
The value returned by a function having a non-void return type that is not an overloaded
operator shall always be used [CODSTA-CPP-58-3]
DESCRIPTION
"In C++ it is possible to call a function without using the return value,
which may be an error. The return value of a function shall always be
used."
SINCE
v7.2
EXCEPTIONS
"The return value of a function may be discarded by use of a (void) cast.
Overloaded operators are excluded, as they should behave in the same way
as built-in operators."
BENEFITS
Rule improves readability of code
EXAMPLE
short func ( short para1 )
{
return para1;
}
void discarded ( short para2 )
{
func ( para2 );
// Violation
}
REPAIR
short func ( short para1 )
{
return para1;
}
void discarded ( short para2 )
{
(void)func ( para2 );
// OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-7
SINCE
v7.2
BENEFITS
Rule prevents undefined and implementation-defined behaviour.
EXAMPLE
#include <stdio.h> // Violation
REPAIR
#include <cstdio>
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Only those escape sequences that are defined in ISO/IEC 14882:2003 shall be used [CODSTACPP-60-3]
DESCRIPTION
"Only those escape sequences that are defined in ISO/IEC 14882:2003
shall be used. The defined escape sequences (ISO/IEC 14882:2003) are:
\n, \t, \v, \b, \r, \f, \a, \\, \?, \', \", \<Octal Number>,
\x<Hexadecimal Number>"
SINCE
v7.2
BENEFITS
The use of an undefined escape sequence leads to undefined behaviour.
EXAMPLE
#include <stdio.h>
void foo( ) {
printf("ABCD\u1111");
printf("abcd\hgf");
printf("\k");
}
// Violation
// Violation
// Violation
REPAIR
Do not use escape sequences not defined in the ISO/IEC 14882:2003
standard.
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-1
2. General Principles of Software Validation;
Objects or functions with external linkage shall be declared in a header file [CODSTA-CPP-613]
DESCRIPTION
"Placing the declarations of objects and functions with external linkage
in a header file documents that they are intended to be accessible from
other
translation units. If external linkage is not required, then the object or
function shall either be declared in an unnamed namespace or declared
static."
SINCE
v7.2
EXCEPTIONS
This rule does not apply to main, or to members of unnamed namespaces.
BENEFITS
Rule reduce the visibility of objects and functions.
EXAMPLE
// file.cpp
int a1 = 0;
void fun(){}
// Violation
// Violation
REPAIR
// file.h
extern int a1;
extern void fun();
// file.cpp
#include "file.h"
int a1 = 0;
// OK
// OK
// OK
void fun(){}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-3-1
SINCE
v7.2
BENEFITS
"As a result of this rule, NULL is considered to have pointer type."
EXAMPLE
#include <cstddef>
void f1( int );
void foo( )
{
f1( NULL ); // Violation
}
REPAIR
void f1( int );
void foo( )
{
f1( 0 ); // OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
"As a result of this rule, NULL is considered to have pointer type."
EXAMPLE
#include <cstddef>
void f1( int* );
void foo( )
{
f1( 0 ); // Violation
}
REPAIR
#include <cstddef>
void f1( int* );
void foo( )
{
f1( NULL ); // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-2
The condition of an if-statement and the condition of an iteration-statement shall have type
bool [CODSTA-CPP-64-3]
DESCRIPTION
"If an expression with type other than bool is used in the condition
of an if-statement or iteration statement, then its result will be
implicitly converted to bool."
SINCE
v7.2
NOTES
Rule does not report violations if the condition expression is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.
EXCEPTIONS
"A condition of the form type-specifier-seq declarator is not required
to have type bool."
BENEFITS
"The condition expression shall contain an explicit test (yielding a
result
of type bool) in order to clarify the intentions of the developer."
EXAMPLE
void foo()
{
int i;
if (i){} // Violation
}
REPAIR
void foo()
{
int i;
if (i != 0){} // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-13
SINCE
v7.2
BENEFITS
"The first operand shall contain an explicit test (yielding a result of
type
bool) in order to clarify the intentions of the developer."
EXAMPLE
void foo(int i, int j, int k, int l)
{
i = j ? k : l;
// Violation
}
REPAIR
void foo(int i, int j, int k, int l)
{
i = (j != 0) ? k : l;
// OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-14
C-style casts (other than void casts) and functional notation casts (other than explicit
constructor calls) shall not be used [CODSTA-CPP-66-3]
DESCRIPTION
"C-style (cast notation), and functional notation casts that do not invoke
a converting constructor are capable of performing casts between unrelated
types."
SINCE
v7.2
EXCEPTIONS
"A C-style cast to void may be used to signify that the return value
for a non-void function call is being ignored"
BENEFITS
C++ casts are more specific than C casts and are much easier to locate
and read.
EXAMPLE
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD2 = (Derived *) pB;
// Violation
REPAIR
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD1 = dynamic_cast<Derived*>( pB );
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-4
Each operand of the ! operator, the logical && or the logical || operators shall have type bool
[CODSTA-CPP-67-3]
DESCRIPTION
"The use of operands with types other than bool with these operators is
unlikely to be meaningful (or intended). This rule allows the detection of
such uses, which often occur because the logical operators (&&, || and !)
can be easily confused with the bitwise operators (&, | and ~)."
SINCE
v7.2
NOTES
Rule does not report violations if the operand is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.
BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.
EXAMPLE
/* examples of incorrect code */
void foo(int a, int b, int c, int d, int* ptr)
{
if ( 1 && ( c < d ) ) {}
// Violation
if ( ( a < b ) && ( c + d ) ){} // Violation
if ( a || ( c + d ) ) {}
// Violation
if ( !ptr ) {}
// Violation
}
REPAIR
/* examples of correct code */
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-1
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
class A
{
public:
A * operator & ( );
};
// Violation
REPAIR
Do not overload the unary '&' operator
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-3
A for loop shall contain a single loop-counter which shall not have floating type [CODSTACPP-69-3]
DESCRIPTION
"A for loop without exactly one loop-counter is simply a while loop.
If this is the desired behaviour, then a while loop is more appropriate."
SINCE
v7.2
NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
BENEFITS
Rule helps to ensure deterministic loop termination.
EXAMPLE
void foo()
{
int x = 0;
int y;
y = 0;
for (x = 0; x < y; x = y++){} // Violation
}
REPAIR
void foo3()
{
int x = 0;
int y;
y = 0;
x = 0;
while(x < y) // OK
{
x = y++;
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-1
If loop-counter is not modified by -- or ++, then, within condition, the loop-counter shall only
be used as an operand to <=, <, > or >= [CODSTA-CPP-70-3]
DESCRIPTION
"When the loop-counter is modified using an operator other than -- or ++,
then == and != shall not be used, as loop termination may not occur,
which may be inconsistent with developer expectations."
SINCE
v7.2
NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
BENEFITS
Rule helps to ensure deterministic loop termination.
EXAMPLE
void foo()
{
int i;
for ( i = 1; i != 10; i += 2 ){} // Violation
}
REPAIR
void foo()
{
int i;
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-2
The loop-counter shall be modified by one of: --, ++, -=n, or +=n; where n remains constant for
the duration of the loop [CODSTA-CPP-71-3]
DESCRIPTION
"The loop-counter shall be modified by one of: --, ++, -=n, or +=n;
where n remains constant for the duration of the loop"
SINCE
v7.2
NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
BENEFITS
Rule helps to ensure deterministic loop termination.
EXAMPLE
void foo()
{
int x;
for ( x = 0; x < 10; x = x + 1 ){} // Violation
}
REPAIR
void foo()
{
int x;
for ( x = 0; x < 10; ++x ){} // OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-4
A loop-control-variable other than the loop-counter shall not be modified within condition or
expression [CODSTA-CPP-72-3]
DESCRIPTION
"A loop-control-variable other than the loop-counter shall
not be modified within condition or expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
loop-control-variables are either the loop-counter, or flags used for
early
loop termination. The code is easier to understand if these are not
modified
within condition or expression."
SINCE
v7.2
NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.
BENEFITS
Rule improves readability of code.
EXAMPLE
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; flag = test(++x) ) {}
}
// Violation
REPAIR
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; ++x ) // OK
{
flag = test(x);
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-5
A loop-control-variable other than the loop-counter which is modified in statement shall have
type bool [CODSTA-CPP-73-3]
DESCRIPTION
"A loop-control-variable other than the loop-counter which is modified
in statement shall have type bool.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
loop-control-variables are typically used to terminate a for loop early.
The code is easier to understand if this is done with the use
of Boolean values"
SINCE
v7.2
NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && ( u8a != 3U ); ++x )
{
u8a = 5;
// Violation
}
}
REPAIR
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && flag; ++x )
{
u8a = 5;
// OK
flag = u8a != 3U;
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-6
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
// file.hpp
namespace // Violation
{
extern int x;
}
REPAIR
Do not define unnamed namespaces in header files
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using namespace NS1; // Violation
void f ()
{
++j1;
}
REPAIR
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using NS1::j1;
// OK
void f ()
{
++j1;
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-4
Multiple declarations for an identifier in the same namespace shall not straddle a usingdeclaration for that identifier [CODSTA-CPP-76-3]
DESCRIPTION
"The set of identifiers introduced by a using-declaration does not include
any
declarations that may be added by a subsequent declaration in the
namespace.
Any subsequent declarations will not be found through the usingdeclaration,
which may not be consistent with developer expectations."
SINCE
v7.2
BENEFITS
Rule prevents unexpected behaviour.
EXAMPLE
namespace NS
{
void foo( unsigned short );
}
using NS::foo;
namespace NS
{
void foo( unsigned int );
}
void some()
{
foo( 0U );
}
// Violation
REPAIR
namespace NS
{
void foo( unsigned short );
}
namespace NS
{
void foo( unsigned int );
}
// OK
using NS::foo;
void some()
{
foo( 0U );
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-5
Const member functions shall not return non-const pointers or references to class-data
[CODSTA-CPP-77-3]
DESCRIPTION
"When an object is declared with const class type, only const member
functions
can be invoked on that object. The common expectation of const member
functions
is that the state of the object may not be modified when invoking the
functions. However, returning a non-const pointer or reference to classdata
from a const function allows a modification to the conceptual state of an
object."
See also: CODSTA-CPP-06, OOP-12, OOP-36
NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.
BENEFITS
Rule prevents exposing internal state of the object to clients, so they
won't
uncontrollably modify the state of the object. Enforces data encapsulation
that
is a cornerstone of Object Oriented programming. Improves code
maintainability.
Helps const functions act const.
EXAMPLE
class Test
{
public:
Test(int & p) : _i(p)
{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1() const
{
return &_i; // Violation
}
protected:
int& GetI2() const
{
return _i; // Violation
}
int * GetI3() const
{
return _k; // Violation
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
GetI2() = 0; // Modification of possibly-const object
*(GetI3()) = 0; // Modification of possibly-const object
}
private:
int z;
};
void bar()
{
const Child c;
*(c.GetI1()) = 0; // Modification of possibly-const object
}
REPAIR
class Test
{
public:
Test(int & p) : _i(p)
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1() const
{
return &_i; // OK
}
protected:
const int& GetI2() const
{
return _i; // OK
}
const int * GetI3() const
{
return _k; // OK
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
// GetI2() = 0; // Not compilable - can't modify const object
// *(GetI3()) = 0; // Not compilable - can't modify const
object
}
private:
int z;
};
void bar()
{
const Child c;
// *(c.GetI1()) = 0; // Not compilable - can't modify const object
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 9-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
If a member function can be made static then it shall be made static, otherwise if it can be
made const then it shall be made const [CODSTA-CPP-78-3]
DESCRIPTION
"Declaring a member function static or const limits its access
to the non-static data members."
See also: CODSTA-CPP-54
SINCE
v7.2
BENEFITS
Rule prevents unintentional modification of the data.
EXAMPLE
class A
{
public:
int foo1 ()
{
return m_s;
}
int foo2 ()
{
return m_i;
}
private:
int m_i;
static int m_s;
};
REPAIR
class A
{
public:
static int foo1 ()
{
return m_s;
}
int foo2 () const
{
return m_i;
}
// OK
// OK
private:
int m_i;
static int m_s;
};
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Array elements shall be accessed by the array operator [] rather than
the dereference operator '*'. Access to array by the dereference operator
'*' is cryptic and hides the real intention.
EXAMPLE
void foo()
{
int array[2];
*(array+1) = 0; // Violation
*array = 0;
// Violation
}
REPAIR
void foo()
{
int array[2];
array[1] = 0; // OK
}
REFERENCES
Motorola Coding Standards R-46
BENEFITS
Prevents error prone code.
The ordering of bits in memory varies from compiler to
compiler. In addition, many popular compilers generate
inefficient code for reading and writing bit members,
and there are potentially severe thread safety issues
relating to bit fields (especially on multiprocessor
systems) due to the fact that most machines cannot
manipulate arbitrary sets of bits in memory, but must
instead load and store whole words.
EXAMPLE
struct A
{
int iVarBitField : 8;
int iVar;
};
REPAIR
Do not declare bitfield.
REFERENCES
Recommended by Parasoft
// Violation
BENEFITS
Code is easier to debug. Prevents incorrectly macro writing.
EXAMPLE
#define PI 3.1416
// Violation
REPAIR
const float PI = 3.1416; // OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 10 Constants - Rule 36
BENEFITS
Makes code more readable.
EXAMPLE
void Foo()
{
int static iVar = 9; // Violation
return;
}
REPAIR
int iVar = 9; // OK
void Foo()
{
iVar++;
return;
}
REFERENCES
Recommended by ParaSoft
EXCEPTIONS
"One exception to this rule is represented by functions which provide
interfaces to other languages (such as C). These are likely to only allow
pre-defined data types to be used as arguments in the interface, in which
case pointers to pointers are needed. Another example is the second
argument
to the main function, which must have the type char*[]."
BENEFITS
Rule improves the readability of the code and encourages data abstraction.
EXAMPLE
void foo() {
int** a; // Violation
}
REPAIR
Instead, declare a class that has
a member variable of the pointer type.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#12
From: 12 Pointers and References - Rec. 48
BENEFITS
Readability. The '?:' operator is difficult to read
and leads to code obfuscation.
EXAMPLE
int main( )
{
return (1 ? 1 : 0); // Violation
};
REPAIR
int main( )
{
if (1)
return 1;
else
return 0;
};
// OK
REFERENCES
Recommended by ParaSoft
NOTES
The rule is enabled only for C++ language.
BENEFITS
The rule improves readability of code.
EXAMPLE
typedef void (*fpt)(void);
typedef void TD_void;
void f1(void);
void f1(void){
}
// Violation
// Violation
// Violation
// Violation
REPAIR
typedef void (*fpt)();
typedef void TD_void;
void f1();
void f1(){
}
// OK
// OK
TD_void foo2(); // OK
// OK
void (*fp1)();
// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Avoiding breaks in the for loop makes your code easier to follow.
EXAMPLE
void func()
{
for (int j = 0; j < 10; j++) {
if (j==5)
{
break;
// Violation
}
break;
// Violation
}
}
REPAIR
void func()
{
for (int j = 0; j < 10; j++) {
while (true)
{
break;
// OK - 'break' in while context
}
}
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Casting pointer to function to pointer to primitive
type can make code error prone.
EXAMPLE
void Foo(char *ptrC)
{
*ptrC = 0;
return;
}
void f()
{
void *ptrV = 0;
void (*funPtr) (char*) = 0;
funPtr = &Foo;
ptrV = (void*)funPtr;
return;
}
// Violation
REPAIR
Remove all function pointer to primitive type pointer casts.
REFERENCES
1. ISO/DIS 26262
point 8.4.4
Storage type modifiers shall be associated with the type, not the variable or the function
[CODSTA-10-3]
DESCRIPTION
This rule checks whether storage type modifiers
are associated with the type, not the variable.
BENEFITS
Improves the readability of code.
EXAMPLE
int static i; // Violation
REPAIR
static char j; // OK
REFERENCES
Motorola Coding Standards R-1
BENEFITS
Rule improves efficiency and prevents error-prone code.
EXAMPLE
#include <assert.h>
void foo( ) {
int i = 0;
assert( i++ != 0 ); // Violation
assert(i=5);
// Violation
assert(false);
// Violation
}
REPAIR
#include <assert.h>
void foo( ) {
int i = 0;
assert(i != 0);
// OK
assert(!"informational message"); // OK
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
BENEFITS
Rule improves readability and maintainability and prevents confusion.
EXAMPLE
void foo() {
int c = 8 << 2;
}
// Violation
REPAIR
Avoid using shift operations.
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.8
From: 18 Portable Code - 18.8 Pointer Arithmetic - Port. Rec. 17
BENEFITS
Prevents confusion of types (e.g., in comparison).
EXAMPLE
int* returnptr();
void foo() {
int* a;
char* b;
if (a == b) {}// Violation
if (returnptr( ) >= b) {}// Violation
if (b < returnptr( )) {}// Violation
}
REPAIR
Do not use pointer arithmetic.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.8
From: 18 Portable Code - 18.8 Pointer Arithmetic - Port. Rec. 18
2. ISO/DIS 26262
point 8.4.4
BENEFITS
The rule prevents undefined behaviours.
EXAMPLE
void foo( const int a, const int* b ) {
int x;
int* y;
(int&) a = x;
// Violation
y = (int*) b;
// Violation
*y = 10;
}
REPAIR
Avoid casting away const.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 13 Type Conversions - Rule 46
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-
Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 94
Do not declare the size of an array when the array is passed into a function as a parameter
[CODSTA-15-2]
DESCRIPTION
This rule detects if the size of an array is declared when the array
is passed into a function as a parameter. Do not declare the
magnitude of a single dimensional array in the argument declaration.
The 'C' language will pass an array argument as a pointer to the first
element in the array.In fact, different invocations of the function
may pass array arguments with different magnitudes. Therefore,
specifying the magnitude of an array in a function argument definition
might complicate software maintenance.
BENEFITS
Prevents potential loss of data.
EXAMPLE
void foo2(int ii[30])
// Violation
{
}
void foo3(char a,int ii[30][30][30]) // Violation
{
}
REPAIR
void foo1(int ii[])
{
}
void foo4(char a,int ii[][30][30])
{
}
REFERENCES
Motorola Coding Standards R-7
// OK
// OK
Do not declare the size of an array when the array is initialized [CODSTA-16-2]
DESCRIPTION
This rule detects if the size of an array is declared when the array
is initialized. When global arrays are initialized in the definition,
their magnitude shall be set by initialization. By allowing the
magnitude of an array to be set automatically during definition,
changes to the number of elements in the initialization list do not
require corresponding changes to the explicit array size.
BENEFITS
Makes code easier to maintain.
EXAMPLE
#define SIZE 4
int tab1[SIZE] = {1,2,3}; // Violation
REPAIR
int tab2[]={1,2,3};
// OK
REFERENCES
Motorola Coding Standards, R-6
Do not compare a pointer to NULL or assign NULL to a pointer; use 0 instead [CODSTA-17-3]
DESCRIPTION
This rule detects code that compares a pointer to NULL or assigns NULL
to a pointer. "Do not compare a pointer to NULL or assign NULL to a
pointer; use 0 instead."
BENEFITS
According to the ANSI-C standard, NULL is defined either as (void*)0 or as
0.
If this definition remains in ANSI-C++, problems may arise.
If NULL is defined to have the type void*, it cannot be assigned an
arbitrary
pointer without an explicit type conversion.
EXAMPLE
#include <stddef.h>
void foo( ) {
int *lp = NULL; // Violation
}
REPAIR
#include <stddef.h>
void foo( ) {
int *lp = 0; // OK
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rule 42
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 175
BENEFITS
Using do statements can lead to errors and confusion.
Using while statements instead of do statements can
make code clearer and help prevent errors.
EXAMPLE
void func( )
{
int i = 0;
do
// Violation
{
i++;
} while ( i < 10);
}
REPAIR
void func( )
{
int i = 0;
while (i < 10)
{
i++;
}
}
// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Using function from ctype.h for char testing makes
code more portable across different character code sets.
EXAMPLE
#include <ctype.h>
void test(char c) {
if( 'a' <= c && c <= 'z') {
}
// Violation
REPAIR
#include <ctype.h>
void test(char c) {
if(islower(c))
{
}
while(isupper(c))
{
}
}
// OK
// OK
REFERENCES
http://www.gnu.org/software/libc/manual/html_node/Character-Handling.html
BENEFITS
Promotes the use of defined constants rather than hard coded values.
EXAMPLE
#include <stddef.h>
#define EOS '\0'
void foo( ) {
char str[30] = "Sample text.";
str[7] = NULL;
}
// Violation
REPAIR
#include <stddef.h>
#define EOS '\0'
void foo( ) {
char str[30] = "Sample text.";
str[7] = EOS;
}
REFERENCES
Motorola Coding Standards G-11
// OK
When using enum, the values of each member should be explicitly declared [CODSTA-21-5]
DESCRIPTION
When using enum, the values of each member should be explicitly declared.
BENEFITS
Explicit declarations of each members values is valuable documentation
when using an emulator, logic analyzer or other debugging device.
EXAMPLE
enum my_enum1
{
a,
// Violation
};
REPAIR
enum my_enum2
{
a = 0 // OK
};
REFERENCES
Motorola Coding Standards G-15
Local variable or parameter names and class member variable or parent class/struct member
variable names shall differ by more than a single character [CODSTA-22-1]
DESCRIPTION
This rule checks that local variable or parameter names and
class member variable or parent class/struct member variable
names differ by more than a single character.
NOTES
Case insensitive check is performed.
Names that are one character in length are skipped.
BENEFITS
Rule improves readability and prevents writing ambiguous code.
EXAMPLE
class Base {
void foo( ) {
float memberF;
// Violation
}
int foo1( );
short foo2( ) {
for( int _var2 = 0; _var2 < 10; _var2++ ) {
}
return Var3;
}
public:
int Member;
float Var1;
float Var2;
short Var3;
};
int Base::foo1( ) {
int _var1 = 6;
return _var1;
}
// Violation
// Violation
// Violation
// Violation
REPAIR
class Base {
void foo( ) {
float fLocal;
// OK
}
int foo1( );
int x;
short foo2( ) {
int y;
// OK
for( int iValue = 0; iValue < 10; iValue++ ) {
}
return Var3;
}
public:
int Member;
float Var1;
float Var2;
short Var3;
};
int Base::foo1( ) {
int iValue = 6;
return iValue;
}
// OK
// OK
REFERENCES
Recommended by ParaSoft
// OK
// OK
BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.
EXAMPLE
int foo(int a, int b) {
if(a > b){
// Violation
return a - b;
}
if(a < b){
return b - a;
}
// Violation
if(a == b)
return 1;
// Violation
REPAIR
int foo(int a, int b) {
if(a > b){
// OK
return a - b;
} else if(a < b){
// OK
return b - a;
} else {
return 1;
}
}
REFERENCES
1. Recommended by ParaSoft
If FALSE is to be defined, and is not already defined, #define FALSE should be 0 [CODSTA-245]
DESCRIPTION
This rule checks whether you defined FALSE as 0.
See also: CODSTA-25
BENEFITS
Any use of FALSE-- other than defining FALSE as 0-- is misleading
and will not be guaranteed to work predictably.
EXAMPLE
#define FALSE 1 // Violation
#undef FALSE
#define FALSE
// Violation
REPAIR
#define FALSE 0 // OK
REFERENCES
http://www.research.att.com/~bs/glossary.html#Gfalse
If FALSE is to be defined, and is not already defined, enum value FALSE should be 0
[CODSTA-25-5]
DESCRIPTION
This rule checks if FALSE is defined as 0.
See also: CODSTA-24, CODSTA-43
BENEFITS
Any use of FALSE-- other than defining FALSE as 0-- is misleading
and will not be guaranteed to work predictably.
EXAMPLE
#ifndef FALSE
typedef enum
{
TRUE = 1,
FALSE = -1
} BOOL ;
#endif
// Violation
REPAIR
#ifndef FALSE
typedef enum
{
TRUE = 1,
FALSE = 0
} BOOL ;
#endif
// OK
REFERENCES
http://www.research.att.com/~bs/glossary.html#Gfalse
NOTES
We excluded using literal constants in initialization.
We also skip usage of 0 or 1 because they are equivalent of true or false.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void boo(int);
int foo( int a[], int b ) {
int e;
int f = 0;
a[5] = 56; // Violation
e= 8;
// Violation
boo(56);
// Violation
return 8; // Violation
}
REPAIR
const int MAX = 8;
// OK
void boo(int);
int foo( float a[], float b ) {
int e;
int f = 0;
// OK
int i = 5;
// OK
a[i] = MAX;
e = MAX;
boo(a[5]);
return MAX;
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151
BENEFITS
In multithread environment using global
variables makes code extremely error prone.
EXAMPLE
struct S {
int a;
}g_struct;
int g_i;
int g_arr[10];
void foo(){
g_i++;
g_struct.a = 10;
g_arr[3] += 2;
}
// Violation
// Violation
// Violation
REPAIR
Do not modify global variables.
REFERENCES
http://charm.cs.uiuc.edu/manuals/html/tcharm/2_1.html
BENEFITS
Prevents form incomplete code.
EXAMPLE
union UNKNOWN
{
};
// Violation
REPAIR
union KNOWN// OK
{
int a;
};
REFERENCES
Recommended by ParaSoft
"#define" or enum constants should be used instead of hard coded values whenever possible
[CODSTA-29-3]
DESCRIPTION
This rule checks whether you are avoiding using hard coded values. Using
#define
or enum constants rather than hard coded values promotes the
maintainability
of 'C' code by creating a localized area for changes.
See also: CODSTA-26
NOTES
Rule active for C code only.
BENEFITS
Readability and maintainability.
EXAMPLE
void foo( ) {
int tabColors[256];
if (tabColors[2] == 1) {
/*...*/
}
}
REPAIR
#define buff 256
#define OK 1
enum color {
RED = 0,
BLUE = 1,
GREEN = 2
/*...*/
};
// Violation
// Violation
void foo( ) {
int tabColors[buff];
// OK
if (tabColors[RED] == OK) { // OK
/*...*/
}
}
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 10 Constants - Rule 37
BENEFITS
Rule prevents non-deterministic behaviour.
EXAMPLE
int* foo1( int x ){
return &x;
// Violation
}
int& foo2( int x ){
return x;
// Violation
}
REPAIR
int foo1( int x ){
return x;
}
// OK
// OK
REFERENCES
Recommended by ParaSoft
NOTES
Rule is limited to primitive types only.
EXCEPTIONS
Explicit type conversions may be used to convert a pointer to a base class
to a pointer of a derived class.
Explicit type conversion must be used to convert an anonymous bit-stream
to an object.
Generally, explicit type conversions are needed for reading an external
representation of an object.
BENEFITS
Rule improves clarity and maintainability of code.
EXAMPLE
void foo( ) {
const int ci = 0;
int i;
i = (int) ci;
// Violation
i = (int) &i;
// Violation
}
REPAIR
Do not use casts.
REFERENCES
Do not write logical expressions of the type if(test) or if(!test) when test is a pointer [CODSTA32-3]
DESCRIPTION
"Do not write logical expressions of the type if(test) or if(!test)
when test is a pointer.(...)
We do not recommend logical tests such as if(pointer)
if pointer is a variable of pointer-type.
The only reason is readability, many programmers find it difficult to read
such code."
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo( ) {
int* ptr;
if (ptr) { // Violation
}
if (!ptr) { // Violation
}
}
REPAIR
void foo( ) {
int* ptr;
if (ptr == 0) { // OK
}
}
REFERENCES
Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rec. 55
Do not use operator ++ or -- in the conditional expression of if, while, or switch [CODSTA-33-3]
DESCRIPTION
Using the operator ++ or -- in the conditional part of if, while or switch
can
make code difficult-to-read and error-prone.
BENEFITS
Makes code more readable.
EXAMPLE
int Foo (int iVar)
{
if (iVar-- && iVar<10)
{
iVar += 10;
}
else
{
iVar -= 10;
}
return iVar;
}
REPAIR
int Foo (int iVar)
{
if (iVar<10) // OK
{
iVar += 10;
}
else
{
iVar -= 10;
}
return iVar;
}
// Violation
REFERENCES
Recommended by ParaSoft
Use a typedef to simplify program syntax when declaring function pointers [CODSTA-34-3]
DESCRIPTION
"Use a typedef to simplify program syntax when declaring function
pointers."
BENEFITS
"Another reason to use typedef is that the readability of the code is
improved.
If pointers to functions are used, the resulting code can be almost
unreadable.
By making a type declaration for the function type, this is avoided."
EXAMPLE
void (*p)();
// Violation
REPAIR
typedef void (*PTF)();
PTF p;
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rec. 49
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 176
BENEFITS
Rule prevents possibility of erroneous code.
EXAMPLE
void foo( ) {
int tag;
switch ( tag ) {// Violation
case 0: {
break;
}
case 1: {
foo( );
break;
}
}
}
REPAIR
void foo( ) {
int tag;
switch ( tag ) {// OK
case 0: {
break;
}
case 1: {
foo( );
break;
}
default: break;
}
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 48
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 194
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,
Do not use a #define that prevents the compiler from checking types except ones used only in
#ifs and #elifs conditions [CODSTA-37-3]
DESCRIPTION
This rule checks whether you use a #define that the compiler cannot check
type.
Using a #define prevents the compiler from checking the type .
See also: MISRA2004-19_7, CODSTA-03, CODSTA-38
NOTES
Rule skips #defines which are used only in #ifs and #elifs conditions.
Rule works only within file scope.
It means that each source and header files are parsed one by one.
BENEFITS
By following this rule, you prevent the compiler from disabling type
checking.
EXAMPLE
#define V1 20
#define V2 1
#if V2
#endif
// Violation
// OK
REPAIR
const int V1 = 20; // OK
#define V2 1
// OK
#if V2
#endif
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
Do not use a #define that prevents the compiler from checking types [CODSTA-38-3]
DESCRIPTION
This rule checks whether you use a #define that the compiler cannot check
type.
Using a #define prevents using unchecked types.
See also: MISRA2004-19_7, CODSTA-03, CODSTA-37
BENEFITS
By following this rule, you prevent the compiler from disabling type
checking.
EXAMPLE
#define MAX_COMPUTERNAME_LENGTH
10
#define MACHINE_NAME_LEN
MAX_COMPUTERNAME_LENGTH + 2
// Violation
REPAIR
const int MAX_COMPUTERNAME_LENGTH = 10;
const int MACHINE_NAME_LEN = MAX_COMPUTERNAME_LENGTH + 2; // OK
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
Avoid internal or external name conflict with a C++ reserved word [CODSTA-39-1]
DESCRIPTION
Internal or external name conflicts with a C++ reserved word will cause
problems
if program is compiled with a C compiler. Most C compilers do not detect
naming
conflicts, and they can lead to unpredictable program behavior.
BENEFITS
Avoid unpredictable program behavior.
EXAMPLE
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
REPAIR
// Avoid using reserved word as variable name
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
void foo1();
*/
void foo1() {}
*/
foo2(void);
/* Violation - there is no 'void' in return type */
foo2(void) {}
/* Violation - there is no 'void' in return type */
foo3(void) {return;} /* Violation - there is no 'void' in return type */
REPAIR
void foo1(void);
/* OK */
void foo1(void) {}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 76
BENEFITS
Avoids improper use of switch.
EXAMPLE
void foo (int i)
{
switch(i)
{
case 0:
break;
default:
break;
}
}
// Violation
REPAIR
void foo (int i)
{
if(i == 0)
{
// ...
} else {
// ...
}
}
REFERENCES
// OK
Recommended by ParaSoft
If TRUE is to be defined, and is not already defined, #define TRUE should be 1 [CODSTA-42-5]
DESCRIPTION
This rule checks whether preprocessor
definition of TRUE is 1. Any other use of TRUE is
misleading and cannot be guaranteed to work
predictably.
See also: CODSTA-43
BENEFITS
Readability and maintainability.
EXAMPLE
#define TRUE 0 // Violation
#undef TRUE
#define TRUE
// Violation
#undef TRUE
REPAIR
#define TRUE 1 // OK
REFERENCES
http://www.research.att.com/~bs/glossary.html#Gtrue
If TRUE is to be defined, and is not already defined, enum value TRUE should be 1 [CODSTA43-5]
DESCRIPTION
This rule checks whether you defined const enum TRUE as 1. Any
other use of TRUE is misleading and cannot be
guaranteed to work predictably.
See also: CODSTA-42, CODSTA-25
BENEFITS
Readability and maintainability.
EXAMPLE
#ifndef TRUE
typedef enum
{
FALSE = 0,
TRUE = 3
} BOOL ;
#endif
// Violation
REPAIR
#ifndef TRUE
typedef enum
{
FALSE = 0,
TRUE = 1
} BOOL ;
#endif
// OK
REFERENCES
http://www.research.att.com/~bs/glossary.html#Gtrue
Local variables and variables of class/parent classes/parent structs should have different
name [CODSTA-44-1]
DESCRIPTION
Rule checks if local variables and variables of class/parent classes/
/parent structs have the same name (case sensitive).
If so, then it reports violation message.
See also: CODSTA-45
BENEFITS
Rule improves readability and prevents writing ambiguous code.
EXAMPLE
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( ) {
float member;
}
short foo2( ) {
for( int var2 = 0; var2 < 10; var2++ ) {
}
return var3;
}
// Violation
// Violation
};
// Violation
REPAIR
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( ) {
float member2;
}
short foo2( ) {
for( int var4 = 0; var4 < 10; var4++ ) {
}
return var3;
}
// OK
// OK
};
class A : public Base {
void foo( ) {
float member2;
}
int foo1( );
};
REFERENCES
Recommended by ParaSoft
// OK
Parameters and variables of class/parent classes/parent structs should have different name
[CODSTA-45-1]
DESCRIPTION
Rule checks if parameters and variables of class/parent classes/
/parent structs have the same name (case sensitive).
If so, then it reports violation message.
See also: CODSTA-44
BENEFITS
Rule improves readability and prevents writing ambiguous code.
EXAMPLE
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( double var3 ) {
float member;
}
// Violation
};
REPAIR
class Base {
public:
int member;
float var1;
float var2;
short var3;
void foo( double var4 ) {
float member;
}
};
// OK
REFERENCES
Recommended by ParaSoft
Use positive logic rather than negative logic whenever practical [CODSTA-46-5]
DESCRIPTION
Use positive logic rather than negative logic whenever practical.
The use of many logical nots "!" within an expression makes
the expression difficult to understand and maintain.
BENEFITS
Makes source code more readable.
EXAMPLE
void foo( int *j)
{
if(j!=0){
// Violation
(*j)++;
}
}
REPAIR
void foo( int *j)
{
if(j==0){
} else {
// OK
(*j)++;
}
}
REFERENCES
Motorola Coding Standards G-13
EXCEPTIONS
This rule applies only to C code. In C++, the keyword struct defines
a type, and no typedefs are necessary, or should be used.
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
struct A {
int i;
};
// Violation - no typedef
struct B {
int i;
};
// Violation - no typedef
REPAIR
typedef struct A {
int i;
} A_t;
struct B {
int i;
};
typedef struct B B_t;
// OK
// OK
REFERENCES
Customer guidelines
The following digraphs will not be used <%, %>, <:, :>, %:, %:%: [CODSTA-48-3]
DESCRIPTION
The following digraphs will not be used <%, %>, <:, :>, %:, %:%:
The use of digraphs listed in this rule can obscure the meaning
of otherwise simple constructs.
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
int a <: 2 :> <: 2 :> = <%<%0,1%>,<%2,3%>%>; // Violation
REPAIR
int a[2][2] = { {0,1}, {2,3} };
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-5-1
Null initialize or increment expressions in for loops will not be used; a while loop will be used
instead [CODSTA-49-3]
DESCRIPTION
Null initialize or increment expressions in for loops
will not be used; a while loop will be used instead.
Rule reports a violation message if 'for' statement
misses init or increment section.
SINCE
v7.1
BENEFITS
A while loop provides a more natural representation.
EXAMPLE
void foo()
{
for(int i=0; i< 10;) // Violation
{
/* ... */
}
int j = 0;
for(; j< 10;)
{
/* ... */
}
}
REPAIR
void foo()
{
int i = 0;
// Violation
while(i< 10)
{
/* ... */
}
// OK
int j = 0;
while(j< 10)
{
/* ... */
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 200
SINCE
v7.1
BENEFITS
Improved readability and maintenance.
EXAMPLE
int i = 0x3fff;
// Violation
REPAIR
int i = 0x3FFF;
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 150
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4
Literal suffixes shall use uppercase rather than lowercase letters [CODSTA-51-2]
DESCRIPTION
Literal suffixes shall use uppercase rather than lowercase letters.
See also: CODSTA-50
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo(long param = 64l) // Violation
{
const long a = 64l; // Violation
}
REPAIR
void foo(long param = 64L) // OK
{
const long a = 64L;
// OK
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4
The initialization expression in a for loop will perform no actions other than to initialize the
value of a single for loop parameter [CODSTA-52-3]
DESCRIPTION
The initialization expression in a for loop will perform no actions other
than
to initialize the value of a single for loop parameter.
Note that the initialization expression may invoke an accessor that
returns
an initial element in a sequence:
for (Iter_type p = c.begin() ; p != c.end() ; ++p) // Good
{
// ...
}
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo()
{
int k = 0;
/* ... */
for(; k>0; k--){}
for(int i=0, k=2; k>0; k--){}
for(int i = k+2-10; k>0; k--){}
for(k--; k>0; k--){}
}
REPAIR
//
//
//
//
Violation
Violation
Violation
Violation
class A
{
public:
int i;
int moo();
};
void foo()
{
int k = 0;
A obj;
/* ... */
for(k=2; k>0; k--){}
for(int i =0; i>0; i--){}
for(k = obj.i; k>0; k--){}
for(k = obj.moo(); k>0; k--){}
}
//
//
//
//
OK
OK
OK
OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 198
The increment expression in a for loop will perform no action other than to change a single
loop parameter to the next value for the loop [CODSTA-53-3]
DESCRIPTION
The increment expression in a for loop will perform no action other
than to change a single loop parameter to the next value for the loop
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo()
{
int k = 0;
for(;k>0; ){}
// Violation
for(int i=0; k>0; k--, i++){} // Violation
for(k--; k>0; k+1){}
// Violation
}
REPAIR
void zoo(){}
class A
{
public:
int i;
};
void foo()
{
int k = 0;
A obj;
for(int i = k+2-10; k>0; zoo()){}
for(k=2; k>0; k--){}
for(int i =0; i>0; i=i-1){}
for(k = obj.i; k>0; k-=1){}
//
//
//
//
OK
OK
OK
OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 199
Every switch statement will have at least two cases and a potential default [CODSTA-54-3]
DESCRIPTION
Every switch statement will have at least two cases and a potential
default.
See also: CODSTA-41, MISRA2004-15_5
SINCE
v7.1
BENEFITS
An if statement provides a more natural representation.
EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}
// Violation
REPAIR
void foo(int i)
{
switch(i)
{
case 1:
break;
case 2:
break;
default:
;
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 196
Enumeration types shall be used instead of integer types (and constants) as case labels
[CODSTA-55-2]
DESCRIPTION
Enumeration types shall be used instead of integer types (and constants)
to
select from a limited series of choices. Rule reports a violation message
if integer types (constants) are used as case labels.
SINCE
v7.1
EXCEPTIONS
This rule is not intended to exclude character constants (e.g. 'A', 'B'
etc.)
from use as case labels.
BENEFITS
Enhances debugging, readability and maintenance.
Note that a compiler flag (if available) should be set to generate a
warning
if all enumerators are not present in a switch statement.
EXAMPLE
void foo(int color)
{
switch(color)
{
case 1:
break;
case 2:
break;
case 3:
break;
// Violation
// Violation
// Violation
default:
break;
}
}
REPAIR
enum color
{
RED = 1,
BLUE = 2,
GREEN = 3
};
void foo(int color)
{
switch(color)
{
case RED:
break;
case BLUE:
break ;
case GREEN:
break;
default:
break;
}
}
// OK
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 148
All 'case' and 'default' labels of 'switch' statement should have an explicit 'break' or a 'return'
statement, or 'fall through' comment [CODSTA-56-3]
DESCRIPTION
All 'case' and 'default' labels of 'switch' statement should have:
- an explicit unconditional 'break' or a 'return' statement or
- at the end a 'fall through' comment containing "fall through" phrase
(checked case insensitive).
SINCE
v7.2
EXCEPTIONS
Rule does not report a violation message for empty labels.
BENEFITS
Rule prevents unpredictable program behaviour.
EXAMPLE
void MyFunction(int i, int j)
{
switch(i)
{
case 1:
// Violation
i++;
case 2:
case 3:
// Violation
i++;
/* wrong comment */
case 4:
// Violation - 'break' and 'return' are nested
if(j > 5){
i--;
break;
} else {
return i;
}
default:
;
}
// Violation
REPAIR
void MyFunction(int i, int j)
{
switch(i)
{
case 1:
// OK
i++;
break;
case 2:
// OK - empty label
case 3:
// OK
i++;
/* fall through */
case 4:
// OK
if(j > 5){
i--;
break;
} else {
return i;
}
break;
default:
// OK
break;
}
}
REFERENCES
Recommended by ParaSoft
SINCE
v7.2
EXCEPTIONS
Rule does not report a violation message if the ';' is placed
in different line than the ')'.
BENEFITS
Rule prevents accidental termination of 'if', 'while', or 'for'
constructs.
EXAMPLE
void foo(int param)
{
if (param);
// Violation
for(;;)
// Violation
while(param); // Violation
{
}
}
REPAIR
void foo(int param)
{
if (param)
{
}
// OK
for(;;)
;
// OK
while(param)
{
// OK
}
}
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule prevents silencing compiler and static analysis tools warnings.
EXAMPLE
int someFunction();
void foo()
{
/* ... */
(void)someFunction();
}
// Violation
REPAIR
int someFunction();
void foo()
{
/* ... */
if(someFunction())
{
/* ... */
} else{
/* ... */
}
}
// OK
REFERENCES
Recommended by ParaSoft
Hardcoded array declarations and 'malloc' calls should not be used [CODSTA-59-4]
DESCRIPTION
Hardcoded calls to malloc and hardcoded array declarations decrease
readability and maintainability of code. Macros should be used instead
of these calls, so that all instances of hardcoded size could be changed
by a single code update.
SINCE
v7.2
EXCEPTIONS
Expressions such as [ARRAY_SIZE + 1] are allowed
in array declarations for type char.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
#include <stdlib.h>
void myFunction()
{
int array[10];
malloc(20);
}
REPAIR
#include <stdlib.h>
#define ARRAY_SIZE 10
#define MALLOC_SIZE 20
// Violation
// Violation
void myFunction()
{
int array[ARRAY_SIZE];
malloc(MALLOC_SIZE);
}
REFERENCES
Recommended by ParaSoft
// OK
// OK
Avoid comparing values with TRUE macro/enum constant using equality operators ("==", "!=")
[CODSTA-60-3]
DESCRIPTION
Avoid checking "== TRUE" and "!= TRUE".
Such checks should be avoided because true can have many possible values
(any non-zero value can be true), but the TRUE macro or enum constant is
defined, for example, as 1.
SINCE
v7.2
BENEFITS
Checking "== TRUE" or "!= TRUE", can be dangerous if
e.g., variable is true but not 1.
EXAMPLE
#define TRUE 1
void foo()
{
int a = 10;
if(a==TRUE)
{
/* ... */
}
}
REPAIR
#define TRUE 1
void foo()
{
// Violation
int a = 10;
if(a)
{
/* ... */
// OK
}
}
REFERENCES
Recommended by ParaSoft
SINCE
v7.2
EXCEPTIONS
"If the condition of a switch statement is of type enum, and all the
enumerators are listed in case labels, then the default-clause is not
required
as the rules associated with enums are intended to ensure that the enum
cannot
be assigned values outside of its set of enumerators."
BENEFITS
Rule improves readability and maintainability of 'switch' statement.
EXAMPLE
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
// Violation
}
switch( colour )
{
case RED:
break;
case GREEN:
break;
// Violation
}
}
REPAIR
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
default:
break;
}
switch( colour )
{
case RED:
break;
case BLUE:
break;
case GREEN:
break;
}
}
// OK
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
A cast shall not convert a pointer to a function to any other pointer type, including a pointer to
function type [CODSTA-62-3]
DESCRIPTION
"Conversion of a function pointer to a non-function pointer type causes
undefined behaviour. Undefined behaviour may arise if a function call is
made using a pointer that is the result of a function pointer conversion."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
void f ( int )
{
reinterpret_cast< void (*)( ) >( &f ); // Violation
reinterpret_cast< void * >( &f );
// Violation
}
REPAIR
Do not cast a pointer to a function to any other pointer type.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-6
Bitwise operators shall only be applied to operands of unsigned underlying type [CODSTA-633]
DESCRIPTION
"Bitwise operations (~, <<, <<=, >>, >>=, &, &=, ^, ^=, | and |=) are not
normally meaningful on signed integers or enumeration constants.
Additionally, an implementation-defined result is obtained if a right
shift
is applied to a negative value."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & s1;
// Violation
REPAIR
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & (unsigned short)s1;
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-21
SINCE
v7.2
BENEFITS
Prevents unpredictable program behaviour.
EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
// Violation
// Violation
{
i = 5;
break;
}
case 2 :
{
// Violation
i = 3;
}
default:
i = 8;
// Violation
}
}
REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
throw;
}
}
// OK
// OK
// OK
// OK - empty case
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
An object with integer type or pointer to void type shall not be converted to an object with
pointer type [CODSTA-65-3]
DESCRIPTION
"An object with integer type or pointer to void type shall
not be converted to an object with pointer type"
SINCE
v7.2
BENEFITS
In general, converting from an integral type or a pointer to void type
to a pointer to an object leads to unspecified behaviour.
EXAMPLE
struct S
{
int i;
int j;
};
void f ( void * v, int i )
{
S * s1 = reinterpret_cast< S * >( v ); // Violation
S * s2 = reinterpret_cast< S * >( i ); // Violation
}
REPAIR
Do not cast an object with integer type or pointer to void type
to an object with pointer type
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-8
Non-constant operands to a binary bitwise operator shall have the same underlying type
[CODSTA-66-3]
DESCRIPTION
"Non-constant operands to a binary bitwise operator shall have the same
underlying type. The term 'underlying type' is defined as describing
the type that would be obtained from evaluating an expression if it were
not for the effects of integral promotion."
SINCE
v7.2
BENEFITS
"Using operands of the same underlying type documents that it is the
number
of bits in the final (promoted and balanced) type that are used, and not
the number of bits in the original types of the expression."
EXAMPLE
void foo()
{
unsigned char mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// Violation
}
REPAIR
void foo()
{
unsigned short mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-20
The types used for an object, a function return type, or a function parameter shall be tokenfor-token identical in all declarations and re-declarations [CODSTA-67-3]
DESCRIPTION
"If a re-declaration has compatible types but not types which are
token-for-token identical, it may not be clear to which declaration
that re-declaration refers."
SINCE
v7.2
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
typedef int INT;
INT i;
extern int i;
// Violation
REPAIR
typedef int INT;
INT i;
extern INT i;
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-9-1
A "U" suffix shall be applied to all octal or hexadecimal integer literals of unsigned type
[CODSTA-68-3]
DESCRIPTION
"The type of an integer is dependent on a complex combination of factors
including:
- The magnitude of the constant;
- The implemented sizes of the integer types;
- The presence of any suffixes;
- The number base in which the value is expressed.
For example, the value 0x8000 is of type unsigned int in a 16-bit
environment,
but of type (signed) int in a 32-bit environment. If an overload set
includes
candidates for an unsigned int and an int, then the overload that would be
matched by 0x8000 is therefore dependent on the implemented integer size.
Adding a "U" suffix to the value specifies that it is unsigned."
SINCE
v7.2
BENEFITS
Rule improves portability and prevents undefined behaviour.
EXAMPLE
unsigned long var = 02;
// Violation
REPAIR
unsigned long var = 02U; // OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Expressions with type (plain) char and wchar_t shall not be used as operands to built-in
operators other than =, ==, != and the unary & operator [CODSTA-69-3]
DESCRIPTION
"Expressions with type (plain) char and wchar_t shall not be used as
operands
to built-in operators other than the assignment operator =, the equality
operators == and !=, and the unary & operator."
SINCE
v7.2
EXCEPTIONS
Exceptionally, the following operators may be used if the associated
restriction is observed:
- The binary + operator may be used to add an integral
value in the range 0 to 9 to 0;
- The binary operator may be used to subtract character 0;
- The relational operators <, <=, >, >= may be used to determine
if a character (or wide character) represents a digit.
(Rule does not report a violation if a character constant is compared
with a variable of type plain char)
BENEFITS
"Manipulation of character data may generate results that are contrary
to developer expectations."
EXAMPLE
void foo()
{
char ch = 't';
// OK
if ( ( ch >= 'a' ) && ( ch <= 'z' ) ) // Violation
{
//...
}
REPAIR
void foo()
{
char ch = 't';
// OK
if ( ch == 't' ) // OK
{
//...
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-3
Expressions with type enum shall not be used as operands to built-in operators other than [ ],
=, ==, !=, <, <=, >, >=, and the unary & operator [CODSTA-70-3]
DESCRIPTION
"Expressions with type enum shall not be used as operands to built-in
operators other than the subscript operator [ ], the assignment operator
=,
the equality operators == and !=, the unary & operator, and the relational
operators <, <=, >, >=."
SINCE
v7.2
BENEFITS
"Enumerations have implementation-defined representation
and so should not be used in arithmetic contexts."
EXAMPLE
/* Examples of incorrect code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 + COLOUR_1 ) == colour ){} // Violation
}
REPAIR
/* Examples of correct code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 < colour) && (COLOUR_3 > colour ) ){} // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-2
Named bit-fields with signed integer type shall have a length of more than one bit [CODSTA71-3]
DESCRIPTION
"Named bit-fields with signed integer type shall have a length of more
than one
bit. The values which may be represented by a bit-field of length one may
not
meet developer expectations. Anonymous signed bit-fields of any length are
allowed."
SINCE
v7.2
NOTES
Rule reports violations only for explicitly signed types
BENEFITS
Rule prevents the potential pitfalls and erroneous code.
EXAMPLE
struct MyStruct
{
signed int si01 : 1;
signed int si02 : 1;
};
// Violation
// Violation
REPAIR
struct MyStruct
{
signed int si01 : 2;
signed int : 1;
};
// OK
// OK
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-4
Assembler instructions shall only be introduced using the asm declaration [CODSTA-73-3]
DESCRIPTION
"The asm declaration is available to all C++ implementations, allowing
a consistent mechanism to be used. However, the parameters to asm are
still implementation-defined."
Rule reports a violation if '#pragma asm', '#pragma endasm' or an
assembler instruction that form is different than "asm" is found.
SINCE
v7.2
BENEFITS
Rule improves consistency of the code.
EXAMPLE
void foo()
{
#pragma asm
"NOP";
#pragma endasm
}
// Violation
// Violation
REPAIR
void foo()
{
asm ( "NOP" ); // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-4-2
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
enum Color{RED, BLUE, BLACK};
struct S
{
Color n : 2;
/* ... */
};
// Violation
REPAIR
struct S
{
unsigned int n: 2 // OK
/* ... */
};
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-3
Bit-fields shall be either bool type or an explicitly unsigned or signed integral type [CODSTA75-3]
DESCRIPTION
"Bit-fields shall be either bool type or an explicitly unsigned or signed
integral type Using int is implementation-defined because bit-fields of
type
int can be either signed or unsigned. The use of wchar_t as a bit-field
type
is prohibited as ISO/IEC 14882:2003 does not explicitly define the
underlying
representation as signed or unsigned."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
/* Examples of incorrect code */
struct S
{
char c : 2;
// Violation
short f : 3;
// Violation
int : 0;
// Violation
};
REPAIR
/* Examples of correct code */
struct S
{
unsigned char c : 2;
// OK
signed short f : 3;
// OK
unsigned int : 0;
// OK
bool b : 4
// OK
};
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-2
The identifier main shall not be used for a function other than the global function main
[CODSTA-76-3]
DESCRIPTION
"main (or its equivalent) is usually the entry point to the program and is
the
only identifier which must be in the global namespace. The use of main for
other functions may not meet developer expectations."
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
namespace
{
int main ( ){} // Violation
}
REPAIR
int main ( ){}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-2
The goto statement shall jump to a label declared later in the same function body [CODSTA77-3]
DESCRIPTION
"Unconstrained use of goto can lead to programs that are extremely
difficult
to comprehend, analyse and, for C++, can also lead to the program
exhibiting
unspecified behaviour. However, in many cases a total ban on goto requires
the introduction of flags to ensure correct control flow, and it is
possible
that these flags may themselves be less transparent than the goto they
replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. "Back" jumps are
prohibited
as they can be used to create iterations without using the well-defined
iteration statements supplied by the core language."
SINCE
v7.2
BENEFITS
Prevents unspecified behaviour.
EXAMPLE
void foo(int j)
{
L1:
++j;
goto L1; // Violation - jumps backward
++j;
}
REPAIR
void foo(int j)
{
++j;
goto L1; // OK ++j;
L1:
}
jumps forward
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-2
Any label referenced by a goto statement shall be declared in the same block, or in a block
enclosing the goto statement [CODSTA-78-3]
DESCRIPTION
"Any label referenced by a goto statement shall be declared in the same
block,
or in a block enclosing the goto statement. Unconstrained use of goto can
lead to programs that are extremely difficult to comprehend, analyse and,
for C++, can also lead to the program exhibiting unspecified behaviour.
However, in many cases a total ban on goto requires the introduction of
flags to ensure correct control flow, and it is possible that these flags
may themselves be less transparent than the goto they replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. Jumping in to nested
blocks is
prohibited as it may lead to complex flow graphs."
SINCE
v7.2
BENEFITS
Prevents unspecified behaviour.
EXAMPLE
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
L1: // Violation
j;
}
}
REPAIR
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
}
L1: // OK
j;
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-1
For any iteration statement there shall be no more than one break or goto statement used for
loop termination [CODSTA-79-3]
DESCRIPTION
"For any iteration statement there shall be no more than one break or goto
statement used for loop termination."
SINCE
v7.2
BENEFITS
"Restricting the number of exits from a loop is done in the interests of
good
structured programming. One break or goto statement is acceptable in a
loop
since this allows, for example, for dual outcome loops or optimal coding."
EXAMPLE
void foo( ) {
int a;
for (a = 0; a < 10; a++) { // Violation
if (a == 5) {
break;
}
if (a == 7) {
break;
}
}
}
REPAIR
void foo( ) {
int a;
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-4
The continue statement shall only be used within a well formed for loop [CODSTA-80-3]
DESCRIPTION
"Over-use of the continue statement can lead to unnecessary complexity
within
the code. This complexity may impede effective testing as extra logic must
be
tested. The required testing may not be achievable due to control flow
dependencies."
SINCE
v7.2
EXCEPTIONS
Rule does not report a violation if the 'continue' is used within 'for'
loop.
BENEFITS
Rule eliminates unnecessary complexity within the code.
EXAMPLE
void foo()
{
int x = 0;
int y;
y = 10;
while(x < y)
{
x++;
/* ... */
continue;
}
// Violation
REPAIR
Do not use 'continue' statement outside 'for' loop.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-3
If a function has internal linkage then all redeclarations shall include the static storage class
specifier [CODSTA-81-3]
DESCRIPTION
"If the declaration of a function includes the static storage class
specifier,
then it has internal linkage. A re-declaration of such a function is not
required to have the static keyword, but it will still have internal
linkage.
However, this is implicit and may not be obvious to a developer. It is
therefore
good practice to apply the static keyword consistently so that the linkage
is explicitly stated."
See also: MISRA2004-8_11
SINCE
v7.2
BENEFITS
Rule improves good programming style and readability.
EXAMPLE
static void f1 ( );
void f1 ( ) { }
// Violation
REPAIR
static void f1 ( );
static void f1 ( ) { }
// OK
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-3-2
SINCE
v7.3
NOTES
The rule does not check called functions - if there's a termination point
in a function called from within the loop, which is used to stop the loop,
the rule will still report a violation.
The rule does not check if the termination point is reachable (e.g.
'break'
inside of an 'if' statement is considered to be valid regardless of the
'if'
condition).
The rule does only limited checking of 'catch' handlers.
BENEFITS
Finds possible infinite loops that could result in unwanted program
termination,
resource exhaustion or computer "freezing".
EXAMPLE
void foo(char *s) {
for (;;) {
switch (*s++) {
case 'a': continue;
case '\0': break;
}
}
while(true) {
if (!s) {
// return;
}
++s;
}
do {
char * ptr = s;
for(; ptr; ++ptr) {
if (!*ptr) {
goto END_LOOP;
}
}
END_LOOP:
} while(1);
}
REPAIR
void foo(char *s) {
for (;;) {
switch (*s++) {
case 'a': continue;
case '\0': break;
}
break;
}
while(true) {
if (!s) {
return;
}
++s;
}
do {
// OK
// OK
// OK
char * ptr = s;
for(; ptr; ++ptr) {
if (!*ptr) {
goto END_LOOP;
}
}
} while(1);
END_LOOP:
}
REFERENCES
Recommended by ParaSoft
SINCE
v7.3
BENEFITS
Rule prevents writing endless loops.
EXAMPLE
void foo(int p){
int i = 0;
while(i == 5){
i = i + 2;
}
while(i < p){
i++;
}
while(i < 7){
loop
// ...
}
REPAIR
void foo(const int p){
int i = 0;
while(i < 5){
i = i + 2;
}
// OK
// OK
// OK
// OK
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 2
SINCE
v7.3
NOTES
The rule does not check called functions - if there's a termination point
in a function called from within the loop, which is used to stop the loop,
the rule won't report a violation.
BENEFITS
The rule prevents unexpected termination of loop that can not terminate.
EXAMPLE
void foo(){
for(;;){
// code
break;
}
// Violation
while(1){
// code
return;
}
// Violation
REPAIR
void foo(){
for(;;){
// code
}
while(1){
// code
}
// OK
// OK
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 2
SINCE
v7.3
NOTES
The rule assumes that the parameter is validated if it is used inside
condition of statements: if, switch or ternary operator.
BENEFITS
The rule prevents use incorrect value of parameter.
EXAMPLE
int foo3(int p, int q){
p++;
q++;
return p + q;
}
// Violation
REPAIR
int foo4(int p, int q){
if(p == 0 || q == 0){
return 0;
}
p++;
q++;
return p + q;
// OK
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 7
SINCE
v7.3
BENEFITS
"Pointers are easily misused, even by experienced programmers. They can
make it
hard to follow or analyze the flow of data in a program, especially by
tool-based
static analyzers."
EXAMPLE
void foo(){
int** p;
int** q;
int i;
**p = 1; // Violation
i = **q; // Violation
}
REPAIR
Do not use more than one level of dereferencing.
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 9
SINCE
v7.3
BENEFITS
The rule improves readability of code and causes that the code can be
easier
checked by static analyzers.
EXAMPLE
typedef void (*FP)();
extern FP x[];
/* Violation - variable x */
void foo1(FP * y) {
/* Violation - param x */
int (*z)(void) = 0;
/* Violation - variable z */
foo1(y);
/* OK - usage is ignored */
}
void foo2(FP) {}
/* OK - unnamed parameter ignored */
void foo3(FP p);
/* OK - function declarations are ignored */
REPAIR
Do not declare pointers to functions.
REFERENCES
The declaration should not contain more than one level of pointer indirection [CODSTA-89-3]
DESCRIPTION
Use of more than one level of pointer indirection can seriously impair
the ability to understand the behaviour of the code, and should therefore
be avoided.
SINCE
v7.3
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int** INTPTR; /* Violation */
int** ptr;
/* Violation */
int* a[];
/* Violation */
struct S{
int** s;
/* Violation */
};
struct S** ps;
int** foo();
int(**pfunc1)();
int**(*pfunc2)();
void fun( int** par,
INTPTR par_t
)
{
int* a[10];
/*
int ** ptr;
INTPTR ptr_t = 0;
}
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
Violation */
/* Violation */
/* Violation */
REPAIR
Do not declare more than one level of pointer indirection.
REFERENCES
1. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 9
2. ISO/DIS 26262
point 8.4.4
SINCE
v7.3
EXCEPTIONS
"Where an expression consists of either a sequence of only logical '&&'
or a sequence of only logical '||', extra parentheses are not required.
BENEFITS
"The effect of this rule is to require that operands are appropriately
parenthesized."
EXAMPLE
int foo( int x, int y, int z )
{
if ( x || y && z );
// Violation
if ( x && !y );
// Violation
return 0;
}
REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
if ( x && ( !y ) );
// OK
// OK
return 0;
}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-1
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 158
SINCE
v7.3
EXAMPLE
int foo(int i)
{
if (i == 0) {
return 0;
/* Violation */
} else if (i == 1) {
return 1;
/* Violation */
} else {
return 2;
/* Violation */
}
}
void foo2(int* a)
{
if (a == 0) {
return; /* Violation - second exit point at the end of function */
}
*a = 10;
}
REPAIR
int foo(int i)
{
int result = 0;
if (i == 0) {
result = 0;
} else if (i == 1) {
result
} else
result
}
return
= 1;
{
= 2;
result;
/* OK */
}
void foo2(int* a)
{
if (a != 0) {
*a = 10;
}
}
/* OK */
REFERENCES
1. HIS Source Code Metriken, version 1.3.1
Metrik "RETURN"
2. ISO/DIS 26262
point 8.4.4
The names of standard library macros and objects shall not be reused [CODSTA-92-3]
DESCRIPTION
"Where the developer uses new versions of standard library macros or
objects
(e.g. to enhance functionality or add checks of input values), the
modified
macro or object shall have a new name.
This is to avoid any confusion as to whether a standard macro or object,
or a modified version of them, is being used."
Rule checks if the following reserved names are used:
- macro and typedef names from C standard library headers: assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- identifiers that begin with the underscore character
See also: NAMING-33, MISRA2004-20_2, CODSTA-93
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#define NULL ( a > b )
#define _NULL ( a > b )
// Violation
// Violation
REPAIR
#define MY_NULL ( a > b ) // OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-2
BENEFITS
Rule prevents undefined behaviour.
DRAWBACKS
It is not possible in static analysis to check if the functionality is
consistent
with those of the original. So, rule reports violations on all declared
functions
which names are reserved. The user should himself check if the modified
function
has the same functionality and could overload a function from standard
library.
Rule also does not have exception that permits overloading functions with
// Violation
REPAIR
int my_printf ( int a, int b )
{
return ( ( a > b ) ? a : b );
}
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v9.0
BENEFITS
The rule prevents memory leaks, dereferencing a null pointers,
buffer overflows, memory corruptions and undefined behaviours.
EXAMPLE
typedef int* INT_P; /* OK - no violation on typedef */
INT_P x;
/* Violation */
int* foo();
/* Violation */
void (*FP)();
/* Violation */
void bar(int*)
/* Violation */
{
int tab[10];
/* Violation */
int *tab1[10];
/* Violation */
}
REPAIR
Pointers and arrays should not be used.
REFERENCES
Recommended by ParaSoft
SINCE
v9.0
BENEFITS
The rule prevents memory leaks, dereferencing a null pointers,
buffer overflows, memory corruptions and undefined behaviours.
EXAMPLE
typedef int* INT_P; /* OK - no violation on typedef */
INT_P x;
/* Violation */
int* foo();
/* Violation */
void (*FP)();
/* Violation */
void bar(int*)
/* Violation */
{
int tab[10];
/* OK - no violation on simple array */
int *tab1[10];
/* Violation */
}
REPAIR
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]
BENEFITS
Rule improves readability and maintainability. If the characters // are
consistently used for writing comments, then the combination /* */ may be
used
to make comments out of entire sections of code during the development and
debugging phases.
EXAMPLE
/* Violation */
REPAIR
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 9
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 126
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
// Violation - no copyright information
REPAIR
// Copyright
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 5
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133
NOTES
C and C++ style comments are allowed.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
// No comment "File:"
REPAIR
// File: <short description of the file>
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo1();
// Violation
REPAIR
// Comment with description for the function.
void foo1();
// Comment with description for the function.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 134
SINCE
v7.1
NOTES
Rule checks only declarations of local and global variables.
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo()
{
int var1;
// Violation
int var2;
// Violation
}
REPAIR
void foo()
{
int var1; // comment - OK
// comment - OK
int var2;
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
typedef int int32;
// Violation
REPAIR
typedef int int32; // OK - comment
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
enum {
ENUM1 = 2,
// Violation
};
REPAIR
enum {
ENUM1 = 2, // OK - comment
};
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
struct S
{
char* c;
// Violation
};
REPAIR
struct S
{
char* c; // comment - OK
};
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
SINCE
v7.2
NOTES
Rule assumes that the usage of assembler is documented if there is
a comment in the same line as 'asm' instruction or in line directly
before 'asm' instruction.
BENEFITS
Rule improves readability of code.
EXAMPLE
// Violation in line with 'asm' instruction
void foo( void )
{
asm ( "NOP" );
}
REPAIR
void foo( void )
{
// OK - comment before 'asm' instruction
asm ( "NOP" );
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-4-1
SINCE
v7.2
BENEFITS
"The safe use of floating-point arithmetic requires a high level of
numerical
analysis skills and indepth knowledge of the compiler and target
hardware."
EXAMPLE
// Violation in line: double d = d1 + d2;
double add(double d1, double d2)
{
double d = d1 + d2;
}
REPAIR
double add(double d1, double d2)
{
double d = d1 + d2; // OK - floating point arithmetic
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-4-2
EXCEPT
Exceptions
RULES
Never allow an exception to be thrown from a destructor, deallocation, and
swap [EXCEPT-01-1]
Throw by value, catch by reference [EXCEPT-02-1]
Do not throw from within destructor [EXCEPT-03-1]
All exceptions should be rethrown or logged with standard logger [EXCEPT04-2]
C++ exceptions shall not be used (i.e. throw, catch and try shall not be
used.) [EXCEPT-05-2]
There should be at least one exception handler to catch all otherwise
unhandled exceptions [EXCEPT-06-3]
An empty throw (throw;) shall only be used in the compound-statement of a
catch handler [EXCEPT-07-3]
Exceptions shall be raised only after start-up and before termination of
the program [EXCEPT-08-3]
An exception object should not have pointer type [EXCEPT-09-3]
Control shall not be transferred into a try or catch block using a goto or
a switch statement [EXCEPT-10-3]
The assignment-expression of a throw statement shall not itself cause an
exception to be thrown [EXCEPT-11-1]
NULL shall not be thrown explicitly [EXCEPT-12-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point [EXCEPT13-3]
Where a function's declaration includes an exception-specification, the
function shall only be capable of throwing exceptions of the indicated
type(s) [EXCEPT-14-3]
A class type exception shall always be caught by reference [EXCEPT-15-3]
Handlers of a function-try-block implementation of a class constructor or
destructor shall not reference nonstatic members from this class or its
bases [EXCEPT-16-3]
Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases, the
handlers shall be ordered most-derived to base class [EXCEPT-17-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point [EXCEPT18-3]
Never allow an exception to be thrown from a destructor, deallocation, and swap [EXCEPT-011]
DESCRIPTION
"Never allow an error to be reported from a destructor, a resource
deallocation
function (e.g., operator delete), or a swap function. These are key
functions
that must not fail because they are necessary for the two key operations
in transactional programming: to back out work if problems are encountered
during processing, and to commit work if no problems occur."
The rule reports a violation if from a destructor, an operator delete
or a swap function is thrown an exception or is called a function
that can throw exceptions.
See also: EXCEPT-03
NOTES
Function can not throw any exceptions if has external 'C' linkage
or in a declaration uses an empty exception specification throw().
BENEFITS
Rule prevents propagation of exceptions out of the destructor,
operator delete and swap function.
EXAMPLE
class Exceptions{};
class A{
A();
~A();
void operator delete(void*);
};
A::~A(){
throw Exceptions();
}
// Violation
// Violation
class B {
public:
B();
~B();
void operator delete(void*);
void foo();
// can throw exceptions
static void soo(); // can throw exceptions
};
B::~B(){
foo();
}
// Violation
// Violation
REPAIR
class A{
A();
~A();
void operator delete(void*);
void foo() throw();
// can not throw exceptions
static void soo() throw(); // can not throw exceptions
};
A::~A(){
foo();
}
// OK
// OK
class B {
public:
B();
~B();
// OK
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 51
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 8
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Prevents memory management problems and preserves polymorphism
of the rethrown object.
EXAMPLE
class Exception {
public:
Exception( char* );
};
bool sanityObserved();
void restoreSanity();
void foo_Violation() {
Exception *exp = new Exception("error
if (!sanityObserved()) {
throw exp;
//
}
try {
restoreSanity();
}
catch(Exception* newException) {
//
throw newException;
//
argument
}
}
message");
Violation - throwing a pointer
REPAIR
class Exception {
public:
Exception( char* );
};
bool sanityObserved();
void restoreSanity();
void foo_OK() {
Exception exp("error message");
if (!sanityObserved()) {
throw exp;
}
try {
restoreSanity();
}
catch(Exception& newException)
{
throw;
}
}
// OK
// OK
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Error Handling and Exceptions", Rule 73
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Prevents throwing from within a destructor. It may lead to memory leaks
and improper object destruction.
EXAMPLE
class Foo {
public:
Foo( ) { }
~Foo( ) {
throw;
}
};
// Violation
REPAIR
class Exception {};
class Foo {
public:
Foo( ) { }
~Foo( ) {
try {
// OK
} catch (Exception& e) {
// caught all exceptions
}
}
};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
EXCEPTIONS
If an exception is rethrown and could be logged somewhere else, then the
rule
does not report violation.
BENEFITS
An exception is an indication of an abnormal condition during the
application
runtime. When debugging abnormal conditions from the security standpoint,
it is critical to have a proper log of suspicious events.
This rule enforces that proper logging is performed for such exceptions.
EXAMPLE
// example of incorrect code
class Exception { };
void x();
void foo1() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // Violation - no logging
return;
}
}
REPAIR
// examples of correct code
#include <iostream>
class Exception{};
void x();
void log(char* msg); // error logging procedure
void foo1() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
std::cerr << "Error";
return;
}
catch (int * e) { // OK
std::cout << "Error";
return;
}
catch (float e) { // OK
std::clog << "Error";
return;
}
}
void foo2() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
log("Error");
}
}
void foo3() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
throw;
}
}
class MyException { };
void foo4() {
try {
x(); // might throw Exception
}
catch (const Exception& e) { // OK
throw MyException();
}
}
REFERENCES
1. http://cwe.mitre.org/data/definitions/391.html
2. http://freshsources.com/HTML/12.07/ALLISON/ALLISON.HTM
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
C++ exceptions shall not be used (i.e. throw, catch and try shall not be used.) [EXCEPT-05-2]
DESCRIPTION
Do not use C++ exceptions.
SINCE
v7.1
BENEFITS
Rule improves portability of the code.
EXAMPLE
#include <iostream>
using namespace std;
int main()
{
char *buf;
try
// Violation
{
buf = new char[512];
if( buf == 0 )
throw "Memory allocation failure!"; // Violation
}
catch( char * str )
// Violation
{
cout << "Exception raised: " << str << '\n';
}
// ...
return 0;
}
REPAIR
#include <iostream>
// OK
return 0;
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.27 Fault Handling, AV Rule 208
There should be at least one exception handler to catch all otherwise unhandled exceptions
[EXCEPT-06-3]
DESCRIPTION
"If a program throws an unhandled exception it terminates
in an implementation-defined manner. In particular, it is
implementation-defined whether the call stack is unwound, before
termination,
so the destructors of any automatic objects may or may not be executed.
By enforcing the provision of a "last-ditch catch-all", the developer can
ensure that the program terminates in a consistent manner."
Rule checks if outermost statement of the 'main' function is a try
statement
with catch-all handler.
SINCE
v7.2
NOTES
Rule check if a try statement with catch-all handler is implemented
directly
in 'main' function. Statements which are implemented in functions that are
called from 'main' function are not detected.
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
class Exception{};
int main( )
{
try // Violation
{
// ...
}
catch ( Exception e )
{
// ...
}
return 0;
}
REPAIR
class Exception{};
int main( )
{
try // OK
{
// ...
}
catch ( Exception e )
{
// ...
}
catch ( ... )
{
// ...
}
return 0;
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-2
2. http://cwe.mitre.org/data/definitions/391.html
An empty throw (throw;) shall only be used in the compound-statement of a catch handler
[EXCEPT-07-3]
DESCRIPTION
"An empty throw re-throws the temporary object that represents an
exception.
Its use is intended to enable the handling of an exception to be split
across
two or more handlers.
However, syntactically, there is nothing to prevent throw; being used
outside
a catch handler, where there is no exception object to re-throw. This may
lead
to an implementation-defined program termination."
SINCE
v7.2
BENEFITS
Rule prevents implementation-defined behaviour.
EXAMPLE
class Exception{};
void foo(int a)
{
Exception E;
if(a)
{
throw;
// Violation
}
}
REPAIR
class Exception{};
void foo(int a)
{
Exception E;
if(a)
{
throw E;
}
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Exceptions shall be raised only after start-up and before termination of the program [EXCEPT08-3]
DESCRIPTION
"Before the program starts executing the body of main, it is in a start-up
phase, constructing and initializing static objects. Similarly, after main
has
returned, it is in a termination phase where static objects are being
destroyed. If an exception is thrown in either of these phases it leads to
the
program being terminated in an implementation-defined manner."
SINCE
v7.2
NOTES
Rule checks only one level of nested function calls.
BENEFITS
"Throwing an exception during start-up or termination results in the
program
being terminated in an implementation-defined manner."
EXAMPLE
class C
{
public:
C ( )
{
throw ( 0 ); // Violation thrown before main starts
}
~C ( )
{
throw ( 0 ); // Violation thrown after main exits
}
};
C c;
int main( ... )
{
// ...
}
REPAIR
Exceptions should not be throwing during start-up or termination phase.
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Prevents memory management problems
EXAMPLE
typedef short int16_t;
class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( &a1 ); // Violation pointer type thrown
}
else
{
throw ( a2 ); // Violation pointer type thrown
}
}
REPAIR
typedef short int16_t;
class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( a1 ); // OK
}
else
{
throw ( *a2 ); // OK
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. ISO/DIS 26262
point 8.4.4
Control shall not be transferred into a try or catch block using a goto or a switch statement
[EXCEPT-10-3]
DESCRIPTION
"A program is ill-formed if control is transferred into a try or catch
block
using a goto or switch statement; however, not all compilers issue
a diagnostic message."
SINCE
v7.2
BENEFITS
Rule detects errors not reported by all compilers
EXAMPLE
/* The code is compilable with MSVC 6.0 */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
try
{
Label_10: // Violation
case 2:
// Violation
break;
}
catch ( Exception e )
{
}
}
REPAIR
/* The example of correct code */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
// OK
try
{
// ...
}
catch ( Exception e )
{
}
case 2:
// OK
break;
}
Label_10:
// OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule improves readability of code
EXAMPLE
class E
{
public:
E ( )
{
throw 10;
}
};
int foo1()
{
try
{
if ( 0 )
{
throw E ( ); // Violation
}
}
catch(...)
{
}
}
REPAIR
class E
{
public:
E ( ){ }
};
int foo()
{
try
{
if ( 0 )
{
throw E ( ); // OK
}
}
catch(...)
{
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
#define NULL 0
void foo()
{
try
{
throw ( NULL ); // Violation
}
catch ( int i )
// NULL exception handled here
{
// ...
}
}
REPAIR
#define NULL 0
void foo()
{
try
{
throw ( 0 ); // OK
}
catch ( int i ) // NULL exception handled here
{
// ...
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [EXCEPT-13-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown from body
of function 'main' or from body of function that does not have any
exception
on an exception specification list.
see also: EXCEPT-18
SINCE
v7.2
NOTES
Rule checks only one level of nested function calls.
BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."
EXAMPLE
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // Violation
}
}
catch ( A const & )
{
}
}
REPAIR
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // OK
}
}
catch ( A const & )
{
}
catch ( B const & )
{
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
NOTES
Rule checks only two levels of nested function calls
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception )
{
foo ( );
}
// Violation
REPAIR
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception, int ) // OK
{
foo ( );
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
"If the exception is caught by reference, slicing does not occur."
EXAMPLE
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase b ) // Violation - derived type objects will be
// caught as the base type
{
}
}
REPAIR
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase &b ) // OK - exceptions caught by reference
{
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
"The effect of accessing a non-static member of a class or a base class in
the
handler (i.e. the catch part) of a function-try-block of a class
constructor/destructor is undefined. For example, if a memory allocation
exception is thrown during creation of the object, the object will not
exist
when the handler attempts to access its members. Conversely, in the
destructor,
the object may have been successfully destroyed before the exception is
handled, so again will not be available to the handler. By contrast, the
lifetime of a static member is greater than that of the object itself, so
the
static member is guaranteed to exist when the handler accesses it."
EXAMPLE
typedef int int32_t;
class C
{
public:
int32_t x;
C( )
try
{
// Action that may raise an exception
}
REPAIR
Do not use non-static member of a class or a base class in the handler
of a function-try-block of a class constructor/destructor
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Where multiple handlers are provided in a single try-catch statement or function-try-block for
a derived class and some or all of its bases, the handlers shall be ordered most-derived to
base class [EXCEPT-17-3]
DESCRIPTION
"Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases,
the handlers shall be ordered most-derived to base class.
When testing to see if the type of an exception matches the type of a
handler,
a derived class exception will match with a handler for its base class.
If the base class handler is found before the handler for the derived
class,
the base class handler will be used. The derived class handler is
unreachable
code and can never be executed."
SINCE
v7.2
BENEFITS
Rule prevents writing unreachable code.
EXAMPLE
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( B &b )
{
// ...
}
catch ( D &d ) // Violation
{
// ...
}
}
REPAIR
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( D &d ) // OK - Derived class caught before base class
{
// ...
}
catch ( B &b ) // OK - Base class caught after derived class
{
// ...
}
}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [EXCEPT-18-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown while
a non-local object is declared or initialized.
see also: EXCEPT-13
SINCE
v7.2
NOTES
Rule checks only one level of nested function calls.
BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."
EXAMPLE
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( );
}
}
catch ( A const & )
{
}
}
};
A a; // Violation - unhandled exception of class B
REPAIR
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10
{
throw A
}
else
{
throw B
}
}
catch ( A const
{
}
catch ( B const
{
}
}
};
A a; // OK
)
( );
( );
& )
& )
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4
FORMAT
Formatting
RULES
Tabs that do not use ASCII spaces shall not be used [FORMAT-01-5]
Place an opening brace '{' on its own line [FORMAT-02-3]
Place a closing brace '}' on its own line [FORMAT-03-3]
Physical lines should be less than eighty characters [FORMAT-04-3]
The length of a macro should not exceed 10 lines [FORMAT-05-3]
Only one statement shall be allowed per line [FORMAT-06-3]
There shall be a single ASCII space character preceding assignment
operators [FORMAT-07-3]
There shall be a single ASCII space character following assignment
operators [FORMAT-08-3]
There shall be a single ASCII space character preceding bitwise operators
[FORMAT-09-3]
There shall be a single ASCII space character following bitwise operators
[FORMAT-10-3]
There shall be a single ASCII space character preceding and following
bitwise operator '&' [FORMAT-11-3]
There shall be a single ASCII space character between a conditional
statement keyword and its opening parenthesis [FORMAT-12-3]
There shall be a maximum of 1 ASCII space character following the opening
parenthesis in conditional statements [FORMAT-13-3]
There shall be a single ASCII space character preceding ternary
conditional operator [FORMAT-14-3]
There shall be a single ASCII space character following ternary
conditional operator [FORMAT-15-3]
There shall be a single ASCII space character preceding and following
relational and equality operators [FORMAT-16-3]
There shall be no white space following '.' or '->' operator [FORMAT-17-3]
There shall be no white space preceding '.' or '->' operator [FORMAT-18-3]
There shall be a single ASCII space character following all commas
[FORMAT-19-3]
There shall be a single ASCII space character following all semicolons
[FORMAT-20-3]
There shall be no white space between a prefix unary operator and its
operand [FORMAT-21-3]
There shall be no white space between a postfix unary operator and its
operand [FORMAT-22-3]
There shall be no white spaces between the "return" or "sizeof "
statements and its opening parenthesis [FORMAT-23-3]
There shall be no white spaces surrounding "return" or "sizeof "
statements argument or expression [FORMAT-24-3]
Tabs that do not use ASCII spaces shall not be used [FORMAT-01-5]
DESCRIPTION
This rule checks whether you are using only ASCII white spaces as tabs.
Different operating systems, display devices, and editors handle tabs
in different ways. Code containing tabs will likely be indented
incorrectly
if ported to another environment.
BENEFITS
Rule prevents inconsistent display of code containing tabs
in different environments.
EXAMPLE
void foo()
{
int i; // Violation
}
REPAIR
void foo()
{
int j; // OK
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 43
EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class A1
{ int a;
};
struct S1 {
int a;
};
// Violation
// Violation
REPAIR
class A1
{
int a;
};
struct S1
{
int a;
};
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61
EXCEPTIONS
Rule does not adhere to enums, initializations and empty blocks.
It is allowed to place tokens after '}' in the same line if:
- '}' ends 'do-while' construct
- '}' ends declaration of class/structure/union/enum
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
int goo(int i)
{
if (i == 0) { return i; }
// Violation
do { i++; } while (i < 10); // Violation
}
struct S{ int i; float f; }ss;
REPAIR
int goo(int i)
{
if (i == 0)
{
return i;
}
// OK
do
{
i++;
// Violation
// OK - Exception
// OK - Exception
// OK - Exception
// OK - Exception
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61
BENEFITS
Rule improves readability of code.
EXAMPLE
const int MAXIMUM_LIMIT = 100;
void foo()
{
int someLocalVariableHoldingTheLimit = (MAXIMUM_LIMIT * 10) (MAXIMUM_LIMIT/2); // Violation
}
REPAIR
const int MAXIMUM_LIMIT = 100;
void foo()
{
int someLocalVariableHoldingTheLimit = (MAXIMUM_LIMIT * 10) (MAXIMUM_LIMIT/2); // OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Readability.
EXAMPLE
// Violation
#define SUM(\
PARAMETER_1,\
PARAMETER_2,\
PARAMETER_3,\
PARAMETER_4)\
(\
PARAMETER_1+\
PARAMETER_2+\
PARAMETER_3+\
PARAMETER_4\
)
void main()
{
int val = SUM(1,1,1,1);
}
REPAIR
// OK
#define SUM( PARAMETER_1, PARAMETER_2, PARAMETER_3, PARAMETER_4)\
(\
PARAMETER_1 + PARAMETER_2 + PARAMETER_3 + PARAMETER_4\
)
void main()
{
REFERENCES
Recommended by ParaSoft
BENEFITS
This rule promotes readability and maintainability by reducing code
complexity.
EXAMPLE
void foo()
{
int i; char c; // Violation
}
REPAIR
void foo()
{
int ii; // OK
char cc;
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 42
There shall be a single ASCII space character preceding assignment operators [FORMAT-07-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character preceding assignment operators.
See also: FORMAT-08
BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.
EXAMPLE
int y =
int z=1;
1; // Violation
// Violation
REPAIR
int x = 1; // OK
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character following assignment operators [FORMAT-08-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character following assignment operators.
See also: FORMAT-07
BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.
EXAMPLE
int y =
int z=1;
1; // Violation
// Violation
REPAIR
int x = 1; // OK
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character preceding bitwise operators [FORMAT-09-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character preceding bitwise operators.
See also: FORMAT-10, FORMAT-11
BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.
EXAMPLE
void foo()
{
int z = 73;
int y=0;
y=z|0x0f; // Violation
y=z | 0x0f; // Violation
}
REPAIR
void foo()
{
int z = 73;
int y=0;
y=z | 0x0f; // OK
}
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character following bitwise operators [FORMAT-10-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character following bitwise operators.
See also: FORMAT-09, FORMAT-11
BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.
EXAMPLE
void foo()
{
int z = 73;
int y=0;
y=z|0x0f; // Violation
y=z | 0x0f; // Violation
}
REPAIR
void foo()
{
int z = 73;
int y=0;
y=z | 0x0f; // OK
}
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character preceding and following bitwise operator '&'
[FORMAT-11-3]
DESCRIPTION
This rule checks whether there is a single ASCII space character
preceding and following bitwise operator &.
See also: FORMAT-09, FORMAT-10
SINCE
v7.0
BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.
EXAMPLE
void Space( ) {
int z = 73;
int y = 0;
y
y
y
y
y
=
=
=
=
=
z & y;
z & y;
z& y;
z &y;
z&y;
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
void Space( ) {
int z = 73;
int y = 0;
y = z & y;
}
// OK
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character between a conditional statement keyword and
its opening parenthesis [FORMAT-12-3]
DESCRIPTION
The rule reports a violation if between a conditional statement keyword
and its opening parenthesis:
- there is no space
- there is more than one space
- there is a tab or comment
or the opening parenthesis is not in the same line as conditional
statement
keyword.
As conditional statement keywords are recognized: if, for, switch, while
See also: FORMAT-13
BENEFITS
The rule improves readability of code.
EXAMPLE
void foo(int x, int y)
{
if(x < y){}
/* Violation
if (x > y){}
/* Violation
for(;;);
/* Violation while
(x < 10)
/* Violation
x++;
do{ /* .. */ }while(y > 1); /* Violation
}
REPAIR
void foo(int x, int y)
{
if (x < y){}
if (x > y){}
for (;;);
while (x < 10)
/*
/*
/*
/*
OK
OK
OK
OK
*/
*/
*/
*/
- no space */
- two spaces */
tab is used */
*/
*/
x++;
do{ /* .. */ }while (y > 1); /* OK */
}
REFERENCES
Recommended by ParaSoft
There shall be a maximum of 1 ASCII space character following the opening parenthesis in
conditional statements [FORMAT-13-3]
DESCRIPTION
This rule checks whether there is a maximum of 1 ASCII space
character following the opening parenthesis in conditional
statements: for, if, switch, while.
See also: FORMAT-12
BENEFITS
A maximum of 1 ASCII space after the opening
parenthesis improves readability.
EXAMPLE
void foo()
{
int x=1;
int y=1;
if(
{
}
x == y
) // Violation
REPAIR
void foo()
{
int x=1;
int y=1;
if (x == y) // OK
{
}
if ( x == y ) // OK
{
}
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character preceding ternary conditional operator
[FORMAT-14-3]
DESCRIPTION
This rule checks that there is a single ASCII space character
preceding ternary conditional operator.
See also: FORMAT-15
BENEFITS
This convention promotes readability by clearly separating
the operands from the operator.
EXAMPLE
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
j = ( i < 0 )?( -i ) : ( i );
}
// Violation
// Violation
REPAIR
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
}
REFERENCES
Recommended by ParaSoft
// OK
There shall be a single ASCII space character following ternary conditional operator
[FORMAT-15-3]
DESCRIPTION
This rule checks whether there is a single ASCII space character
following ternary conditional operator.
See also: FORMAT-14
BENEFITS
This convention promotes readability by clearly separating
the operands from the operator.
EXAMPLE
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
j = ( i < 0 )?( -i ) : ( i );
}
// Violation
// Violation
REPAIR
void foo()
{
int j=10;
int i=1;
j = ( i < 0 ) ? ( -i ) : ( i );
}
REFERENCES
Recommended by ParaSoft
// OK
There shall be a single ASCII space character preceding and following relational and equality
operators [FORMAT-16-3]
DESCRIPTION
This rule checks whether there is a single ASCII space character
preceding and following relational and equality operators.
BENEFITS
This convention promotes readability by clearly separating
the operands from the operator.
EXAMPLE
void foo(int x)
{
if(x==1)
// Violation
{
}
if(x
{
}
>
if(x <=1)
{
}
1)
// Violation
// Violation
REPAIR
void foo(int x)
{
if(x == 1)
// OK
{
}
if(x > 1)
{
}
// OK
if(x <= 1)
{
}
// OK
REFERENCES
Recommended by ParaSoft
NOTES
The violation is not reported if '.' or '->' is last in line ignoring
white spaces, comments and backslashes. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.
BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.
EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj.
x;
/* Violation */
myObjPtr-> x; /* Violation */
}
#define MACRO a. b /* Violation */
REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {
myObj.x;
/* OK */
myObjPtr->
/* OK: '->' is last in line*/
x;
myObj./*comment*/ x; /* OK: no space immediately after '.' */
}
#define MACRO a. /* OK: '.' is last in line */ \
b
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif
REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
NOTES
The Violation is not reported if '.' or '->' is first in line ignoring
white spaces and comments. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.
BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.
EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj
.x;
/* Violation */
myObjPtr ->x; /* Violation */
}
#define MACRO a .b /* Violation */
REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {
myObj.x;
/* OK */
myObjPtr
->x;
/* OK: '->' is first in line*/
myObj /*comment*/.x; /* OK: no space immediately before '.' */
}
#define MACRO a \
.b /* OK: '.' is first in line */
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif
REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
There shall be a single ASCII space character following all commas [FORMAT-19-3]
DESCRIPTION
This rule checks whether there is a single ASCII
space character following all commas.
BENEFITS
Since commas delineate individual statements, a space shall be used
to highlight this fact. This greatly improves the readability of 'C'.
EXAMPLE
void foo()
{
int xx,yy;
// Violation
int xxx, yyy; // Violation
}
REPAIR
void foo()
{
int x, y; // OK
}
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character following all semicolons [FORMAT-20-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character following all semicolons.
BENEFITS
Since semicolons delineate individual statements, a space shall be used
to highlight this fact. This greatly improves the readability of 'C'.
EXAMPLE
void foo()
{
int i;
for ( i = 0;i <= 10;i++) // Violation
{
}
}
REPAIR
void foo()
{
int i;
for ( i = 0; i <= 10; i++) // OK
{
}
}
REFERENCES
Recommended by ParaSoft
There shall be no white space between a prefix unary operator and its operand [FORMAT-21-3]
DESCRIPTION
This rule checks whether there is no white space between a prefix unary
operator
and its operand. This promotes continuity in the relationship between
the operators and their associated operand. These operators act solely on
their
operand and cannot be considered separately from it.
BENEFITS
Improves readability.
EXAMPLE
void foo()
{
int i=0;
-- i; // Violation
}
REPAIR
void foo()
{
int i=0;
--i;
// OK
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
There shall be no white space between a postfix unary operator and its operand [FORMAT-223]
DESCRIPTION
This rule checks whether there is no white space between a postfix unary
operator and its operand. This promotes continuity in the relationship
between the operators and their associated operand. These operators
act solely on their operand and cannot be consider separately from it.
BENEFITS
Improves the readability of code.
EXAMPLE
void foo()
{
int y = 0;
y ++;
}
// Violation
REPAIR
void foo()
{
int y = 0;
y++;
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
There shall be no white spaces between the "return" or "sizeof " statements and its opening
parenthesis [FORMAT-23-3]
DESCRIPTION
This rule checks for white spaces between the "return" and "sizeof"
statements.
See also: FORMAT-24, FORMAT-25
BENEFITS
Improves the readability of code.
EXAMPLE
void foo()
{
sizeof (int); // Violation
}
REPAIR
void foo()
{
sizeof(int); // OK
}
REFERENCES
Recommended by ParaSoft
There shall be no white spaces surrounding "return" or "sizeof " statements argument or
expression [FORMAT-24-3]
DESCRIPTION
This rule checks whether there are no white spaces between
the "return" and "sizeof" statements, arguments, or expressions.
See also: FORMAT-23, FORMAT-25
BENEFITS
Improves the readability of code.
EXAMPLE
void foo()
{
sizeof( int ); // Violation
}
REPAIR
void foo()
{
sizeof(int); // OK
}
REFERENCES
Recommended by ParaSoft
Parenthesis shall be used with the "return" and "sizeof" statements [FORMAT-25-3]
DESCRIPTION
This rule checks whether parentheses are used with
the "return" and "sizeof" statements.
See also: FORMAT-23, FORMAT-24
BENEFITS
Improves the readability of code.
EXAMPLE
#define true 1
#define false 0
int foo()
{
return true; // Violation
}
REPAIR
#define true 1
#define false 0
int goo()
{
return(true); // OK
}
void xoo()
{
return;
}
// OK
REFERENCES
Recommended by ParaSoft
There shall be a single ASCII space character preceding and following logical operators
[FORMAT-26-3]
DESCRIPTION
This rule checks whether there is a single ASCII space
character preceding and following logical operators.
BENEFITS
This convention promotes readability by clearly
separating the operands from the operator.
EXAMPLE
void foo()
{
int x = 1;
int y = 1;
if(x||y)
{
}
if(x
{
}
||
// Violation
y) // Violation
REPAIR
void foo()
{
int x = 1;
int y = 1;
if(x || y) // OK
{
}
}
REFERENCES
Recommended by ParaSoft
NOTES
- Rule treats tab characters as alignment to correct column indentation.
- Rule does not check indentation for lines which are in context
of "()" or "[]" or line which starts with preprocessor directives.
- Rule can be parameterized by changing values of the following variables
in Python scripts:
- Variable "IndentSize" contains the size of indentation in spaces.
- Variable "TabSize" contains the size of tab character in spaces.
- Both variables are set to 4.
BENEFITS
Improves readability of code.
EXAMPLE
class A {
};
void foo(){
}
class B {
int a;
int b;
};
// Violation
// Violation
// Violation
// Violation
// Violation
x = 2;
// Violation
}
}
REPAIR
class A {
};
void foo(){
}
class B {
int a;
int b;
};
// OK
// OK
// OK
// OK
// OK
REFERENCES
Recommended by ParaSoft
In a function definition, the return type of the function should be written on a separate line
directly above the function name [FORMAT-28-3]
DESCRIPTION
"In function definition, the return type of the function should be written
on a separate line directly above the function name."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
int foo() {
return 0;
}
// Violation
REPAIR
int
foo() {
return 0;
}
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.2 Functions - Rec. 22
Multiple variable declarations shall not be allowed on the same line [FORMAT-29-3]
DESCRIPTION
Rule triggers if some variables are declared on the same line.
See also: FORMAT-33
NOTES
Violation is not reported if variables are declared by macros.
BENEFITS
Rule increases readability and prevents confusion.
EXAMPLE
void foo( ) {
int a, b;
}
// Violation
REPAIR
void foo( ) {
int a;
int b;
}
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.19 Variables, AV Rule 152
BENEFITS
Rule improves readability of code.
EXAMPLE
void
foo () {// Violation
}
REPAIR
void
foo() {// OK
}
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.2 Functions - Rec. 23
BENEFITS
Makes code more readable.
EXAMPLE
void foo( int j, int i) {
if (i != j > 0) {}
}
// Violation
REPAIR
void foo( int j, int i) {
if (i != j && j > 0) {}
}
// OK
REFERENCES
Motorola Coding Standards G-12
The dereference operator `*' and the address-of operator `&' should be directly connected with
the type names [FORMAT-32-3]
DESCRIPTION
"The dereference operator * and the "address-of" operator & should be
directly connected to the type names in declaration and definition."
BENEFITS
Rule makes source code more readable.
EXAMPLE
void foo() {
int k=42;
int *p1;// Violation
int &r1 = k;// Violation
}
REPAIR
void foo() {
int k=42;
int* p2;// OK
int& r2 = k;// OK
}
REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#6.5
from: 6 Style - 6.4 Pointers and References - Rec. 26
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 62
BENEFITS
Rule prevents confusion and makes source code more readable.
EXAMPLE
void foo( )
{
int* a, b;
}
// Violation
REPAIR
void foo( )
{
int* a;
int b;
}
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 39, 6 Style - 6.5 Pointers and References Rec. 26
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-0-1
Braces "{}" which enclose a block should be placed in the same column [FORMAT-34-3]
DESCRIPTION
Rule checks if opening and closing braces are placed in the same column.
See also: FORMAT-02, FORMAT-03
EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//
Rule does not report violation
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class Foobar {
int a;
};
// Violation
struct S1 {
int a;
};
// Violation
REPAIR
class Foobar
{
int a;
};
struct S1
{
int a;
};
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 60
When declaring functions, the leading parenthesis and the first argument are to be written on
the same line as the function name [FORMAT-35-3]
DESCRIPTION
"When declaring functions, the leading parenthesis and the first argument
(if any) are to be written on the same line as the function name."
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
void foo
( );
void goo(
int a );
// Violation
// Violation
REPAIR
void foo( );
// OK
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.2 Functions - Rec. 21
SINCE
v7.1
NOTES
- Rule treats tab characters as an alignment to correct column
indentation.
- Rule does not check indentation for lines which are in context
of "()" or "[]" or lines which start with preprocessor directives.
- Rule can be parameterized by changing value of the "TabSize" variable
in Python scripts (by default it is set to 4 spaces).
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x ) {
if (x == 0) {
}
x = 2;
x = 2;
// Violation
x = 2;
// Violation
x = 2;
// Violation
x = 2;
// Violation
}
REPAIR
void foo( int x ) {
if (x == 0) {
}
x = 2;
// OK
x = 2;
// OK
x = 2;
// OK
x = 2;
// OK
x = 2;
// OK
}
REFERENCES
Recommended by ParaSoft
First line in control statement body should be indented more than control statement keyword
[FORMAT-37-3]
DESCRIPTION
First line in control statement body (if, else, while, do while, for,
switch, try, catch, case, default) should be indented more than
control statement keyword.
See also: FORMAT-27, FORMAT-36
SINCE
v7.1
NOTES
- Rule does not check indentation for lines which starts with preprocessor
directives.
- Rule can be parameterized by changing values of the following variables
in Python scripts:
"MinIndentSize" - the minimum admissible size of indentation in spaces
"MaxIndentSize" - the maximum admissible size of indentation in spaces
"TabSize"
- size of tab character in spaces
All variables are set to 4 by default.
For example: MinIndentSize = 2, MaxIndentSize = 4:
while (x == 0)
x = 1;
// OK - indent size = 2
while (x == 0)
x = 1;
// OK - indent size = 3
while (x == 0)
x = 1;
// OK - indent size = 4
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x ) {
while (x == 0)
x = 1;
// Violation
if (x == 0) {
x++;
// Violation
x++;
}
}
REPAIR
void foo( int x ) {
while (x == 0)
x = 1;
// OK
if (x == 0) {
x++;
// OK
x++;
}
}
REFERENCES
Recommended by ParaSoft
When declaring functions with more than 2 parameters, the leading parenthesis and the first
argument are to be written on the same line as the function name, each additional argument
will be written on a separate line [FORMAT-38-3]
DESCRIPTION
When declaring and defining functions with more than two parameters,
the leading parenthesis and the first argument will be written on
the same line as the function name. Each additional argument will
be written on a separate line (with the closing parenthesis directly
after the last argument).
SINCE
v7.1
BENEFITS
Readability and style.
EXAMPLE
void foo(int a, int b, int c);// Violation
void zoo(
int a, int b,
int c
)
{
// Violation
// Violation
// Violation
REPAIR
void foo(int a,
int b,
int c);
void zoo( int a,
int b,
// OK
int c)
// OK
{
}
void goo(int a, int b); // OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 58
SINCE
v9.2
NOTES
<header> includes are not compared with "header" includes.
Two includes are compared only if they are in consequent lines.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
#include "zheader2.h"
#include "zheader1.h" // Violation
// this line have no #include
#include "zheader0.h" // ok - previous include not in previous line
#include <iostream> // ok - <header> not compared with "header"
#include <algorithm> // Violation
REPAIR
#include
#include
#include
#include
#include
"zheader0.h"
"zheader1.h"
"zheader2.h"
<algorithm>
<iostream>
White spaces after the opening square bracket '[' and before its closing square bracket ']' shall
be used in consistent way [FORMAT-40-5]
DESCRIPTION
The rule checks if after the opening square bracket '[' and before the
closing
square bracket ']' the white spaces are used in consistent way.
See also: FORMAT-41
SINCE
v9.2
NOTES
It is possible to adapt this rule to standard that allows or disallows to
use
white spaces after '[' and before ']'. The modification can be done in
python
method 'formatRule'. To variable 'format' should be assigned the string
containing the preferred format.
There are three possibilities:
1. format = "[ 1 ] or [1]" (the default)
In this case there are two correct patterns:
- at least one white space both after the opening square brace '[' and
before the closing square brace ']'
- no white space neither after the opening square brace '[' nor before
the closing square brace ']'. For example:
int a1[1];
// OK
int a2[ 1]; // Violation
int a3[1 ]; // Violation
int a4[ 1 ]; // OK
2. format = "[1]"
In this case should be no white space neither after the opening square
brace '[' nor before the closing square brace ']'. For example:
int a1[1];
// OK
int a2[ 1]; // Violation
1 ]"
there should be at least one white space after the opening
'[' and before the closing square brace ']'. For example:
// Violation
// Violation
// Violation
// OK
BENEFITS
The rule improves readability of code.
EXAMPLE
// the default format:
int tab[ 10]; /* Violation */
void foo() {
tab[0 ] = 0; /* Violation */
}
REPAIR
// the default format:
int tab[10];
/* OK - space removed */
void foo() {
tab[ 0 ] = 0; /* OK - space added */
}
REFERENCES
Recommended by Parasoft
There shall be no space between '[' opening square bracket and preceding token [FORMAT-415]
DESCRIPTION
The rule reports a violation if:
- there is a space, tab or comment preceding opening square bracket ('[')
- an opening square bracket ('[') is first token in line.
The intention of this rule is to have the bracket "glued" together
with preceding token.
See also: FORMAT-17, FORMAT-18, FORMAT-40
SINCE
v9.2
EXCEPTIONS
No violation is reported for following code:
const char special[256] = {
[0] = 1, ['?'] = 1,
['x'] = 1 };
BENEFITS
The rule improves readability of code.
EXAMPLE
int tab [10];
/* Violation */
void foo(int param []) {
/* Violation */
char* arr = new char [10]; /* Violation */
tab/*comment*/[0] = 0;
/* Violation */
tab
[0] = 0;
/* Violation */
delete [] arr;
/* Violation */
}
REPAIR
int tab[10];
void foo(int param[]) {
char* arr = new char[10];
tab[0] = 0;
delete[] arr;
}
REFERENCES
Recommended by Parasoft
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
INIT
Initialization
RULES
Headers should not contain any initialization [INIT-01-3]
Do not initialize unsigned integer variables with signed constants [INIT02-3]
Initialize all variables [INIT-03-3]
Initialize all pointer variables [INIT-04-2]
Do not initialize a reference to an object whose address can be changed
[INIT-05-1]
All member variables should be initialized in constructor [INIT-06-1]
Make class members' initialization explicit by providing user-defined
constructor [INIT-07-3]
User-defined constructor must be provided to ensure the proper
initialization of dynamically allocated class objects [INIT-08-3]
Initialize static class members [INIT-09-1]
List members in an initialization list in the order in which they are
declared [INIT-10-3]
Assign to all data members in operator= [INIT-11-2]
Avoid initialization order problems across translation units [INIT-12-3]
Do not assume that members are initialized in any special order in
constructors [INIT-13-3]
Prefer initialization to assignment in constructors [INIT-14-5]
NOTES
Rule is designed for C code.
BENEFITS
Rule prevents producing "multiply defined" diagnostics.
EXAMPLE
// header file
int i = 0;// Violation
REPAIR
// header file
int i;// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
The rule prevents undesirable implicit conversions.
EXAMPLE
struct S {
unsigned int m_i;
};
void foo()
{
unsigned int y = -21;
S s = {-10};
}
// Violation
// Violation
class A {
public:
A();
private:
unsigned int ai;
};
A::A() : ai(-10){
}
REPAIR
struct S {
unsigned int m_i;
signed int n_i;
};
// Violation
void foo()
{
unsigned int y = 21;
signed int x = -21;
S s = { 10, -10};
}
// OK
// OK
// OK
class A {
public:
A();
private:
unsigned int ai;
signed int si;
};
A::A() : ai(10), si(-10){
}
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
2. ISO/DIS 26262
point 8.4.4
EXCEPTIONS
Exception to this rule are 'volatile' data, non-primitive types, and
arrays.
BENEFITS
Prevents reading from uninitialized variables.
EXAMPLE
int a;
void foo( ) {
int b;
}
// Violation
// Violation
REPAIR
int a = 0;
void foo( ) {
int b = 0;
}
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 142
4. http://cwe.mitre.org/data/definitions/457.html
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
6. ISO/DIS 26262
point 8.4.4
NOTES
This rule enforces a good coding standard practice: always initialize
pointer
variables, even if you're going to change (assign) the variable at once.
BENEFITS
Initializing pointer variables prevents dereferencing of uninitialized
pointers.
EXAMPLE
void foo(int y, int * p)
{
int *i; // Violation
int *j; // Violation
if (y) {
j = 0;
} else {
j = p;
}
}
REPAIR
void foo(int y, int * p)
{
int *i = 0;
// OK
int *j = y ? 0 : p; // OK
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 19
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. ISO/DIS 26262
point 8.4.4
BENEFITS
Prevents illegal accessing to not existing variable which was free
previously.
EXAMPLE
void foo()
{
int *ptr = 0;
int &rptr = *ptr; // Violation
}
REPAIR
void foo()
{
int ptr = 0;
int &rptr = ptr; // OK
}
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
The rule assumes that member variable might be initialized
by passing its non-const pointer to an external function.
BENEFITS
Prevents reading from uninitialized variables.
EXAMPLE
class C
{
public:
C( );
private:
int mem_a;
int mem_b;
int mem_c;
int mem_d;
int mem_e;
};
C::C( ) // Violation - mem_a, mem_b, mem_c, mem_d, mem_e - not initialized
{
}
REPAIR
class C
{
public:
C( );
void init();
void init2();
void getPtr(int *);
private:
int mem_a; // initialized in constructor initialization list
int mem_b; // initialized inside constructor body
int mem_c; // initialized inside function 'init' called from
constructor
int mem_d; // initialized inside function 'init2' called from 'init'
int mem_e; // its non-const pointer is passed to an external function.
};
void C::init()
{
mem_c = 2;
init2();
}
void C::init2()
{
mem_d = 2;
}
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
NOTES
Classes that have only static members or no members at all are omitted
by this rule.
BENEFITS
If you follow this rule, you will make class initialization explicit and
prevent the compiler from initializing members improperly, especially
pointer members.
EXAMPLE
class B
{
public:
static int s;
int b;
int a;
};
int main()
{
B bb;
// Violation
return 0;
}
REPAIR
class A
{
public:
A(){}
private:
static int w;
int b;
int a;
};
class C // OK
{
public:
int foo();
void qwe(int x);
};
class D // OK
{
public:
static int s;
static int b;
static int a;
};
int main()
{
C cc; // OK
A a;
// OK
D dd; // OK
return 0;
}
REFERENCES
Recommended by ParaSoft
NOTES
Classes that have only static members or no members at all are omitted
by this rule.
BENEFITS
If you follow this rule, you will make class initialization explicit and
prevent the compiler from initializing members improperly, especially
pointer members.
EXAMPLE
class B
{
public:
static int s;
int b;
int a;
};
B* foo(B* b)
{
B* a=new B(); // Violation
return new B(); // Violation
}
int main()
{
foo(new B()); // Violation
return 0;
REPAIR
class A
{
public:
A(){}
static int w;
int b;
int a;
};
A* foo2()
{
A* a=new A(); // OK
return new A(); // OK
}
REFERENCES
Recommended by ParaSoft
SINCE
v7.0
BENEFITS
Prevents reading from uninitialized variables.
EXAMPLE
class C{
const static int a; // Violation
static int b;
};
int C::b; // Violation
REPAIR
class C{
const static int a = 0;
static int b;
};
// OK
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
2. ISO/DIS 26262
point 8.4.4
List members in an initialization list in the order in which they are declared [INIT-10-3]
DESCRIPTION
"Recall that the destructors for the members of an object are always
called
in the inverse order of their constructors. Thus, if members were
initialized
in the order of their appearance in an initialization list, compilers
would
have to keep track of the order in which the members were initialized for
each
object, just to ensure that the destructors would be called in the right
order.
That would be an expensive proposition. To avoid that overhead, the order
of construction and destruction is the same for all objects of a given
type,
and the order of members in an initialization list is ignored."
In example section variable b from class A will not be initialized as we
assumed (initialized by the same value).
See also: INIT-06, INIT-14, MISRA-030
BENEFITS
Prevents access to null pointer when memory is not allocated.
EXAMPLE
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int b;
int a;
};
class B : public A {
public:
B( int );
private:
int a;
float b;
};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}
before b
// Violation - a is declared
REPAIR
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int a;
int b;
};
// OK - a is declared before b
class B : public A {
public:
B( int );
private:
float b;
int a;
};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}
// OK - b is declared before a
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 13
3, JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 75
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
The rule assumes that member variable might be initialized
by passing its non-const pointer to an external function.
BENEFITS
Assign to all member variables in operator= function in order to prevent
data corruption.
EXAMPLE
class C
{
public:
C& operator=(const C&);
private:
int mem_a;
int mem_b;
int mem_c;
int mem_d;
};
C& C::operator=(const C&) // Violation - mem_a, mem_b, mem_c, mem_d - not
assigned
{
}
REPAIR
class C
{
public:
C& operator=(const C&);
void init();
void init2();
void getPtr(int *);
private:
int mem_a; // assigned inside operator= body
int mem_b; // assigned inside function 'init' called from operator=
int mem_c; // assigned inside function 'init2' called from 'init'
int mem_d; // its non-const pointer is passed to an external function.
};
void C::init()
{
mem_b = 2;
init2();
}
void C::init2()
{
mem_c = 2;
}
C& C::operator=(const C&) // OK - all members are assigned
{
mem_a = 1;
init();
getPtr(&mem_d);
}
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 12
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
SINCE
v7.0
BENEFITS
"This approach is founded on C++'s guarantee that local
static objects are initialized when the object's definition
is first encountered during a call to that function. So if
you replace direct accesses to non-local static objects
with calls to functions that return references to local
static objects, you're guaranteed that the references you
get back will refer to initialized objects. As a bonus, if you
never call a function emulating a non-local static object,
you never incur the cost of constructing and destructing
the object, something that can't be said for true non-local
static objects."
EXAMPLE
#include <iostream>
using namespace std;
class FileSystem {
public:
size_t numDisks( ) const;
};
extern FileSystem tfs;
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_tfs = tfs.numDisks( );
}
Directory tempDir( );
// Violation
REPAIR
#include <iostream>
using namespace std;
class FileSystem {
public:
size_t numDisks( ) const;
};
FileSystem& tfs_one( ) {
static FileSystem fs;
return fs;
}
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_one = tfs_one().numDisks( );
}
Directory tempDir( );
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
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
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]
>, >=, <, <= 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]
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
// ...
return x;
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
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
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
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
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
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
//
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) {
// 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
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;
}
}
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
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,
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
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
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;
}
};
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
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
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
// Violation
{
return (*ptr) + 1;
}
REPAIR
typedef int* PINT;
typedef const int* CINT;
int function1(CINT ptr)
{
return (*ptr) + 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 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
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 */
/* Violation */
REPAIR
void foo1( ) {
/* empty */
}
/* OK */
void foo2( );
/* OK */
void foo3( ) {
foo2( );
}
/* 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 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
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();
};
// OK
// OK
REFERENCES
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
SINCE
v7.1
EXCEPTIONS
Constructors, destructors, template methods, virtual methods.
BENEFITS
Inlining short, simple functions can save both time and space.
EXAMPLE
int goo(int a, int b)
{
/* code */
return 1;
}
int foo(int a, int b)
{
return(goo(a,b));
}
REPAIR
int goo(int a, int b)
{
/* code */
return 1;
// Violation
}
inline int foo(int a, int b) // OK
{
return(goo(a,b));
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 124
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
EXCEPTIONS
There also may be a situation where the object is so small that it would
be
more efficient to pass by value instead of by reference.
Due to C++'s type system and the fact that QString, RWCString and CString
are implicitly shared, they may be treated like ints or other basic types.
BENEFITS
Improves code consistency and runtime performance.
EXAMPLE
class A {
public:
const A violation( A a ) {
value
return a;
}
};
REPAIR
class A {
public:
const A& valid( const A &a ) {
return a;
}
// OK
// OK
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 20
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 22
4. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 43
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125
7. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
"Assignment versions of operators are more efficient than stand-alone
versions,
because stand-alone versions must typically return a new object, and that
costs
us the construction and destruction of a temporary. Assignment versions of
operators write to their left-hand argument, so there is no need to
generate
a temporary to hold the operator's return value."
EXAMPLE
class A {
public:
};
A& operator+( A& a, A& b );
A& operator-( A& a, A& b );
class B {
public:
B& operator+=( B& b );
};
B& operator+( B& a, B& b );
void foo( ) {
B ba, bb ,bc, bd;
// Violation
// Violation
bb = ba + bc + bd;
// Violation
REPAIR
class A {
public:
A& operator+=( A& a );
A& operator-=( A& a );
};
A& operator+( A& a, A&
A& operator-( A& a, A&
class B {
public:
B& operator+=( B& b
};
B& operator+( B& a, B&
void foo( ) {
B ba, bb ,bc, bd;
bb = ba;
bb += bc;
bb += bd;
}
b );
b );
// OK
// OK
);
b );
// OK
// OK
// OK
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 22
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125
BENEFITS
Rule improves readability and maintainability. If the characters // are
consistently used for writing comments, then the combination /* */ may be
used
to make comments out of entire sections of code during the development and
debugging phases.
EXAMPLE
/* Violation */
REPAIR
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 9
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 126
NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.
BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."
EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}
// Violation
REPAIR
void foo()
{
int x = 5;
/* Comment without
// OK
code within */
#if 0
if (x==0){
x++;
}
#endif
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3
BENEFITS
Prevents from various undefined and implementation-defined behaviours
associated with
them and they shall not be used.
EXAMPLE
#include <stddef.h>
void foo() {
wchar_t* x = L"Fred";/* Violation */
}
REPAIR
#include <stddef.h>
void foo() {
char* x = "Fred";/* OK */
}
REFERENCES
1. Origin: Misra Guidelines - Rule 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 13
SINCE
v7.1
NOTES
Rule checks only declarations of local and global variables.
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo()
{
int var1;
// Violation
int var2;
// Violation
}
REPAIR
void foo()
{
int var1; // comment - OK
// comment - OK
int var2;
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
typedef int int32;
// Violation
REPAIR
typedef int int32; // OK - comment
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
enum {
ENUM1 = 2,
// Violation
};
REPAIR
enum {
ENUM1 = 2, // OK - comment
};
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
struct S
{
char* c;
// Violation
};
REPAIR
struct S
{
char* c; // comment - OK
};
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 132
NOTES
C and C++ style comments are allowed.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
// No comment "File:"
REPAIR
// File: <short description of the file>
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
// Violation - no copyright information
REPAIR
// Copyright
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.3 Comments - Rule 5
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 133
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo1();
// Violation
REPAIR
// Comment with description for the function.
void foo1();
// Comment with description for the function.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 4 Source Code in Files - 4.3 Comments - Rec. 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 134
Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [JSF-135_a-2]
DESCRIPTION
Do not hide names of global variables and parameters.
BENEFITS
Hiding names of global variables or parameters
can lead to errors and confusion.
EXAMPLE
int x;
void foo( ) {
int x;
/* Violation */
x = 3;
}
REPAIR
Avoid hiding names of global variables and parameters.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4
Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [JSF-135_b-2]
DESCRIPTION
Do not hide names of local variables.
BENEFITS
Hiding names of local variables can lead to errors and confusion.
EXAMPLE
int foo( ) {
int a;
{
int a;
}
}
/* Violation */
REPAIR
Avoid hiding names of local variables.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4
BENEFITS
Prevents using global variables.
EXAMPLE
int globalVar;
// Violation
REPAIR
void foo( ) {
int localVar;
}
// OK
REFERENCES
1. Misra Guidelines - Rule 22
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 57
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 136
4. ISO/DIS 26262
point 8.4.4
BENEFITS
Prevents from accidentally overwriting of functions or variables
EXAMPLE
int g1; /* Violation */
void foo1() {}; /* Violation */
REPAIR
static int g2; /* OK */
static void foo2(){}; /* OK */
REFERENCES
1. Origin: Misra Guidelines - Rule 23
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 137
BENEFITS
Rule prevents variable-name hiding which can be confusing.
EXAMPLE
static unsigned short x;
static unsigned short y;
void foo( ) {
extern unsigned short x;
// Violation
extern unsigned short y;
// Violation
{
extern unsigned short y; // Violation
}
}
REPAIR
Do not declare variables simultaneously with internal and external
linkage in the same translation unit.
REFERENCES
1. Origin:
The static storage class specifier shall be used in definitions and declarations of objects and
functions that have internal linkage [JSF-138_b-2]
DESCRIPTION
"It is good practice to apply the static keyword consistently to
all declarations of objects and functions with internal linkage."
See also: CODSTA-81
BENEFITS
Rule improves good programming style and readability.
EXAMPLE
/* file.h */
static int x;
/* file.c */
#include "file.h"
extern int x;
/* Violation */
REPAIR
/* file.h */
static int x;
/* file.c */
#include "file.h"
static int x;
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 138
External object should not be declared in more than one file [JSF-139-3]
DESCRIPTION
External objects should be declared in header files which are then
included in all
those source files which use these objects. This rule will inform about
multiple
declarations of symbols.
BENEFITS
Rule improves readability, clarity of code and prevents errorneous code.
EXAMPLE
/* misra_027.h */
/* Do not declare external object in more than one file. */
extern int a;
/* Violation */
/* misra_027.c */
#include "misra_027.h"
extern int a;
REPAIR
/* misra_027.h */
extern int a;
/* OK */
/* misra_027.c */
#include "misra_027.h"
int a;
REFERENCES
1. Origin: Misra Guidelines - Rule 27
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 139
Literal suffixes shall use uppercase rather than lowercase letters [JSF-14-2]
DESCRIPTION
Literal suffixes shall use uppercase rather than lowercase letters.
See also: CODSTA-50
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo(long param = 64l) // Violation
{
const long a = 64l; // Violation
}
REPAIR
void foo(long param = 64L) // OK
{
const long a = 64L;
// OK
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4
BENEFITS
Prevents from dependencies on compiler.
EXAMPLE
void foo()
{
register int a;
}
// Violation
REPAIR
Do not use the 'register' storage class specifier.
REFERENCES
1. Origin:
A class, structure, or enumeration will not be declared in the definition of its type [JSF-141-3]
DESCRIPTION
A class, structure, or enumeration will not be declared in the definition
of its type.
SINCE
v7.1
BENEFITS
Rule improves readability.
EXAMPLE
enum
{
up,
down
} direction;
// Violation
REPAIR
enum direction_e
{
up,
down
};
direction_e direction; // OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 141
All automatic variables shall have been assigned a value before being used [JSF-142_a-2]
DESCRIPTION
"The intent of this rule is that all variables shall have been written to
before
they are read. This does not necessarily require initialisation at
declaration.
Ideally a static check should be performed for any automatic variables
which
might be used without having first been assigned a value"
See also: INIT-06, INIT-10, INIT-14, BD-PB-NOTINIT
NOTES
The rule assumes that local variable might be initialized
by passing its non-const pointer to an external function.
BENEFITS
Prevents reading from uninitialized variables.
EXAMPLE
void foo( ) {
int b;
b++;
}
// Violation
REPAIR
void foo( ) {
int b = 0;
b++;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
EXCEPTIONS
Exception to this rule are 'volatile' data, non-primitive types, and
arrays.
BENEFITS
Prevents reading from uninitialized variables.
EXAMPLE
int a;
void foo( ) {
int b;
}
// Violation
// Violation
REPAIR
int a = 0;
void foo( ) {
int b = 0;
}
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 142
4. http://cwe.mitre.org/data/definitions/457.html
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
6. ISO/DIS 26262
point 8.4.4
Variables will not be introduced until they can be initialized with meaningful values [JSF-1432]
DESCRIPTION
Variables will not be introduced until they can be initialized with
meaningful values.
Rule reports a violation message if:
- value assigned to local variable during initialization is not used (i.e.
there is
no variable usage after initialization statement and before new value
assignment)
- local variable is prematurely declared and is only used in for loop
SINCE
v7.1
NOTES
Rule is enabled for C++ only.
BENEFITS
Prevent clients from accessing variables without meaningful values.
EXAMPLE
int f(int);
void fun_1(int x)
{
int i;
int max=0;
max = f(x);
for (i=0 ; i<max ; ++i)
{
}
}
REPAIR
int f(int);
void fun_2(int x)
{
int max = f(x);
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 143
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Braces shall be used to indicate and match the structure in the non-zero initialization of arrays
and structures [JSF-144-2]
DESCRIPTION
"ISO C requires initializer lists for arrays, structures and union types
to be
enclosed in a single pair of braces (though the behaviour if this is not
done
is undefined). The rule given here goes further in requiring the use
of additional braces to indicate nested structures.
The zero initialization of arrays or structures shall only be applied
at the top level. The non-zero initialization of arrays or structures
requires an explicit initializer for each element."
NOTES
Rule checks only up to three-level nested bracket initialization.
EXCEPTIONS
"All the elements of arrays or structures can be initialized (to zero or
NULL)
by giving an explicit initializer for the first element only. If this
method
of initialization is chosen then the first element should be initialized
to zero (or NULL), and nested braces need not be used."
BENEFITS
"This forces the programmer to explicitly consider and demonstrate the
order
in which elements of complex data types are initialized"
EXAMPLE
int y[3][2] = { 1, 2, 3, 4, 5, 6 }; // Violation
struct S {
int i;
struct T {
int j;
}t;
} s = {1, 2}; // Violation
REPAIR
int y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // OK
struct S {
int i;
struct T {
int j;
}t;
} s = {1, { 2 }}; // OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Misra Guidelines - Rule 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 144
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-2
In an enumerator list, the "=" construct shall not be used to explicitly initialise members other
than the first, unless all items are explicitly initialised [JSF-145-2]
DESCRIPTION
"In enumerator list, the '=' construct shall not be used
to explicitly initialize members other than the first,
unless all items are explicitly initialized."
BENEFITS
Helps avoid errors and confusion.
EXAMPLE
enum TEST { /* Violation */
X = 1,
Y,
Z = 3,
};
enum TEST2 { /* Violation */
X2,
Y2 = 2,
Z2,
};
enum TEST3 { /* Violation */
X3,
Y3,
Z3 = 3,
};
REPAIR
enum TEST { /* OK */
X,
Y,
Z,
};
enum TEST2 { /* OK */
X2 = 1,
Y2,
Z2,
};
enum TEST3 { /* OK */
X3 = 1,
Y3 = 2,
Z3 = 3,
};
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Origin: Misra Guidelines - Rule 32
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-3
The underlying bit representations of floating point numbers shall not be used [JSF-147-2]
DESCRIPTION
The underlying bit representations of floating point numbers shall not be
used
in any way by the programmer.
BENEFITS
Prevents from casting with possible data losing.
EXAMPLE
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
long * pl;
pi
pi
ps
pl
=
=
=
=
(int*)pf;
(int*)pd;
(short*)pf;
(long*)pf;
/*
/*
/*
/*
Violation
Violation
Violation
Violation
REPAIR
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
pf = (float*)pd;
ps = (short*)pi;
}
/* OK */
/* OK */
*/
*/
*/
*/
REFERENCES
1. Origin: Misra Guidelines - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.17 Types, AV Rule 147
Enumeration types shall be used instead of integer types (and constants) as case labels [JSF148-2]
DESCRIPTION
Enumeration types shall be used instead of integer types (and constants)
to
select from a limited series of choices. Rule reports a violation message
if integer types (constants) are used as case labels.
SINCE
v7.1
EXCEPTIONS
This rule is not intended to exclude character constants (e.g. 'A', 'B'
etc.)
from use as case labels.
BENEFITS
Enhances debugging, readability and maintenance.
Note that a compiler flag (if available) should be set to generate a
warning
if all enumerators are not present in a switch statement.
EXAMPLE
void foo(int color)
{
switch(color)
{
case 1:
break;
case 2:
break;
case 3:
break;
// Violation
// Violation
// Violation
default:
break;
}
}
REPAIR
enum color
{
RED = 1,
BLUE = 2,
GREEN = 3
};
void foo(int color)
{
switch(color)
{
case RED:
break;
case BLUE:
break ;
case GREEN:
break;
default:
break;
}
}
// OK
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 148
Octal constants (other than zero) and octal escape sequences shall not be used [JSF-149-2]
DESCRIPTION
"Any integer constant beginning with a '0' (zero) is treated as octal.
So there is a danger, for example, with writing fixed length constants.
Octal escape sequences can be problematic because the inadvertent
introduction of a decimal digit ends the octal escape and introduces
another character. It is better not to use octal constants or escape
sequences at all and to statically check for any occurrences.
The integer constant zero (written as a single numeric digit) is, strictly
speaking, an octal constant, but is a permitted exception to this rule.
Additionally \0 is the only permitted octal escape sequence."
EXCEPTIONS
Rule ignores any #pragma parasoft / codewizard directives.
Rule ignores any values inside asm blocks.
BENEFITS
Rule increases readability and maintainability.
Rule prevents using implementation-defined values.
EXAMPLE
void foo()
{
int code1;
int code2;
int code3;
code1 = 052;
/* Violation */
code2 = 071;
/* Violation */
code3 = '\100'; /* Violation */
}
REPAIR
void foo1()
{
int code1;
int code2;
int code3;
code1 = 42;
code2 = 57;
code3 = 64;
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 7
2. Origin: Misra Guidelines - Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 149
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-2
SINCE
v7.1
BENEFITS
Improved readability and maintenance.
EXAMPLE
int i = 0x3fff;
// Violation
REPAIR
int i = 0x3FFF;
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 150
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4
NOTES
We excluded using literal constants in initialization.
We also skip usage of 0 or 1 because they are equivalent of true or false.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void boo(int);
int foo( int a[], int b ) {
int e;
int f = 0;
a[5] = 56; // Violation
e= 8;
// Violation
boo(56);
// Violation
return 8; // Violation
}
REPAIR
const int MAX = 8;
// OK
void boo(int);
int foo( float a[], float b ) {
int e;
int f = 0;
// OK
int i = 5;
// OK
a[i] = MAX;
e = MAX;
boo(a[5]);
return MAX;
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151
SINCE
v7.1
BENEFITS
The effect of attempting to modify a string literal is undefined.
EXAMPLE
void moo(char * p)
{
}
void foo()
{
char* c1 = "Hello";
char c2[] = "Hello";
char c3[6] = "Hello";
char* c12;
c12 = "Hello";
moo("Hello");
}
// Violation
// Violation
// Violation
// Violation
// Violation
REPAIR
void moo(const char * p)
{
}
void foo()
{
// OK
// OK
// OK
// OK
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Multiple variable declarations shall not be allowed on the same line [JSF-152-2]
DESCRIPTION
Rule triggers if some variables are declared on the same line.
See also: FORMAT-33
NOTES
Violation is not reported if variables are declared by macros.
BENEFITS
Rule increases readability and prevents confusion.
EXAMPLE
void foo( ) {
int a, b;
}
// Violation
REPAIR
void foo( ) {
int a;
int b;
}
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.19 Variables, AV Rule 152
Note:
Rule reports a violation message on each union's declaration.
BENEFITS
Rule prevents undefined behaviour and erroneous code.
EXAMPLE
union U {
/* Violation */
int _i;
char _buf[ sizeof( int ) ];
};
REPAIR
Do not use union.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 97
3. Origin: Misra Guidelines - Rule 109
Bit fields shall only be defined to be of type unsigned int or signed int [JSF-154-2]
DESCRIPTION
"Bit fields shall only be defined to be of type unsigned int or signed
int.
Using int is implementation-defined because bit fields of type int can be
either signed or unsigned. The use of enum, short or char types for bit
fields
is not allowed because the behaviour is undefined."
BENEFITS
Prevents implementation-defined behaviour.
EXAMPLE
enum Enum { E1, E2};
struct Struct
{
unsigned char f1:2;
unsigned short f2:2;
unsigned long f3:2;
enum Enum
f4:2;
int
f5:2;
};
/*
/*
/*
/*
/*
Violation
Violation
Violation
Violation
Violation
REPAIR
struct Struct
{
unsigned int
unsigned int
unsigned int
signed int
signed int
};
REFERENCES
f1:2;
f2:2;
f3:2;
f4:2;
f5:2;
/*
/*
/*
/*
/*
OK
OK
OK
OK
OK
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
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
REFERENCES
1. Origin:
The right-hand operand of a logical && or || operator shall not contain side effects [JSF-157-2]
DESCRIPTION
"There are some situations in C or C++ where certain parts of expressions
may
not be evaluated. If these sub-expressions contain side effects then those
side
effects may or may not occur, depending on the values of other sub
expressions.
The operators which can lead to this problem are && and || where the
evaluation
of the right-hand operand is conditional on the value of the left-hand
operand.
The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
See also: MISRA2004-12_2_a, MISRA2004-12_4_b
NOTES
Rule checks only three nested level of function calls.
BENEFITS
Rule prevents conditional evaluation of the right-hand operand that can
easily
cause problems if the developer relies on a side effect occurring.
EXAMPLE
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i++)) ; // Violation
}
REPAIR
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i)) i++; // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 33
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 157
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-14-1
5. ISO/DIS 26262
point 8.4.4
SINCE
v7.3
EXCEPTIONS
"Where an expression consists of either a sequence of only logical '&&'
or a sequence of only logical '||', extra parentheses are not required.
BENEFITS
"The effect of this rule is to require that operands are appropriately
parenthesized."
EXAMPLE
int foo( int x, int y, int z )
{
if ( x || y && z );
// Violation
if ( x && !y );
// Violation
return 0;
}
REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
if ( x && ( !y ) );
// OK
// OK
return 0;
}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-1
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 158
BENEFITS
Overloading these operators changes the way the compiler reads the
semantics of an expression, resulting in unpredictable program behavior.
EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
~A( );
int value( ) { return _i; }
private:
int _i;
};
int operator&&( A& lhs, A& rhs ) {
return lhs.value( ) && rhs.value( );
}
// Violation
REPAIR
Do not overload operator &&, || or ,(comma).
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
Assignment operators shall not be used in expressions that yield a Boolean value [JSF-160-2]
DESCRIPTION
"No assignments are permitted in any expression which is considered to
have a
Boolean value. This precludes the use of both simple and compound
assignment
operators in the operands of a Boolean-valued expression. However, it does
not
preclude assigning a Boolean value to a variable. If assignments are
required
in the operands of a Boolean-valued expression then they must be performed
separately outside of those operands. This helps to avoid getting "=" and
"=="
confused, and assists the static detection of mistakes."
NOTES
An expression is considered to represent a Boolean value either because
it appears in a position where a Boolean value is expected or because it
uses an operator that gives rise to a Boolean value. Boolean values are
expected in the following contexts:
- the controlling expression of an if statement
- the controlling expression of an iteration statement
- the first operand of the conditional operator ?
BENEFITS
Rule prevents getting "=" and "==" confused.
EXAMPLE
void foo()
{
int x;
int y;
int z;
z = !(x = y);
if ((x > y) && (x = 4));
// Violation
// Violation
if (!(x = y));
// Violation
REPAIR
void foo()
{
int x;
int y;
int z;
z = !(x == y);
// OK
if ((x > y) && (x == 4)); // OK
if (!(x == y));
// OK
}
REFERENCES
1. Misra Guidelines - Rule 35
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 160
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-1
Avoid implicit conversions between signed and unsigned integer types [JSF-162_a-2]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used.
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = u32a;
s32b = s32a + u32a;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = (signed int)u32a;
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4
Avoid implicit conversions between signed and unsigned integer types [JSF-162_b-2]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used
when variables are initialized.
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = u32a;
}
/* Violation */
REPAIR
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = (signed int)u32a;
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4
Use explicit type conversions for arithmetic using signed and unsigned values [JSF-162_c-2]
DESCRIPTION
"Mixing signed and unsigned values is error prone as it subjects
operations
to numerous arithmetic conversion and integral promotion rules."
The rule reports a violation if one operand of arithmetic binary
expression
is signed type and other is unsigned type. A violation is reported only if
both operands are non constant expressions.
The following binary arithmetic operators are checked:
'+', '-', '*', '/', '%', '^', '&', '|', '>>', '<<',
'+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '>>=', '<<='
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
void foo(signed char a, unsigned char b)
{
unsigned char c = a + b;
}
// Violation
REPAIR
void foo(signed char a, unsigned char b)
{
unsigned char c = (unsigned char)a + b;
}
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 8
2. Misra Guidelines - Rule 48
SINCE
v7.1
BENEFITS
Over time, unsigned values will likely be mixed with signed values what
is error prone as it subjects operations to numerous arithmetic
conversion and integral promotion rules.
EXAMPLE
void foo(unsigned p)
{
unsigned int a = 0;
int b = 0;
b = p + a;
// Violation
REPAIR
void foo(signed p)
{
signed int a = 0;
int b = 0;
b = p + a;
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 163
The right-hand operand of a shift operator shall lie between zero and one less than the width
in bits of the underlying type of the left-hand operand [JSF-164-2]
DESCRIPTION
"If, for example, the left-hand operand of a left-shift or right-shift is
a
16-bit integer, then it is important to ensure that this is shifted only
by a
number between 0 and 15 inclusive.
There are various ways of ensuring this rule is followed. The simplest is
for
the right-hand operand to be a constant (whose value can then be
statically
checked). Use of an unsigned integer type will ensure that the operand is
non-negative, so then only the upper limit needs to be checked
(dynamically at
run-time or by review). Otherwise both limits will need to be checked."
The rule checks right-hand operand of shift operator and reports a
violation
in following cases:
- the operand is a constant with negative value or with value that exceeds
the length (in bits) of the left-hand operand
- the operand is a non-const variable and it's value is not checked by
specific
pattern.
The specific pattern recognized by the rule requires the shift operator
to be wrapped by an 'if' statement which checks the variable's value
using
comparison operators (both "greater then" and "less then" operators must
be used).
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
uint8_t;
uint16_t;
{
uint8_t u8a;
u8a = (uint8_t) (u8a << 9); /* Violation */
u8a = (uint8_t) (u8a << p); /* Violation */
}
REPAIR
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
{
uint8_t u8a;
uint16_t u16a;
uint8_t;
uint16_t;
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-8-1
The left-hand operand of a right-shift operator shall not have a negative value [JSF-164.1-2]
DESCRIPTION
The rule reports a violation message if as left-hand operand of rightshift
operator is used one from the following options:
- constant with a negative value
- unary operator '-' followed by parameter, variable or expression
- parameter or variable of signed type
- expression of signed type that contains parameter, variable,
dereferenced
pointer or function call of signed type
SINCE
v7.1
BENEFITS
Rule prevents implementation-defined behaviours.
"For e1 >> e2, if e1 has a signed type and a negative value, the value
of (e1 >> e2) is implementation-defined."
EXAMPLE
void foo(signed int signed_param)
{
signed int signed_variable;
int variable;
signed int* ptr_signed_variable;
signed_param >> 5;
signed_variable >> 5;
-variable >> 5;
-100 >> 5;
-100u >> 5;
*ptr_signed_variable >> 5;
}
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
REPAIR
void foo(unsigned int unsigned_param)
{
unsigned int unsigned_variable;
int variable;
unsigned int* ptr_signed_variable;
unsigned_param >> 5;
unsigned_variable >> 5;
(unsigned int)variable >> 5;
100 >> 5;
100u >> 5;
*ptr_signed_variable >> 5;
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The unary minus operator shall not be applied to an expression whose underlying type is
unsigned [JSF-165-2]
DESCRIPTION
"Applying the unary minus operator to an expression of type unsigned int
or
unsigned long generates a result of type unsigned int or unsigned long
respectively and is not a meaningful operation. Applying unary minus to an
operand of smaller unsigned integer type may generate a meaningful signed
result
due to integral promotion, but this is not good practice."
BENEFITS
Prevents unexpected result due to integral promotion.
EXAMPLE
void foo() {
unsigned char ui1;
signed short si2;
si2 = -ui1;
}
// Violation
REPAIR
void foo() {
unsigned char ui1;
signed short si2;
si2 = -(signed short) ui1;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
The sizeof operator shall not be used on expressions that contain side effects [JSF-166-3]
DESCRIPTION
"A possible programming error in C is to apply the sizeof operator to an
expression and expect the expression to be evaluated. However the
expression
is not evaluated: sizeof only acts on the type of the expression. To avoid
this
error, sizeof shall not be used on expressions that contain side effects,
as the side effects will not occur."
"The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
NOTES
Rule checks only three nested level of function calls.
EXCEPTIONS
An operand of the form sizeof(i) where i is volatile is permitted.
BENEFITS
Prevents error that are caused by believing that operand of sizeof is
evaluated.
EXAMPLE
int glob;
int fun_with_se(){
glob++; // side-effect
return glob;
}
void foo1(int i){
int j, k, l, m;
j = sizeof(k = 2);
// Violation - k is not set to 2
l = sizeof(i++);
// Violation - i is not incremented
m = sizeof(fun_with_se()); // Violation - glob is not incremented
}
REPAIR
int fun_without_se(){
// no side-effect
return 1;
}
void foo1(int i){
int j, k, l, m, n, o;
volatile int vol;
k = 2;
j = sizeof(k);
i++;
l = sizeof(i);
// examples of correct code
m = sizeof(fun_without_se());
n = sizeof(int);
o = sizeof(vol);
}
// OK
// OK
// OK
// OK
// OK - volatile objects are permitted
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 166
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-4
BENEFITS
Prevents unexpected loss of data/precision.
EXAMPLE
void foo()
{
int i=2;
int j=3;
int k;
k=j/i;
REPAIR
void boo()
{
int i=2;
int j=3;
int k;
/*
REFERENCES
1. Origin: Misra Guidelines - Rule 41
The comma operator shall not be used, except in the control expression of a for loop [JSF168_a-2]
DESCRIPTION
"Use of the comma operator in situations other than the control
expression
of a loop is generally detrimental to the readability of code, and the
same
effect can be achieved by other means"
See also: misra2004-12_10
BENEFITS
Extensive use of comma operator reduces readability.
EXAMPLE
void foo1( int x, int y )
{
int i;
i = (x = 1, y = 0);
x++, y++;
for (i = 0; i < 10; i++){
foo1( (x--, y + 2), y );
}
}
// Violation
// Violation
// Violation
REPAIR
void foo2( int x, int y ) {
int i;
x++;
y++;
for (i = 0; i >=0, i < 10; i++){
}
x--;
foo2( y + 2, y );
}
// OK
// OK
// OK
REFERENCES
1. Origin: Misra Guidelines - Rule 42
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 168
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int x, y;
x = 0, y = 0;
}
// Violation
REPAIR
void foo() {
int x, y;
x = 0;
y = 0;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-18-1
EXCEPTIONS
"One exception to this rule is represented by functions which provide
interfaces to other languages (such as C). These are likely to only allow
pre-defined data types to be used as arguments in the interface, in which
case pointers to pointers are needed. Another example is the second
argument
to the main function, which must have the type char*[]."
BENEFITS
Rule improves the readability of the code and encourages data abstraction.
EXAMPLE
void foo() {
int** a; // Violation
}
REPAIR
Instead, declare a class that has
a member variable of the pointer type.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#12
From: 12 Pointers and References - Rec. 48
BENEFITS
The rule prevents undefined behaviours.
EXAMPLE
#include <errno.h>
int err_check( ) {
errno = 1;
return (errno);
}
/* Violation */
/* Violation */
REPAIR
Do not use errno.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 119
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 17
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 19, Rule 19-3-1
The declaration of objects should contain no more than 2 levels of pointer indirection [JSF170_a-2]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int * INTPTR;
struct s {
int *** s3;
};
struct s *** ps3;
int ** (***pfunc3)();
int *** ( **pfunc4)();
void function( int * par1,
int *** par3,
INTPTR * const * const par5
)
{
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4
The declaration of objects should contain no more than 2 levels of pointer indirection [JSF170_b-2]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int* apInt[] ;
apInt* rule12;
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4
>, >=, <, <= shall not be applied to pointer types except where they point to the same array
[JSF-171-2]
DESCRIPTION
"Attempting to make comparisons between pointers will produce undefined
behaviour."
NOTES
"It is permissible to address the next element beyond the end of an array,
but accessing this element is not allowed."
EXCEPTIONS
"Both operands are of the same type and point to the same array"
BENEFITS
Rule makes the code more readable and less confusing.
DRAWBACKS
For more complex code rule may not be able to check if there is
applied pointer comparison to pointers which point the same array.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
}
=
=
=
=
=
a; i
p1;i
p2;i
p3;i
p4;i
=
=
=
=
=
p1
p2
p3
p4
p5
<
<
<
<
<
a;
a;
a;
a;
a;
//
//
//
//
//
OK
OK
OK
Violation - false positive
Violation - false positive
EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 < p2;
i = p2 < a;
i = p3 < a;
// Violation
// Violation
// OK
REPAIR
Do not apply pointer comparison to pointers that address elements
of different arrays
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 103
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 171
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-18
The address of an object with automatic storage shall not be assigned to another object that
may persist after the first object has ceased to exist [JSF-173-2]
DESCRIPTION
"If the address of an automatic object is assigned to another automatic
object
of larger scope, or to a static object, or returned from a function then
the
object containing the address may exist beyond the time when the original
object
ceases to exist (and its address becomes invalid). For example:
int * foo( void ) {
int local_auto;
return (&local_auto);
}"
BENEFITS
Prevents loss of data
EXAMPLE
int* global;
int* foo() {
int iLocal;
static int* siLocal;
siLocal = &iLocal;
global = &iLocal;
return &iLocal;
}
void goo() {
int* piLocal;
{
int iiLocal;
piLocal = &iiLocal;
}
}
// Violation
// Violation
// Violation
// Violation
REPAIR
Do not assign local address of object to more global,
or static object or return from function.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 106
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 173
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-2
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
BENEFITS
Complying with this rule leads to safer code.
EXAMPLE
struct S{
int si;
};
struct S* ret_ptr(struct S* p){
return p;
}
void func(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
/* here pointer 's' should be checked */
s->si = i;
/* Violation - pointer 's' may be null */
}
REPAIR
struct S{
int si;
};
struct S* ret_ptr(struct S* p){
return p;
}
int check(struct S* p){
if(p == 0)
return 0;
if(p > 0)
return 1;
}
void func1(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(s){
s->si = i;
/* OK - pointer 's' was checked in 'if' condition */
}
}
void func2(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(!s){
return;
}
s->si = i;
/* OK - pointer 's' was checked in 'if' condition */
}
void func3(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(check(s)){
s->si = i;
/* OK - pointer 's' was checked in 'check' function */
}
}
void func4(int i){
struct S* s;
struct S* ptr;
s = ret_ptr(ptr);
if(s == 0){
s->si = i;
/* OK - pointer 's' was checked in 'if' condition.
The 'if' condition is not correct, but the rule
does not check such cases. To detect this issue
could be used Bug Detectiv rule - BD-PB-NP */
}
}
REFERENCES
1. Origin: Misra Guidelines - Rule 107
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 174
3. http://cwe.mitre.org/data/definitions/476.html
4. ISO/DIS 26262
point 8.4.4
Do not compare a pointer to NULL or assign NULL to a pointer; use 0 instead [JSF-175-2]
DESCRIPTION
This rule detects code that compares a pointer to NULL or assigns NULL
to a pointer. "Do not compare a pointer to NULL or assign NULL to a
pointer; use 0 instead."
BENEFITS
According to the ANSI-C standard, NULL is defined either as (void*)0 or as
0.
If this definition remains in ANSI-C++, problems may arise.
If NULL is defined to have the type void*, it cannot be assigned an
arbitrary
pointer without an explicit type conversion.
EXAMPLE
#include <stddef.h>
void foo( ) {
int *lp = NULL; // Violation
}
REPAIR
#include <stddef.h>
void foo( ) {
int *lp = 0; // OK
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rule 42
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 175
Use a typedef to simplify program syntax when declaring function pointers [JSF-176-3]
DESCRIPTION
"Use a typedef to simplify program syntax when declaring function
pointers."
BENEFITS
"Another reason to use typedef is that the readability of the code is
improved.
If pointers to functions are used, the resulting code can be almost
unreadable.
By making a type declaration for the function type, this is avoided."
EXAMPLE
void (*p)();
// Violation
REPAIR
typedef void (*PTF)();
PTF p;
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 12 Pointers and References - Rec. 49
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 176
BENEFITS
Generally improves runtime performance and predictability of program
behavior. May detect severe coding defects masked by the compiler.
EXAMPLE
class A {
public:
operator const char*( ) const;
};
// Violation
void foo(){
A a;
const char* ch_ptr = a; // implicit conversion
}
REPAIR
class A {
public:
const char* asPointerToConstChar( ) const; // OK
};
void foo(){
A a;
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 5
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 177
BENEFITS
Allowing casts down the inheritance hierarchy leads to maintenance
problems,
and downcasting from a base class is always illegal.
EXAMPLE
class Base {};
class Derived: public Base {};
class Derived2: public Derived {};
void foo() {
Base *pb;
Derived *pd = (Derived *) pb;
Base *pb2;
Derived *pd2 = (Derived2 *) pb2;
// Violation
// Violation
REPAIR
class Base {};
void foo() {
Base *pb0;
Base *pd0 = (Base *) pb0;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of
dynamic_cast [JSF-179-2]
DESCRIPTION
"Since the virtualness of inheritance is not a property of a base class,
the layout of a derived class object, referenced through a virtual base
pointer, is unknown at compile time."
"Casting from a virtual base to a derived class, using any means
other than dynamic_cast has undefined behaviour.
The behaviour for dynamic_cast is defined."
See also: OOP-29, OOP-49
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviours.
EXAMPLE
// The code is not compilable with all compilers
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = static_cast<D*>(pB); // Violation
}
REPAIR
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = dynamic_cast<D*>(pB);
}
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 179
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
// Violation - The macro offsetof shall not be used. Macro is in line:
[10]
#include <stddef.h>
struct S {
int x, y, z;
char buffer[ 128 ];
};
int main( ) {
int i = offsetof( struct S, buffer );
return 0;
}
REPAIR
Do not use offsetof.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
Implicit conversions which may result in a loss of information shall not be used [JSF-180_a-2]
DESCRIPTION
"C performs many type conversions implicitly and silently, so as to
harmonize
types within an expression before evaluating it. Some of these conversions
can
result in loss of information. Such implicit conversions shall not be
used,
but explicit casts should be used instead."
The rule reports a violation if a parameter/variable/expression of
integral
or floating type is implicitly cast to a narrower type.
See also: MISRA2004-10_1_b, MISRA2004-10_2, PORT-27, PORT-28
NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
float < double < long double
The rule assumes that the size of enumeration type is the same as int
type.
EXCEPTIONS
The rule does not report violation if a conversion is used:
- on a constant expression
- between integral and floating type
- between signed and unsigned type
- on a bit field
BENEFITS
"Explicit casts should normally only be used in the case where a
conversion
which could result in a loss of information is specifically required by
the
programmer. If the static checking of implicit conversions is overridden
by
the use of explicit casts in this way, then the programmer should be aware
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
REFERENCES
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
float f32a;
unsigned int u32a;
f32a = u32a;
f32a = f32a + u32a;
f32a = u32a + 2.5f;
}
REPAIR
void Conv1_int( ) {
float f32a;
unsigned int u32a;
/* Violation */
/* Violation */
/* Violation */
f32a = (float)u32a;
f32a = f32a + (float)u32a;
f32a = (float)u32a + 2.5f;
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
u32a = u32b + u16b + u16a;
u32a = u16b + (u16a + u32b);
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
The underlying type of an integer constant is determined according
to its magnitude and signedness.
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = u32a;
u8a = u32a;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = (unsigned short)u32a;
u8a = (unsigned char)u32a;
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
unsigned int Conv_ret1( signed char a )
{
return a;
/* Violation */
}
REPAIR
unsigned int Conv_ret1( signed char a )
{
return (unsigned int)a;
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double(si);
/* Violation */
takes_unsigned_int(uc);
/* Violation */
takes_signed_int(ui);
/* Violation */
}
REPAIR
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double((double) si);
takes_unsigned_int(ui);
takes_signed_int((int) ui);
}
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4
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
BENEFITS
Simplifies code, protects from errors.
EXAMPLE
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = (Base *)d;
}
class Base1 {
int f();
};
class Base2 {
int f();
};
};
// Violation
// Violation
REPAIR
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = d;
}
};
// OK - cast removed
class Base1 {
int f();
};
class Base2 {
int f();
};
class Derived1 : public Base1, public Base2 { };
int Func1() {
Derived1 *d = new Derived1();
return d->Base1::f();
// OK - scope operator used
}
class Child1 : public Base1 {};
class Child2 : public Base1 {};
void foo(Child1* c1, Child2* c2, bool b) {
Base1* p = 0;
if (b) {
p = c1;
// OK - code rewritten
} else {
p = c2;
// OK - code rewritten
}
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 181
EXCEPTIONS
The rule allows to cast to UINT_PTR or INT_PTR type. These types are
integral
types that scale to the size of a pointer for both 32-bit and 64-bit
Windows.
BENEFITS
Prevents undefined or implementation-defined behaviour.
EXAMPLE
void foo( ) {
int* pi;
int i;
i = (int) pi;
}
// Violation
REPAIR
Do not cast pointers to non-pointers.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
2. Misra Guidelines rule 45
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 7
4. http://msdn2.microsoft.com/en-gb/library/aa489560.aspx
5. http://www.codeproject.com/system/64BitOSAndPortingIssues.asp
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
7. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-9
8. ISO/DIS 26262
point 8.4.4
EXCEPTIONS
The rule allows to cast integer constant '0' to pointer type.
BENEFITS
Rule prevents undefined or implementation-defined behaviour.
EXAMPLE
void foo( ) {
int* pi;
int i;
pi = (int*)i;
}
// Violation
REPAIR
Do not cast non-pointers to pointers.
REFERENCES
1. Origin: Misra Guidelines rule 45
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
4. ISO/DIS 26262
point 8.4.4
NOTES
Rule is limited to primitive types only.
EXCEPTIONS
Explicit type conversions may be used to convert a pointer to a base class
to a pointer of a derived class.
Explicit type conversion must be used to convert an anonymous bit-stream
to an object.
Generally, explicit type conversions are needed for reading an external
representation of an object.
BENEFITS
Rule improves clarity and maintainability of code.
EXAMPLE
void foo( ) {
const int ci = 0;
int i;
i = (int) ci;
// Violation
i = (int) &i;
// Violation
}
REPAIR
Do not use casts.
REFERENCES
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}
REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
// Violation
// Violation
// Violation
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a
=
=
=
=
f32a;
f32a;
f64a;
f32b + f32a + f64b;
REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
//
//
//
//
Violation
Violation
Violation
Violation
u32b
s32b
f32a
f64a
=
=
=
=
(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
BENEFITS
"Programs that use the new casts are easier to parse
(both for humans and for tools), and they allow compilers
to diagnose casting errors that would otherwise go undetected."
EXAMPLE
void foo1(){
int i, j;
double d = (double)i/j;
}
// Violation
class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = (Derived*)b;
// Violation
REPAIR
void foo1(){
int i, j;
double d = static_cast<double>(i)/j;
}
// OK
class Base {
Base( );
virtual ~Base( );
};
class Derived : public Base {};
void foo2(){
Base* b;
Derived* d;
d = dynamic_cast<Derived*>(b);
}
// OK
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Basics", Item 2
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 95
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 185
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo(int a, int b)
{
if(a == a){
a = a + b;
}
else{
// Violation
a = a - b;
}
}
REPAIR
void foo(int a, int b)
{
if(a == 3){
a = a + b;
}
else{
a = a - b;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
There shall be no unreachable code after 'return', 'break', 'continue', and 'goto' statements
[JSF-186_b-2]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code after 'return', 'break',
'continue' and 'goto' statements.
See also: MISRA2004-14_1_a, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// Violation
foo();
case 2:
j = 3;
return j; // Violation
foo();
}
}
REPAIR
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// OK
case 2:
j = 3;
return j; // OK
}
foo();
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo()
{
int unreachable_code = 1;
if(0)
{
unreachable_code = 2;
}
}
// Violation
REPAIR
There shall be no unreachable code
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo( int i ) {
switch (i) {
// Violation
i = 0;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}
REPAIR
void foo( int i ) {
switch (i) {
// OK
case 0:
i = 0;
break;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo( int i, int j )
{
for ( i = 0; i < 0; i++ )
{
j = 1;
}
}
// Violation
REPAIR
void foo( int i, int j )
{
for ( i = 0; i < 5; i++ )
{
j = 1;
}
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
NOTES
This rule does not report violations on the code inside loop.
Rule MISRA2004-14_1_g reports violations on the code inside loop.
BENEFITS
Rule helps avoid useless code.
EXAMPLE
int foo1( int c ) {
if ( c > 2 ) {
// Violation
return 0;
} else {
return 1;
}
return c;
// unreachable code
}
int foo2( int i ) {
switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return 2;
}
return i;
}
// Violation
// unreachable code
REPAIR
int foo1( int
if ( c > 2
return
} else {
return
}
}
c ) {
) {
0;
// OK
c;
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
There shall be no unreachable code after "if" or "switch" statement inside while/for/do...while
loop [JSF-186_g-2]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation on the code inside loop if:
- the code is after 'if/else' construction, where each branch has
unconditional
'break', 'continue' or 'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_f
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
int foo( int c ) {
while ( c > 1 ) {
if ( c > 2 ) {
continue;
} else {
break;
}
// Violation
c++;
// unreachable code
}
for (int i = 0; i > 1; i++ ) {
switch(i){
// Violation
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}
c++;
// unreachable code
}
return c;
}
REPAIR
int foo( int c ) {
while ( c > 1 ) {
c++;
if ( c > 2 ) {
continue;
} else {
break;
}
}
// OK
}
return c;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
All non-null statements shall either have at least one side-effect however executed or cause
control flow to change [JSF-187-2]
DESCRIPTION
"Any statement (other than a null statement) which has no side effect and
does
not result in a change of control flow will normally indicate a
programming
error, and therefore a static check for such statements shall be
performed."
A side effect and null statement are defined by ISO/IEC 9899:1999
standard.
"Accessing a volatile object, modifying an object, modifying a file,
or calling a function that does any of those operations are all side
effects,
which are changes in the state of the execution environment."
"A null statement (consisting of just a semicolon) performs no
operations."
For example, if an expression evaluation result is not used, because
a programmer forgot to use assignment operator to store the value,
or because he accidentally wrote "==" instead of "=", the statement
is considered not to have a side effect. Such programming errors
are potentially disastrous.
NOTES
Empty function body is not considered as violating this rule.
For purposes of this rule any function call is considered as
having side effects, even if no variable is modified as a result
of the function call.
The rule does not report violations on empty blocks.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
struct tagStruct {
int _iField;
char * _p;
};
int bar( );
void foo( ) {
int i = 0;
struct tagStruct s, *ps;
/* Examples of incorrect code - no side effects: */
i + 3;
/* Violation - result not
3;
/* Violation - result not
i;
/* Violation - result not
i + bar();
/* Violation - result not
ps->_p + s._iField;
/* Violation - result not
ps->_iField << s._iField; /* Violation - result not
*(ps->_p);
/* Violation - result not
}
used
used
used
used
used
used
used
REPAIR
struct tagStruct{
int _iField;
char * _p;
};
volatile struct tagStruct volStr;
int bar( );
void foo( ) {
int i = 0;
volatile int j = 0;
struct tagStruct s, *ps;
/* Examples of correct code - with side effects: */
i = i + 3;
/* OK - assignment */
i <<= 3;
/* OK - assignment */
bar();
/* OK - function call */
j;
/* OK - volatile variable */
volStr._p;
/* OK - volatile variable */
*/
*/
*/
*/
*/
*/
*/
if(ps->_iField){}
;
{}
/* OK - null statement */
/* OK - empty block */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
system
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 53
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 187
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
BENEFITS
The goto statement can lead to errors and confusion.
EXAMPLE
int foo( int a ) {
if (a < 0) {
goto end;
}
a = foo(a-1);
end:
return a+1;
}
/* Violation */
REPAIR
int foo( int a ) {
/* Code was changed and does not use goto anymore */
if (a >= 0) {
a = foo(a-1);
}
return a+1;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 49
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
BENEFITS
Rule prevents using 'continue' which can lead to errors and confusion.
EXAMPLE
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
continue;
}
i /= 2;
}
}
/* Violation */
REPAIR
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
/* OK - code was changed and does not use continue anymore */
} else {
i /= 2;
}
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rec. 53
3. Origin: Misra Guidelines - Rule 57
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 190
5. ISO/DIS 26262
point 8.4.4
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
BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.
EXAMPLE
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
}
// Violation
REPAIR
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
// OK
else
{
// comment or action
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 60
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 192
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-2
An unconditional break statement shall terminate every non-empty switch clause [JSF-193-2]
DESCRIPTION
"The last statement in every switch clause shall be a break statement,
or if the switch clause is a compound statement, then the last statement
in the compound statement shall be a break statement."
NOTES
This rule allows also to use return instead break statement.
BENEFITS
Prevents unpredictable program behaviour.
EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
case 2 :
{
i = 3;
}
default:
i = 8;
}
}
// Violation
// Violation
// Violation
// Violation
REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
break;
}
}
// OK
// OK
// OK
// OK - empty case
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Misra Guidelines - Rule 61
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 47
BENEFITS
Rule prevents possibility of erroneous code.
EXAMPLE
void foo( ) {
int tag;
switch ( tag ) {// Violation
case 0: {
break;
}
case 1: {
foo( );
break;
}
}
}
REPAIR
void foo( ) {
int tag;
switch ( tag ) {// OK
case 0: {
break;
}
case 1: {
foo( );
break;
}
default: break;
}
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 48
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 194
A switch expression shall not represent a value that is effectively Boolean [JSF-195-3]
DESCRIPTION
Values which are effectively Boolean should not be represented in
'switch' condition.
The rule forbids following operators:
a) equality operators (== and !=)
b) logical operators (!, && and ||)
c) relational operators (<, >, <= and >=)
which produce boolean-by-construct values.
BENEFITS
Rule prevents using values that are effectively Boolean in switch.
EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}
// Violation
REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}
REFERENCES
// OK
Every switch statement will have at least two cases and a potential default [JSF-196-3]
DESCRIPTION
Every switch statement will have at least two cases and a potential
default.
See also: CODSTA-41, MISRA2004-15_5
SINCE
v7.1
BENEFITS
An if statement provides a more natural representation.
EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}
// Violation
REPAIR
void foo(int i)
{
switch(i)
{
case 1:
break;
case 2:
break;
default:
;
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 196
BENEFITS
Prevents giving unexpected results when the variable is tested.
EXAMPLE
void foo()
{
float i;
for (i=0.;i<10.;i++)
{
}
}
/* Violation */
REPAIR
void foo()
{
int i;
for (i=0;i<10;i++) /* OK */
{
}
}
REFERENCES
1. Origin: Misra Guidelines - Rule 65
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 197
The initialization expression in a for loop will perform no actions other than to initialize the
value of a single for loop parameter [JSF-198-3]
DESCRIPTION
The initialization expression in a for loop will perform no actions other
than
to initialize the value of a single for loop parameter.
Note that the initialization expression may invoke an accessor that
returns
an initial element in a sequence:
for (Iter_type p = c.begin() ; p != c.end() ; ++p) // Good
{
// ...
}
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo()
{
int k = 0;
/* ... */
for(; k>0; k--){}
for(int i=0, k=2; k>0; k--){}
for(int i = k+2-10; k>0; k--){}
for(k--; k>0; k--){}
}
REPAIR
//
//
//
//
Violation
Violation
Violation
Violation
class A
{
public:
int i;
int moo();
};
void foo()
{
int k = 0;
A obj;
/* ... */
for(k=2; k>0; k--){}
for(int i =0; i>0; i--){}
for(k = obj.i; k>0; k--){}
for(k = obj.moo(); k>0; k--){}
}
//
//
//
//
OK
OK
OK
OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 198
The increment expression in a for loop will perform no action other than to change a single
loop parameter to the next value for the loop [JSF-199-3]
DESCRIPTION
The increment expression in a for loop will perform no action other
than to change a single loop parameter to the next value for the loop
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo()
{
int k = 0;
for(;k>0; ){}
// Violation
for(int i=0; k>0; k--, i++){} // Violation
for(k--; k>0; k+1){}
// Violation
}
REPAIR
void zoo(){}
class A
{
public:
int i;
};
void foo()
{
int k = 0;
A obj;
for(int i = k+2-10; k>0; zoo()){}
for(k=2; k>0; k--){}
for(int i =0; i>0; i=i-1){}
for(k = obj.i; k>0; k-=1){}
//
//
//
//
OK
OK
OK
OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 199
The setjmp macro and the longjmp function shall not be used [JSF-20-2]
DESCRIPTION
"setjmp and longjmp allow the normal function call mechanisms to be
bypassed,
and shall not be used."
Rule reports a violation message if setjmp or longjmp is used and the file
includes any of the following headers: setjmp.h, setjmp, or csetjmp.
BENEFITS
Rule prevents normal function call mechanisms from being bypassed.
EXAMPLE
#include <setjmp.h>
jmp_buf mark;
int
fperr;
void foo( void ) {
int jmpret;
jmpret = setjmp( mark );
}
/* Violation */
REPAIR
Do not use the setjmp macro and the longjmp function.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 122
Null initialize or increment expressions in for loops will not be used; a while loop will be used
instead [JSF-200-3]
DESCRIPTION
Null initialize or increment expressions in for loops
will not be used; a while loop will be used instead.
Rule reports a violation message if 'for' statement
misses init or increment section.
SINCE
v7.1
BENEFITS
A while loop provides a more natural representation.
EXAMPLE
void foo()
{
for(int i=0; i< 10;) // Violation
{
/* ... */
}
int j = 0;
for(; j< 10;)
{
/* ... */
}
}
REPAIR
void foo()
{
int i = 0;
// Violation
while(i< 10)
{
/* ... */
}
// OK
int j = 0;
while(j< 10)
{
/* ... */
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 200
Do not modify for loop counter within a body of the loop [JSF-201-2]
DESCRIPTION
"Loop counters shall not be modified in the body of the loop.
However other loop control variables representing logical values
may be modified in the loop, for example a flag to indicate that something
has been completed, which is then tested in the for statement."
NOTES
A
-
BENEFITS
Modification 'for' loop counter within a body of the loop can lead to
errors and confusion.
EXAMPLE
void foo( ) {
int i;
for ( i = 0; i < 5; i++ ) {
i = i + 3;
}
}
/* Violation */
REPAIR
void foo( ) {
int i;
for ( i = 0; i < 5; i = i + 3 ) {} /* OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 67
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 201
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-5-3
NOTES
Rule does not detect indirect tests of equality and inequality which are
equally
problematic and are also forbidden by Misra standard:
if ( ( x <= y ) && ( x >= y ) )
{
/* ... */
}
BENEFITS
"The inherent nature of floating-point types is such that comparisons of
equality will often not evaluate to true even when they are expected to.
In
addition the behaviour of such a comparison cannot be predicted before
execution, and may well vary from one implementation to another. "
EXAMPLE
void foo() {
float x, y;
if (x == y);
if (x == 0.0f);
}
// Violation
// Violation
REPAIR
void foo( float epsilon ) {
float x, y;
if (x - epsilon <= y && y <= x + epsilon);
if (-epsilon <= x && x <= epsilon);
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 50
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 202
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-2
Evaluation of constant unsigned integer expressions should not lead to wrap-around [JSF203-2]
DESCRIPTION
"Because unsigned integer expressions do not strictly overflow, but
instead
wrap-around in a modular way, any constant unsigned integer expressions
which in effect 'overflow' will not be detected by the compiler."
The rule reports a violation if a result of subtraction of two integer
constants is lower than 0.
NOTES
This rule checks only simple subtractions for unsigned integer constants.
It is not possible to checks:
- expressions other than subtraction
- complex expressions
- expressions which use Macro definition or hexadecimal values
BENEFITS
Prevents from wrap-around for unsigned integer.
EXAMPLE
#if (1u - 2u) /* Violation */
/* ... */
#endif
REPAIR
Avoid wrap-around for unsigned integer.
REFERENCES
1. Origin: Misra Guidelines - Rule 51
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
BENEFITS
Rule improves efficiency and prevents error-prone code.
EXAMPLE
#include <assert.h>
void foo( ) {
int i = 0;
assert( i++ != 0 ); // Violation
assert(i=5);
// Violation
assert(false);
// Violation
}
REPAIR
#include <assert.h>
void foo( ) {
int i = 0;
assert(i != 0);
// OK
assert(!"informational message"); // OK
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
The increment (++) and decrement (--) operators should not be mixed with other operators in
an expression [JSF-204_b-2]
DESCRIPTION
"It is the intention of the rule that when the increment or decrement
operator
is used, it should be the only side-effect in the statement.
The use of increment and decrement operators in combination with other
arithmetic operators is not recommended because:
- It can significantly impair the readability of the code
- It introduces additional side effects into a statement with the
potential for
undefined behaviour
It is safer to use these operations in isolation from any other arithmetic
operators."
BENEFITS
Improves readability and maintainability.
Reduces risk of potential undefined behaviour
caused by additional side effects
EXAMPLE
void foo() {
int x, y;
x = --y + x++;
}
/* Violation */
REPAIR
void foo() {
int x, y;
--y;
x = y + x;
x++;
}
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-10
The value of an expression shall be the same under any order of evaluation that the standard
permits [JSF-204_c-2]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
As an example of what can go wrong, consider x = b[i] + i++; This will
give
different results depending on whether b[i] is evaluated before i++ or
vice
versa. The problem could be avoided by putting the increment operation
in a separate statement."
The rule reports a violation if a variable is used and
incremented/decremented
in the same statement.
See also: MISRA2004-12_4_a, MISRA2004-12_4_b
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
void foo( )
{
int a, b[10];
a = b[a] + a++; // Violation
}
REPAIR
void foo( )
{
int a, b[10];
a = b[a] + a;
a++;
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The second or third operand of a ternary operator '?:' shall not contain side effects [JSF204_d-2]
DESCRIPTION
"There are some situations in C or C++ code where certain parts of
expressions
may not be evaluated. If these sub-expressions contain side effects then
those
side effects may or may not occur, depending on the values of other
sub-expressions.
The operators which can lead to this problem are &&, || and ?:. In the
case of
the ?: operator, either the second or third operands are evaluated but not
both.
The ?: operator is specifically provided to choose between two subexpressions,
and is therefore less likely to lead to mistakes."
See also: MISRA2004-12_2_a, MISRA2004-12_4_a
NOTES
Rule checks only two nested level of function calls.
BENEFITS
Rule prevents conditional evaluation of the second or third operand of
ternary
operator that can easily cause problems if the developer relies on a side
effect
occurring.
EXAMPLE
int i;
int j;
int foo( ) {
return (i > j) ? j++ : i++; // Violation - developer expects 2nd and
3rd
// operand to be evaluated
}
REPAIR
int i;
int j;
int foo( ) {
if (i > j) {
++i;
return j++;
} else {
++j;
return i++;
}
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. ISO/DIS 26262
point 8.4.4
Don't write code that depends on the order of evaluation of function arguments [JSF-204_e-2]
DESCRIPTION
The order of evaluation of function arguments is unspecified. This means
that
if arguments contain side effects then the order in which side effects
take
place is unspecified. A function call can give different results depending
on which of the function's arguments is evaluated first.
By side effect we understand accessing a volatile object, modifying an
object
or calling a function that does any of those operations.
Rule checks calls of functions that have at least two arguments.
A violation is reported if
* a volatile object is read or modified, or
* a non-volatile object is modified
during evaluation of a function argument and the same object is read or
modified during evaluation of function's other argument.
EXCEPTIONS
Only one level of function calls is checked.
BENEFITS
Rule prevents writing source code which might produce different results
between compilers.
EXAMPLE
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
Transmogrify(Bump(count),Bump(count)); // Violation
Transmogrify(count++,count);
// Violation
}
REPAIR
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
int temp1 = Bump(count);
Transmogrify(temp1,Bump(count)); // OK
Transmogrify(count,count);
// OK
count++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 31
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
5. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
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
EXCEPTIONS
The rule allows to use a placement new.
BENEFITS
"There is a range of unspecified,
behaviour associated with dynamic
of
other potential pitfalls. Dynamic
memory
leaks, data inconsistency, memory
behaviour."
EXAMPLE
void foo()
{
int * p = new int[10]; // Violation
/* ... */
delete[] p;
// Violation
REPAIR
Do not use neither 'new' and 'delete' operators nor 'calloc', 'malloc',
'realloc' and 'free' functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Misra Guidelines - Rule 118
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-4-1
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 206
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 3
Encapsulate global variables and constants, enumerated types, and typedefs in a class [JSF207-3]
DESCRIPTION
"Encapsulate global variables and constants, enumerated types, and
typedefs
in a class. Static variables in a class should be used instead of global
variables and constants, enumerated data types, and typedefs."
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
enum Days {yesterday};
typedef int myint;
myint glob;
// Violation
// Violation
// Violation
REPAIR
class A {
public:
enum Days {yesterday};
typedef int MyInt;
static MyInt glob;
};
// OK
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 5 Assigning Names - Rec. 19
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 207
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
C++ exceptions shall not be used (i.e. throw, catch and try shall not be used.) [JSF-208-2]
DESCRIPTION
Do not use C++ exceptions.
SINCE
v7.1
BENEFITS
Rule improves portability of the code.
EXAMPLE
#include <iostream>
using namespace std;
int main()
{
char *buf;
try
// Violation
{
buf = new char[512];
if( buf == 0 )
throw "Memory allocation failure!"; // Violation
}
catch( char * str )
// Violation
{
cout << "Exception raised: " << str << '\n';
}
// ...
return 0;
}
REPAIR
#include <iostream>
// OK
return 0;
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.27 Fault Handling, AV Rule 208
typedefs that indicate size and signedness should be used in place of the basic types [JSF209-2]
DESCRIPTION
"The basic numerical types of signed and unsigned variants of char, int,
short, long, and float, double should not be used, but specific-length
typedefs should be used."
Rule reports a violation message if basic numerical type is used
( e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA-013
EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- plain char, boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)
BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."
EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
short* v_short,
float& r_float)
{
double h;
const int z = 1;
return 1;
REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
char ch;
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}
/* OK (plain char) */
/* OK (typedef name starts with 'bool'
/* OK (bit-bield type) */
/*
/*
/*
/*
/*
OK
OK
OK
OK
OK
(plain char) */
(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 18 Portable Code - 18.1 Data Abstraction - Port. Rec. 1
BENEFITS
Prevents from problems associated with implementation-defined
and undefined behaviour in signal handling.
EXAMPLE
#include <signal.h>
/* Violation */
REPAIR
Do not use <signal.h> header.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 123
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 21
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-7-1
Algorithms shall not make assumptions concerning the order of allocation of nonstatic data
members separated by an access specifier [JSF-210.1-2]
DESCRIPTION
This rule is intended to prohibit an application from making assumptions
concerning the order in which non-static data members, separated by an
access specifier, are ordered.
Rule reports a violation message if static_cast type is pointer to class
with non-static data members separated by an access specifier.
SINCE
v7.1
BENEFITS
The order of allocation of nonstatic data members, separated by an
access-specifier, is unspecified.
EXAMPLE
class A
{
protected: // a could be stored before b, or vice versa
int a;
private:
int b;
};
class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);
// Violation
// application
REPAIR
struct A
{
int a;
int b;
};
class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);
// OK
// attributes in B
not separated
// by an access
specifier
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 210.1
Limited dependence should be placed on C's operator precedence rules in expressions [JSF213_a-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
Parentheses are required for the right-hand operand because the right-hand
side itself contains an assignment expression.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int a, b;
b = a = 0;// Violation
}
REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
Limited dependence should be placed on C's operator precedence rules in expressions [JSF213_b-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it.
It is easy to make a mistake with the rather complicated precedence rules
of C,
and this approach helps to avoid such errors, and helps to make the code
easier
to read. However, do not add too many parentheses so as to clutter the
code and
make it unreadable."
"No parentheses are required for the right-hand operand of an assignment
operator unless the right-hand side itself contains an assignment
expression."
NOTES
Macro's body is excluded from checking.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int a, b;
b = (a = 0);// OK
b = (a + 0);// Violation
}
REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
b = a + 0;// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( )
{
int a, b;
b = a * (-1);
}
// Violation
REPAIR
void foo( )
{
int a, b;
b = a * -1;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
Limited dependence should be placed on C's operator precedence rules in expressions [JSF213_d-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it
unreadable."
"If all operators are the same, parentheses may be used to control the
order of
operation. Some operators (e.g. addition and multiplication) that are
associative in algebra are not necessarily associative in C. Similarly,
integer
operations involving mixed types (prohibited by several rules) may produce
different results because of the integral promotions. The following
example
written for a 16-bit implementation demonstrates that addition is not
associative and that it is important to be clear about the structure of an
expression:"
SINCE
v7.0
BENEFITS
Rule increases safety in arithmetic operations.
EXAMPLE
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
REPAIR
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus(
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a + (b
}
) {
10;
65535;
0;
+ c); /* OK d is 65545 */
void fooMultiply( ) {
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a * (b
10;
65535;
0;
* c); /* OK d is 655350 */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
Use parentheses unless all operators in the expression are the same [JSF-213_e-2]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it unreadable.
Use parentheses unless all operators in the expression are the same."
See also: MISRA2004-12_5, CODSTA-90
NOTES
The operands of a logical && and || are checked by the rule MISRA2004-12_5
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( ) {
int a, b;
b = a * a + a;
}
// Violation
REPAIR
void foo( ) {
int a, b;
b = (a * a) + a;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
SINCE
v7.0
BENEFITS
"This approach is founded on C++'s guarantee that local
static objects are initialized when the object's definition
is first encountered during a call to that function. So if
you replace direct accesses to non-local static objects
with calls to functions that return references to local
static objects, you're guaranteed that the references you
get back will refer to initialized objects. As a bonus, if you
never call a function emulating a non-local static object,
you never incur the cost of constructing and destructing
the object, something that can't be said for true non-local
static objects."
EXAMPLE
#include <iostream>
using namespace std;
class FileSystem {
public:
size_t numDisks( ) const;
};
extern FileSystem tfs;
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_tfs = tfs.numDisks( );
}
Directory tempDir( );
// Violation
REPAIR
#include <iostream>
using namespace std;
class FileSystem {
public:
size_t numDisks( ) const;
};
FileSystem& tfs_one( ) {
static FileSystem fs;
return fs;
}
class Directory {
public:
Directory( );
};
Directory::Directory( ) {
size_t disks_one = tfs_one().numDisks( );
}
Directory tempDir( );
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
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
BENEFITS
Prevents form problems associated with a large number of unspecified,
undefined and implementation-defined behaviour associated
with streams and file I/O.
EXAMPLE
#include <stdio.h>
/* Violation */
REPAIR
Do not use <stdio.h> library.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 124
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 22
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 27, Rule 27-0-1
The library functions atof, atoi and atol from library stdlib.h shall not be used [JSF-23-2]
DESCRIPTION
'atof', 'atoi' and 'atol' functions from library <stdlib.h> have undefined
behaviour associated with them when the string cannot be converted.
BENEFITS
Prevents using functions which have sometimes undefined behaviour.
EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *s; double x; int i; long l;
s = " -2309.12E-15";
x = atof( s );
/* Violation */
s = " -9885 pigs";
i = atoi( s );
/* Violation */
s = "98854 dollars";
l = atol( s );
/* Violation */
}
REPAIR
Do not use atof, atoi and atol functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 125
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 23
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
The library functions abort, exit, getenv and system from library stdlib.h shall not be used
[JSF-24-2]
DESCRIPTION
'abort', 'exit', 'getenv' and 'system' functions from stdlib.h, cstdlib,
or stdlib_iso.h libraries shall not be used.
BENEFITS
Prevents using functions which are not required in an embedded system.
EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *libvar;
libvar = getenv( "LIB" );
system( "dir" );
abort( );
exit( 0 );
}
/*
/*
/*
/*
Violation
Violation
Violation
Violation
*/
*/
*/
*/
REPAIR
Do not use abort, exit, getenv and system functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 126
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 24
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-3
The time handling functions of library time.h shall not be used [JSF-25-2]
DESCRIPTION
"This library is associated with clock times.
Various aspects are implementation dependent
or unspecified, such as the formats of times."
Rule prevents inclusion of <time.h> and <ctime> headers.
See also: SECURITY-01
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include <time.h>
/* Violation */
REPAIR
Do not include time.h header.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 127
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 25
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 18, Section 7, Rule 18-0-4
Only the following pre-processor directives shall be used: #ifndef, #define, #endif, #include
[JSF-26-2]
DESCRIPTION
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include
SINCE
v7.1
BENEFITS
Limit the use of the pre-processor to those cases where it is necessary.
EXAMPLE
#pragma once // Violation
REPAIR
#ifndef FOO_H
#define FOO_H
/* ... */
#endif
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 26
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
BENEFITS
Rule improves maintainability and optimization of code.
EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present
REPAIR
// file foo.hh
// OK
#ifndef FOO_HH
#define FOO_HH
int i;
#endif
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 27
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-3
The #ifndef and #endif pre-processor directives will only be used to prevent multiple
inclusions of the same header file [JSF-28-3]
DESCRIPTION
The #ifndef and #endif pre-processor directives will only be used
as defined in below example to prevent multiple inclusions of the
same header file.
#ifndef Header_filename
#define Header_filename
// Header declarations...
#endif
SINCE
v7.1
BENEFITS
Conditional code compilation should be kept to a minimum as it can
significantly obscure testing and maintenance efforts.
EXAMPLE
#ifndef MAX
// Violation
// Violation
int a;
REPAIR
#ifndef FOO_H
#define FOO_H
int max = 10;
int a;
// OK
#endif
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 28
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
BENEFITS
"While macros can provide a speed advantage over functions, functions
provide
a safer and more robust mechanism. This is particularly true with respect
to the type checking of parameters, and the problem of function-like
macros
potentially evaluating parameters multiple times.
See also: CODSTA-03, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40
EXAMPLE
#define SUM(A,B) ((A)+(B))
/* Violation */
REPAIR
int sum( int a, int b ) {
return (a + b);
}
void foo( int x, int y ) {
/* ... */
sum( x, y );
/* ... */
}
REFERENCES
/* OK */
SINCE
v7.1
NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 20" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for
N.
BENEFITS
Studies have found that methods with high Cyclomatic Complexity are errorprone.
EXAMPLE
void foo2(int i, int a, int b, int j, int k)
{
switch (i)
{
case 1: // 1
i++;
default:
i++;
}
switch (j)
{
case 1: // 2
j++;
default:
j++;
}
switch (k)
{
case 1: // 3
k++;
default:
k++;
}
if(a||b)
// 4, 5
{
}
if((a||b)&&(a&&b)) // 6, 7, 8, 9
{
}
do
// 10
{
}while(0);
// Violation - CC value: 21
switch (i)
{
case 1: // 11
i++;
default:
i++;
}
switch (j)
{
case 1: // 12
j++;
default:
j++;
}
switch (k)
{
case 1: // 13
k++;
default:
k++;
}
if(a||b)
// 14, 15
{
}
if((a||b)&&(a&&b)) // 16, 17, 18, 19
{
}
do
// 20
{
}while(0);
}
REPAIR
Keep a Cyclomatic Complexity value on the level lower than 20.
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 3.2 Code Size and Complexity, AV Rule 3
BENEFITS
Code is easier to debug. Prevents incorrectly macro writing.
EXAMPLE
#define PI 3.1416
// Violation
REPAIR
const float PI = 3.1416; // OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 2
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 10 Constants - Rule 36
EXCEPTIONS
Macros are almost never necessary in C++. Exceptions to this rule are:
- #ifdef
- #ifndef
- #if
- #if defined
when used as include guards and for conditional compilation.
BENEFITS
Improves code reliability and maintainability.
EXAMPLE
#define PI 3.14
// Violation
REPAIR
const double PI = 3.14; // OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
The #include pre-processor directive will only be used to include header (*.h) files [JSF-32-3]
DESCRIPTION
The #include pre-processor directive will only be used to include
header (*.h) files.
SINCE
v7.1
EXCEPTIONS
In the case of template class or function definitions, the code may be
partitioned into separate header and implementation files. In this
case, the implementation file may be included as a part of the header
file. Rule allows for mentioned exception if the implementation file
has the same name as a header file.
BENEFITS
Rule improves the clarity of code.
The only files included in a .cpp file should be the relevant
header (*.h) files.
EXAMPLE
// file.cpp
#include <file2.cpp>
#include <file3.hh>
// Violation
// Violation
// file.h
#include <file2.cpp>
#include <file3.hh>
// Violation
// Violation
REPAIR
// file.cpp
#include <file2.h>
#include <file3.h>
// file.h
#include <file.cpp>
file.cpp
#include <file2.h>
#include <file3.h>
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 32
The #include directive shall use the <filename.h> notation to include header files [JSF-33-2]
DESCRIPTION
The #include directive shall use the <filename.h> notation to include
header files.
SINCE
v7.1
BENEFITS
The include form "filename.h" is typically used to include local header
files.
However, due to the unfortunate divergence in vendor implementations, only
the <filename.h> form will be used.
EXAMPLE
#include "foo.h" // Violation
REPAIR
#include <foo.h>
// OK
#include <dir1/dir2/foo.h> // OK: relative path used
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Filess, AV Rule 33
Use mechanism that prevents multiple inclusion of the file i.e. include guards or "#pragma
once" preprocessor directive [JSF-35-3]
DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be either:
- #pragma once - preprocessor directive
or
- include guards defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-02, PFO-07, and MISRA2004-19_15
SINCE
v7.1
BENEFITS
Rule improves maintainability and optimization of code.
EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present
REPAIR
// file foo.hh
// OK
#pragma once
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 35
NOTES
As a headers rule detects files with extensions ".h", ".hh", ".hxx", ".i"
(e.g. "file.h", "file.hh", "file.hxx", "file.i").
EXCEPTIONS
The following definitions are allowed in a header file:
- inline functions
- function templates
- static data members of class templates
- const variables if they have internal or no linkage (C++ mode)
- static const variables
BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.
EXAMPLE
/* file.h */
void f1(){}
int var;
class C {
void f2();
};
// Violation
// Violation
void C::f2() {}
// Violation
/* file.cpp */
#include "file.h"
REPAIR
/* file.h */
void f1();
extern int var;
class C {
void f2();
};
template <typename T>
void f3 ( T ) { }
// OK
// OK
// OK
/* file.cpp */
#include "file.h"
void f1(){}
int var;
void C::f2() {}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-1
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 61
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 39
SINCE
v7.1
NOTES
Tab is counted as one character.
White spaces at the end of line are counted in the same way as other
characters.
Comments with 'parasoft-suppress' are not counted.
To change the default limit of characters modify the variable
'lineLengthLimit'
at the begin of python method 'check'.(e.g. 'lineLengthLimit = 100' means
that
the maximal allowed number of characters in a physical line is 100)
BENEFITS
The rule improves readability of code.
EXAMPLE
int
/*
..........................................................................
..........*/ i1 ; /* Violation */
int
/* ..........white spaces at the end of
line.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........Violation.......
*
..........................................................................
............................Violation.....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* Violation
*/
REPAIR
int
/*
..........................................................................
................*/ i1 ; /* OK */
int
/* ..........There is no spaces at the
end.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........OK......
*
..........................................................................
............................OK....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + \
xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* OK */
int
/*
..........................................................................
...............*/ i3 ; /* parasoft-suppress ITEM ... OK */
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 41
BENEFITS
This rule promotes readability and maintainability by reducing code
complexity.
EXAMPLE
void foo()
{
int i; char c; // Violation
}
REPAIR
void foo()
{
int ii; // OK
char cc;
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 42
Tabs that do not use ASCII spaces shall not be used [JSF-43-4]
DESCRIPTION
This rule checks whether you are using only ASCII white spaces as tabs.
Different operating systems, display devices, and editors handle tabs
in different ways. Code containing tabs will likely be indented
incorrectly
if ported to another environment.
BENEFITS
Rule prevents inconsistent display of code containing tabs
in different environments.
EXAMPLE
void foo()
{
int i; // Violation
}
REPAIR
void foo()
{
int j; // OK
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 43
User-specified identifiers (internal and external) will not rely on significance of more than 64
characters [JSF-46-2]
DESCRIPTION
Identifiers names consisting of more than 64 characters should not be
used.
SINCE
v7.1
BENEFITS
Rule ensures that code can be ported between the majority of
compilers/linkers
without requiring modification (shortening) of identifiers names
EXAMPLE
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam) //
Violation 65 chars
{
}
REPAIR
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam)
64 chars
{
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
// OK
Do not use identifiers which begin with one or two underscores (`_' or `__') [JSF-47-3]
DESCRIPTION
"Do not use identifiers which begin with one or two underscores (`_' or
`__')."
See also: CODSTA-92, CODSTA-93
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
void _foo( );
// Violation
REPAIR
void foo( );
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 47
Identifiers will not differ by mixture of case, the underscore character, interchange of the
similarly looking letters and numbers [JSF-48-3]
DESCRIPTION
Identifiers will not differ by:
- Only a mixture of case
- The presence/absence of the underscore character
- The interchange of the letter 'O', with the number '0' or the letter 'D'
- The interchange of the letter 'I', with the number '1' or the letter 'l'
- The interchange of the letter 'S' with the number '5'
- The interchange of the letter 'Z' with the number '2'
- The interchange of the letter 'n' with the letter 'h'.
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo(int paramS, int param5);
// Violation
REPAIR
void foo(int param1, int param2);
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 48
Only the first word of the name of a class, structure, namespace, enumeration, or typedef will
begin with an uppercase letter [JSF-50-3]
DESCRIPTION
The first word of the name of a class, structure, namespace, enumeration,
or type created with typedef will begin with an uppercase letter.
All others letters will be lowercase.
SINCE
v7.1
NOTES
If one wants to eliminate some abbreviations from checking it can be done
by
adding abbreviation string to array abb_table in rule's python method
checkNamingConvention() e.g. abb_table = ["RGB", "IBM"]
EXCEPTIONS
The first letter of a typedef name may be in lowercase if the typedef is a
class member or
when it is used as a replacement for primitive types.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class sample_Class
{
// ...
};
// Violation
REPAIR
class Sample_class
{
// ...
};
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 50
All letters contained in function and variable names will be composed entirely of lowercase
letters [JSF-51-3]
DESCRIPTION
All letters contained in function and variable names will be composed
entirely of lowercase letters.
SINCE
v7.1
EXCEPTIONS
Constructors and destructors.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class Sample_class
{
public:
int Some_function();
private:
int Some_variable;
};
// Violation
// Violation
REPAIR
class Sample_class
{
public:
int some_function();
private:
int some_variable;
};
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 51
SINCE
v7.1
BENEFITS
Although it is an accepted convention to use uppercase letters for
constants and enumerators, it is possible for third party libraries
to replace constant/enumerator names as part of the macro substitution
process (macros are also typically represented with uppercase letters).
EXAMPLE
const int Max_pressure = 100;
// Violation
enum Switch_position {Up, down}; // Violation
REPAIR
const int max_pressure = 100;
enum Switch_position {up, down};
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 52
Header files will always have a file name extension of '.h' [JSF-53-3]
DESCRIPTION
The rule reports violations on header files which does not have '.h'
extension.
See also: PREPROC-08, NAMING-37, NAMING-38
SINCE
v7.1
NOTES
A header file is defined as any file that is included via #include.
BENEFITS
Rule makes source code more readable.
EXAMPLE
// file.cpp
#include "file.hpp"
// file.hpp
extern int i;
// Violation
REPAIR
// file.cpp
#include "file.h"
// file.h
extern int i;
REFERENCES
// OK
The following character sequences shall not appear in header file names: ', \, /*, //, or " [JSF53.1-2]
DESCRIPTION
The following character sequences shall not appear in header file
names: ', \, /*, //, or ".
SINCE
v7.1
BENEFITS
If any of the character sequences ', \, /*, //, or " appears in a
header file name (i.e. <h-char-sequence>), the resulting behavior is
undefined.
EXAMPLE
#include "foo's.h" // Violation
REPAIR
#include <foo_s.h> // OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 53.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Implementation files will always have a file name extension of ".cpp" [JSF-54-3]
DESCRIPTION
If a file name extension is not ".h" (reserved for header file) than
it should be ".cpp" (implementation file).
Rule detects file name extensions different than ".cpp" and ".h".
".cpp" extension should be used for implementation files whereas
".h" are reserved for headers (rule NAMING-41).
See also: NAMING-41
SINCE
v7.1
NOTES
Rule is enabled for C++ only.
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
//file.cc
// Violation
REPAIR
//file.cpp
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 54
BENEFITS
Readability and maintainability.
EXAMPLE
class Test {
protected:
void foo2(
private:
void foo3(
public:
void foo1(
};
// Violation
);
);
);
REPAIR
class Test {
public:
void foo1(
protected:
void foo2(
private:
void foo3(
};
// OK
);
);
);
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class Test {// Violation
public:
void foo1( );
private:
void foo3( );
protected:
void foo2( );
};
REPAIR
class Test {// OK
public:
void foo1( );
protected:
void foo2( );
private:
void foo3( );
};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.1 Classes - Rule 20
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
When declaring functions with more than 2 parameters, the leading parenthesis and the first
argument are to be written on the same line as the function name, each additional argument
will be written on a separate line [JSF-58-3]
DESCRIPTION
When declaring and defining functions with more than two parameters,
the leading parenthesis and the first argument will be written on
the same line as the function name. Each additional argument will
be written on a separate line (with the closing parenthesis directly
after the last argument).
SINCE
v7.1
BENEFITS
Readability and style.
EXAMPLE
void foo(int a, int b, int c);// Violation
void zoo(
int a, int b,
int c
)
{
// Violation
// Violation
// Violation
REPAIR
void foo(int a,
int b,
int c);
void zoo( int a,
int b,
// OK
int c)
// OK
{
}
void goo(int a, int b); // OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 58
The statement forming the body of a 'switch', 'while', 'do...while' or 'for' statement shall be a
compound statement [JSF-59_a-2]
DESCRIPTION
" The statement that forms the body of a switch statement or a while,
do ... while or for loop, shall be a compound statement (enclosed within
braces), even if that compound statement contains a single statement."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x ) {
int i;
switch(i)
;
// Violation
// Violation
REPAIR
void foo( int x ) {
int i;
switch(i)
{
}
// OK
{foo( x );}
while (1)
{foo( x );}
// OK
do
// OK
{foo( x );}
while(1);
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 59
3. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-3-1
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x, int
{
int i, j;
if(x > 0)
//
x = i;
else if(y > 0) //
y = i;
else
y = j;
//
x = j;
}
y )
Violation
Violation
Violation
REPAIR
void foo( int x, int y )
{
int i, j;
if(x > 0)
// OK
{
x = i;
}
else if(y > 0) // OK
{
y = i;
}
else
{
y = j;
x = j;
// OK
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Misra Guidelines - Rule 59
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-1
Braces "{}" which enclose a block should be placed in the same column [JSF-60-3]
DESCRIPTION
Rule checks if opening and closing braces are placed in the same column.
See also: FORMAT-02, FORMAT-03
EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//
Rule does not report violation
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class Foobar {
int a;
};
// Violation
struct S1 {
int a;
};
// Violation
REPAIR
class Foobar
{
int a;
};
struct S1
{
int a;
};
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 60
EXCEPTIONS
Rule does not adhere to enums,
enum E {EN1 = 2, EN2 = 1}; //
int array[] = {1,2,3,4,5}; //
class FooBar{};
//
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class A1
{ int a;
};
struct S1 {
int a;
};
// Violation
// Violation
REPAIR
class A1
{
int a;
};
struct S1
{
int a;
};
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61
EXCEPTIONS
Rule does not adhere to enums, initializations and empty blocks.
It is allowed to place tokens after '}' in the same line if:
- '}' ends 'do-while' construct
- '}' ends declaration of class/structure/union/enum
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
int goo(int i)
{
if (i == 0) { return i; }
// Violation
do { i++; } while (i < 10); // Violation
}
struct S{ int i; float f; }ss;
REPAIR
int goo(int i)
{
if (i == 0)
{
return i;
}
// OK
do
{
i++;
// Violation
// OK - Exception
// OK - Exception
// OK - Exception
// OK - Exception
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style Classes - 6.3 Compound Statements- Rec. 24
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 61
The dereference operator `*' and the address-of operator `&' should be directly connected with
the type names [JSF-62-3]
DESCRIPTION
"The dereference operator * and the "address-of" operator & should be
directly connected to the type names in declaration and definition."
BENEFITS
Rule makes source code more readable.
EXAMPLE
void foo() {
int k=42;
int *p1;// Violation
int &r1 = k;// Violation
}
REPAIR
void foo() {
int k=42;
int* p2;// OK
int& r2 = k;// OK
}
REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#6.5
from: 6 Style - 6.4 Pointers and References - Rec. 26
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 62
NOTES
The violation is not reported if '.' or '->' is last in line ignoring
white spaces, comments and backslashes. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.
BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.
EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj.
x;
/* Violation */
myObjPtr-> x; /* Violation */
}
#define MACRO a. b /* Violation */
REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {
myObj.x;
/* OK */
myObjPtr->
/* OK: '->' is last in line*/
x;
myObj./*comment*/ x; /* OK: no space immediately after '.' */
}
#define MACRO a. /* OK: '.' is last in line */ \
b
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif
REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
NOTES
The Violation is not reported if '.' or '->' is first in line ignoring
white spaces and comments. This allows splitting long
expressions between lines.
The violation is not reported if '.' or '->' is preceded by 'operator'
keyword.
BENEFITS
This promotes continuity in the relationship between the operators
and the members/elements on which they act. These operators are used
to access members/elements and cannot be considered separately from them.
EXAMPLE
struct MyStruct {
int x;
} myObj;
void foo(struct MyStruct* myObjPtr) {
myObj
.x;
/* Violation */
myObjPtr ->x; /* Violation */
}
#define MACRO a .b /* Violation */
REPAIR
struct MyStruct {
int x;
} myObj;
void fooR(struct MyStruct* myObjPtr) {
myObj.x;
/* OK */
myObjPtr
->x;
/* OK: '->' is first in line*/
myObj /*comment*/.x; /* OK: no space immediately before '.' */
}
#define MACRO a \
.b /* OK: '.' is first in line */
#ifdef __cplusplus
struct S {
int operator -> (); /* OK: preceded by 'operator' keyword */
};
#endif
REFERENCES
1.Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.7 Miscellaneous - Rec. 27
2.JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
There shall be no white space between a prefix unary operator and its operand [JSF-63_c-3]
DESCRIPTION
This rule checks whether there is no white space between a prefix unary
operator
and its operand. This promotes continuity in the relationship between
the operators and their associated operand. These operators act solely on
their
operand and cannot be considered separately from it.
BENEFITS
Improves readability.
EXAMPLE
void foo()
{
int i=0;
-- i; // Violation
}
REPAIR
void foo()
{
int i=0;
--i;
// OK
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
There shall be no white space between a postfix unary operator and its operand [JSF-63_d-3]
DESCRIPTION
This rule checks whether there is no white space between a postfix unary
operator and its operand. This promotes continuity in the relationship
between the operators and their associated operand. These operators
act solely on their operand and cannot be consider separately from it.
BENEFITS
Improves the readability of code.
EXAMPLE
void foo()
{
int y = 0;
y ++;
}
// Violation
REPAIR
void foo()
{
int y = 0;
y++;
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 63
NOTES
Rule skips 'static const' variables.
BENEFITS
Prevents the use of "public" data members. Public data members can be
directly
accessed by any user code.
Using public accessor member functions to return data instead
will prevent unauthorized access.
EXAMPLE
class A {
public:
int iData;
};
// Violation
REPAIR
class A {
private:
int iData;
// OK
public:
const int accessiData( );
};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.1 Considerations Regarding Access Rights - Rule 22
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 41
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 22
4. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Design and Declaration", Item 20
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 67
6. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
Rule skips 'static const' variables.
BENEFITS
Prevents the use of "protected" data members. Protected data members,
while
inaccessible within their classes, can be directly accessed by other
untrusted
classes using inheritance. Using protected accessor member functions to
return
data instead will prevent unauthorized access.
EXAMPLE
class A {
protected:
int iProtectedData;
};
// Violation
REPAIR
class A {
private:
int iPrivateData;
protected:
const int accessData();
};
REFERENCES
// OK
Declare the copy constructor and copy assignment operator private not in class itself, but in a
specifically designed base class [JSF-68-2]
DESCRIPTION
"It's possible to move the link-time error up to compile time (always a
good
thing earlier error detection is better than later) by declaring the
copy
constructor and copy assignment operator private not in class itself,
but in a base class specifically designed to prevent copying.
This works, because compilers will try to generate a copy constructor
and a copy assignment operator if anybody even a member or friend
function tries to copy a class object."
See also: CODSTA-CPP-02, CODSTA-CPP-19, CODSTA-CPP-21, CODSTA-CPP-24, MRM04,
MRM-05, MRM-37, MRM-38, MRM-40, MRM-47, MRM-48, OOP-27, OOP-34
SINCE
v7.0
BENEFITS
"The compiler-generated versions of these functions will try
to call their base class counterparts, and those calls will be
rejected, because the copying operations are private in the
base class."
EXAMPLE
class HomeForSale {
public:
HomeForSale();
private:
HomeForSale(const HomeForSale&);
// Violation
HomeForSale& operator=(const HomeForSale&); // Violation
};
REPAIR
class Uncopyable {
protected:
Uncopyable() {}
~Uncopyable() {}
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
};
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 6
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 68
SINCE
v7.1
BENEFITS
"Writing const appropriately helps you gain a better understanding of your
design and makes your code sturdier and safer."
EXAMPLE
class A
{
int foo(int a)
{
return a;
}
};
// Violation
REPAIR
class A
{
int foo(int a) const
{
// OK
return a;
}
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 15
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 69
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Freed memory shouldn't be accessed under any circumstances. Destructor should not be
called manually [JSF-70.1-2]
DESCRIPTION
"There are three major kinds of invalid objects:
- Destroyed objects: Typical examples are automatic objects that have gone
out
of scope and deleted heap-based objects.
- Semantically invalidated objects: Typical examples include dangling
pointers
to deleted objects (e.g., a pointer p after a delete p;) and invalidated
iterators. It is generally undefined and unsafe to do anything except
assign
another valid value to an invalidated object.
- Objects that were never valid.
Be aware of object lifetimes and validity. Never dereference an invalid
iterator
or pointer. Don't make assumptions about what delete does and doesn't do;
freed memory is freed, and shouldn't be subsequently accessed under
any circumstances. Don't try to play with object lifetime by calling
the destructor manually (e.g. obj.~T())."
The rule reports violations on the use of pointers to deleted objects
and on explicit calls of destructors.
NOTES
The rule checks only simple cases (use of variables, parameters,
a[b], a.b, a->b, or *a expressions after they were deleted).
The rule does not check a flow. It assumes that pointer to deleted object
is used if between 'delete' and an use of that pointer there is no
'case', 'default', 'break', 'return', 'throw', 'goto', exit(), abort().
BENEFITS
Rule prevents writing unsafe and error prone code.
EXAMPLE
class A {
public:
A();
~A();
};
void foo1( ) {
A obj;
obj.~A( );
}
// Violation
char* foo2( ) {
char * a = new char;
delete a;
return a;
// Violation
};
char* foo3(char * ptr){
char * a = new char;
if(a > ptr){
delete a;
(*a)++;
// Violation
} else {
(*a)++;
// OK
}
a = ptr + 1;
return a;
// OK
}
REPAIR
Don't use invalid objects.
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 99
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 70.1
Public and protected methods should not be invoked by class constructor [JSF-71-2]
DESCRIPTION
The intent of this rule is to prevent an object from being used before it
is in
a fully initialized state. This may occur when a class constructor invokes
a public or protected method that requires the object to be fully
initialized as a pre-condition of method invocation.
Rule reports a violation message if class constructor invokes public or
protected method.
See also: OOP-16, INIT-06
SINCE
v7.1
BENEFITS
Public (and in some cases protected) methods assume object initialization
and class invariants have been established prior to invocation. Thus,
invocation of such methods during object construction risks the use of
uninitialized or invalid data since class invariants can not be guaranteed
before an object is fully constructed.
EXAMPLE
class A
{
public:
A();
void foo();
private:
int obj1;
};
A::A()
{
foo();
}
// Violation
REPAIR
Do not call public/protected methods from constructor.
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 71
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Improves code reliability and maintainability, may identify runtime bugs
in the application.
EXAMPLE
class Base {
public:
Base( ) {
init_Base( );
// Violation
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
init_Base( );
// Violation
init_Derived1( );
// Violation
this->init_Derived2( ); // Violation
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}
REPAIR
class Base {
public:
Base( ) {
Base::init_Base( );
// OK
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
Base::init_Base( );
// OK
Derived::init_Derived1( ); // OK
derived->init_Derived2( ); // OK
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 49
BENEFITS
Improves code consistency and runtime performance
EXAMPLE
#include <string>
using namespace std;
class A {
public:
A( const char* file, const char* path ) {
myFile = file;
// Violation
myPath = path;
// Violation
}
private:
string myFile;
string myPath;
};
REPAIR
#include <string>
using namespace std;
class A {
public:
A( const char* file, const char* path ) :
myFile(file), myPath(path) {}
// OK
private:
string myFile;
string myPath;
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09,
Chapter: "Construction, Destruction, and Copying", Rule 48
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 12
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 74
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
List members in an initialization list in the order in which they are declared [JSF-75-2]
DESCRIPTION
"Recall that the destructors for the members of an object are always
called
in the inverse order of their constructors. Thus, if members were
initialized
in the order of their appearance in an initialization list, compilers
would
have to keep track of the order in which the members were initialized for
each
object, just to ensure that the destructors would be called in the right
order.
That would be an expensive proposition. To avoid that overhead, the order
of construction and destruction is the same for all objects of a given
type,
and the order of members in an initialization list is ignored."
In example section variable b from class A will not be initialized as we
assumed (initialized by the same value).
See also: INIT-06, INIT-14, MISRA-030
BENEFITS
Prevents access to null pointer when memory is not allocated.
EXAMPLE
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int b;
int a;
};
class B : public A {
public:
B( int );
private:
int a;
float b;
};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}
before b
// Violation - a is declared
REPAIR
class A {
public:
A( int x ) : a( x ), b( a ) {}
private:
int a;
int b;
};
// OK - a is declared before b
class B : public A {
public:
B( int );
private:
float b;
int a;
};
B::B( int y ) : b( 5 ), A( 1 ), a( y ) {}
// OK - b is declared before a
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 13
3, JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 75
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Declare an assignment operator for classes with dynamically allocated memory [JSF-76_a-2]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or
'delete' to deallocate its data member, has an explicitly defined
canonical
assignment operator. A canonical assignment operator returns a class
reference
type and takes a const reference of the type.
"An assignment is not inherited like other operators. If an assignment
operator
is not explicitly defined, then one is automatically defined instead.
If you perform an assignment 'b = a;' (where 'a' and 'b' are pointers)
there is
no client-defined operator= to call, so C++ generates and calls the
default
assignment operator instead.
This default assignment operator performs memberwise assignment from the
members of 'a' to the members of 'b', which for pointers is just a bitwise
copy.
There are at least two problems with this state of affairs.
First, the memory that 'b' used to point to was never deleted;
it is lost forever. This is a classic example of how a memory leak can
arise.
Second, both 'a' and 'b' now contain pointers to the same character
string.
When one of them goes out of scope, its destructor will delete the memory
still pointed to by the other."
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-38,
MRM-40, MRM-47, OOP-27, OOP-30, OOP-34
EXCEPTIONS
Rule does not report violation if there's an assignment operator in a base
class which prevents implicitly declared assignment operator in this class
from being used.
BENEFITS
"Bit-wise copying is only performed for member data having primitive
types.
One consequence of this is that bit-wise copying is performed for member
data
having pointer types. If an object manages the allocation of the instance
of
an object pointed to by a pointer member, this will probably lead to
problems:
either by invoking the destructor for the managed object more than once or
by
attempting to use the deallocated object."
EXAMPLE
class MyClass { // Violation
public:
MyClass( );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}
REPAIR
class MyClass { // OK
public:
MyClass( );
MyClass& operator=( const MyClass& );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 AssignmentOperators - Rule 27
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Declare a copy constructor for classes with dynamically allocated memory [JSF-76_b-2]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or 'delete' to deallocate its data member, has an explicitly defined copy
constructor.
See also: CODSTA-CPP-19, MRM-05, MRM-37, MRM-40, MRM-48, OOP-27, OOP-30,
OOP-34
EXCEPTIONS
Rule does not report violation if there's an copy constructor in a base
class which prevents implicitly declared copy constructor in this class
from being used.
BENEFITS
"A copy constructor is recommended to
is initialized using an object of the
the allocation and deallocation of an
object has a pointer to the object to
constructor),
only the value of the pointer will be
invocations
of the destructor for the same object
in a run-time error."
EXAMPLE
class MyClass{ // Violation
public:
MyClass();
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}
REPAIR
class MyClass{ // OK
public:
MyClass();
MyClass(MyClass&);
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 25
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Constructors,
Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
A copy constructor shall copy all data members and bases [JSF-77-2]
DESCRIPTION
"A class may contain many data members as well as exist within an
inheritance
hierarchy. Hence the copy constructor must copy all members, including
those
in base classes."
SINCE
v7.1
NOTES
The rule does not report violations on variables of class/struct type.
If a copy constructor of base class is called then the rule assumes
that all variables from a base class are copied.
BENEFITS
"Ensure data members and bases are properly handled when an object is
copied."
EXAMPLE
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:
// Violation
private:
int derived_member_1;
int derived_member_2;
};
REPAIR
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:
Derived (int x, int y, int z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) { }
Derived(const Derived& rhs) : Base(rhs),
derived_member_1 (rhs.derived_member_1),
derived_member_2 (rhs.derived_member_2)
{
}
private:
int derived_member_1;
int derived_member_2;
};
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The definition of a constructor shall not contain default arguments that produce a signature
identical to that of the implicitly-declared copy constructor [JSF-77.1-2]
DESCRIPTION
The definition of a member function shall not contain default arguments
that
produce a signature identical to that of the implicitly-declared copy
constructor for the corresponding class/structure.
SINCE
v7.1
BENEFITS
If the class definition does not explicitly declare a copy constructor,
one is declared implicitly. Thus, for the class definition
class X
{
X(const X&, int);
};
a copy constructor is implicitly-declared. If the user-declared
constructor
is later defined as
X::X(const X& x, int i =0)
{
/* ... */
}
then any use of X's copy constructor is ill-formed because of the
ambiguity.
EXAMPLE
class A
{
A(const A&, int);
A(const A&);
};
A::A(const A& x, int i =0) // Violation
{
/* ... */
}
REPAIR
class A
{
A(const A&, int i=0);
A(const A&);
};
A::A(const A& x, int i) // OK
{
/* ... */
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Define a virtual destructor in classes used as base classes which have virtual functions [JSF78-2]
DESCRIPTION
All classes which are used as base classes and which have virtual
functions
must define a virtual destructor. If a class, having virtual functions but
without virtual destructors, is used as a base class, there may be a
surprise
if pointers to the class are used. If such a pointer is assigned to an
instance
of a derived class and if delete is then used on this pointer, only the
base
class' destructor will be invoked. If the program depends on the derived
class'
destructor being invoked, the program will fail.
See also: OOP-23, OOP-24, OOP-31
BENEFITS
Define a virtual destructor in order to prevent data corruption.
EXAMPLE
class Base
// Violation
{
public:
virtual void foo( );
~Base( );
};
class Derived : public Base{};
REPAIR
class Base
// OK
{
public:
virtual void foo( );
virtual ~Base( );
};
class Derived : public Base{};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 26
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 78
Call fclose() on pointer member in destructor if the pointer was used to open a file [JSF-79-2]
DESCRIPTION
This rule reports a violation message when pointer member was used to open
a file in constructor and the file is not closed in destructor.
See also: MRM-33
SINCE
v7.1
BENEFITS
Prevention of resource leaks, especially in error cases.
Releasing resources in a destructor provides a convenient means of
resource
management, especially in regards to exceptional cases. Moreover, if it is
possible that a resource could be leaked, then that resource should be
wrapped
in a class whose destructor automatically cleans up the resource.
EXAMPLE
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}
~File_ptr ()
{
}
private:
// Violation
FILE *p;
};
REPAIR
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}
~File_ptr ()
{
if (p)
{
fclose(p);
}
}
// OK
private:
FILE *p;
};
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 79
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
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;
};
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;
};
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
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
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
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
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
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
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) {}
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) {}
};
// 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
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
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:
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
// 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]
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
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
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.
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.
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
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.
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.
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"
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.
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.
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.
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.
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.
NOTES
This rule applies only to the C++ programming language.
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
class Foo {// Violation
public:
void method1();
void method2();
void method3();
void method4();
void method5();
void method6();
void method7();
void method8();
void method9();
void method10();
void method11();
void method12();
void method13();
void method14();
void method15();
void method16();
void method17();
void method18();
void method19();
void method20();
void method21();
};
REPAIR
Limit the number of public methods to 20 per class.
REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, November/December 1999, pg. 33.
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
void foo(int a, int b, int c, int d, int e, int f) // Violation
{
}
REPAIR
Limit the number of parameters to 5 per function.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 41
2. Motorola Coding Standards G-6
3. HIS Source Code Metriken, version 1.3.1
Metrik "PARAM"
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
#define PLUS(a,b,c,d,e,f) (a+b+c+d+e+f) // Violation
REPAIR
Limit the number of parameters to 5 per macro.
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
struct
{
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
};
_tA// Violation
i0;
i1;
i2;
i3;
i4;
i5;
i6;
i7;
i8;
i9;
i10;
i11;
i12;
i13;
i14;
i15;
i16;
i17;
i18;
i19;
i20;
i21;
i22;
i23;
REPAIR
Limit the number of fields to 20.
REFERENCES
Recommended by ParaSoft
NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 10" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for
N.
BENEFITS
Studies have found that methods with high Cyclomatic Complexity are errorprone.
EXAMPLE
void foo(int a, int b) // Violation - CC value: 11
{
switch (a)
{
case 1:
// 1
break;
case 2:
// 2
break;
case 3:
// 3
break;
default:
break;
}
if(a||b)
// 4, 5
{
}
if((a||b)&&(a&&b)) // 6, 7, 8, 9
{
}
do
// 10
{
}while(0);
}
REPAIR
Keep a Cyclomatic Complexity value on the level lower than 10.
REFERENCES
McCabe, T., "A Complexity Measure," IEEE Transactions on Software
Engineering, December 1976.
HIS Source Code Metriken, version 1.3.1
Metrik "v(G)"
The percentage of comment lines versus the total number of module lines should be between
20 and 60 [METRICS-19-3]
DESCRIPTION
Rule checks if percentage of comment lines versus the total number of
method
lines is between 20 and 60.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo1(int y) {// Violation
//
//
//
//
}
void foo12() {// Violation
/*
*/
}
void foo3() {// Violation
/**//**//**//**/
}
void foo4() {// Violation
REPAIR
void foo1() {// OK
//
//
//
//
}
void foo2() {// OK
/*
*/
}
void foo3() {// OK
/**//**//**//**/
REFERENCES
Recommended by ParaSoft
NOTES
Rule triggers when the number of declarations and statements within
function body exceeds 50.
BENEFITS
By always using short functions, such an error can be more exactly
localized.
EXAMPLE
void too_long_function() {// Violation
int a1;
int a2;
int a3;
int a4;
int a5;
int a6;
int a7;
int a8;
int a9;
int a10;
int a11;
int a12;
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
int
}
a13;
a14;
a15;
a16;
a17;
a18;
a19;
a20;
a21;
a22;
a23;
a24;
a25;
a26;
a27;
a28;
a29;
a30;
a31;
a32;
a33;
a34;
a35;
a36;
a37;
a38;
a39;
a40;
a41;
a42;
a43;
a44;
a45;
a46;
a47;
a48;
a49;
a50;
a51;
a52;
a53;
a54;
REPAIR
Number of declarations and statements within function body
should be limited to 50.
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.7 General - Rec 47
NOTES
Rule triggers if function contains more than 10 blocks.
BENEFITS
By always using short and simple functions, such an error can be more
exactly
localized and function testing is much easier.
EXAMPLE
void func( int i ) {
if (1) {
} else {
}
do {
} while(1);
switch(i) {
case 1:
break;
default:
break;
}
if (1) {
} else {
}
if (2) {
} else {
}
if (3) {
// Violation
} else {
}
}
REPAIR
Limit the number of blocks within function body to 10.
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.7 General - Rec. 47
BENEFITS
Rule improves
EXAMPLE
class A
{
void foo( int x )
// Violation
{
// ...
// more than 75 lines of constants, declarations, expressions,
// statements, types
// ...
}
};
REPAIR
Do not type functions longer than 75 lines of code.
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 20
NOTES
It is possible to change the allowed nesting level by modifying
one element of rule in Rule Wizard. The level is checked by expression
in last "Count" node. The default "$$==5" expression imposes maximum
nesting level of 5. For example, to report violation if nesting level is
higher than 10, change the expression to "$$==10".
BENEFITS
"Excessive block nesting depth (e.g. if, for, while, and try blocks) make
functions more difficult to understand and maintain, and often needlessly
so."
EXAMPLE
int foo1(int i)
{
if(i > 1){
// OK - 5 level
// Violation - 6 level
// OK - 7 level - violation already
i;
// Violation - 6 level
// OK - 5 level
// Violation - 6 level
// OK - 7 level - violation already reported on level
if(i == 1) {
return i;
} else {
if(i == 2) {
return i;
} else {
if(i == 3) {
return i;
} else {
if(i == 4) {
return i;
} else {
if(i == 5) { // OK - 5 level
return i;
} else {
if(i == 6) { // Violation - 6 level
return i;
} else {
if(i == 7) { // OK - 7 level - violation
already reported on level 6
return i;
}
}
}
}
}
}
}
}
int foo3(int i)
{
{
{
{
{
{
{
}
}
}
}
}
// OK - 5 level
// Violation - 6 level
return i;
}
}
void foo4()
{
// try-catch is linear and introduces one level, same as if-else:
try {
// OK - 1 level
} catch(char) {
// OK - 1 level
} catch(int) {
// OK - 1 level
} catch(long) {
// OK - 1 level
} catch(float) {
// OK - 1 level
} catch(double) { // OK - 1 level
} catch(...) {
// OK - 1 level
}
}
int foo5(int i)
{
while(i) { // 1
for(;;) { // 2
if(i) { // 3
} else { // still 3
switch(i) { // 4
case 1: // still 4
++i;
{ // 5
do { // 6 - Violation
return i;
} while(0);
}
}
}
}
}
}
#define MACRO(x) { { { { { { return x; } } } } } }
int foo6(int i)
{
// Code from macros might produce violations
MACRO(i); // Violation
}
REPAIR
Do not
"Avoid
Prefer
Prefer
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 20
Avoid source files that are longer than 500 lines [METRICS-24-5]
DESCRIPTION
Source files should be no longer than 500 lines. Experience has shown
that larger files are cumbersome to edit correctly and to maintain.
BENEFITS
Improves maintainability and readability of code.
EXAMPLE
// Source file - Violation
/*
code
*/
#line 501
int i = 0;
// line: 501
REPAIR
Limit source files to 500 lines.
REFERENCES
Recommended by ParaSoft
Any one function (or method) will contain no more than 200 logical source lines of code (LSLOCs) [METRICS-25-3]
DESCRIPTION
Any one function (or method) will contain no more than 200
logical source lines of code (L-SLOCs).
SINCE
v7.1
NOTES
Logical line of code is a single declaration or statement terminated
by semicolon.
Two semicolons in parenthesis after 'for' keyword are counted as one.
BENEFITS
Rule prevents using long functions which tend to be complex and
therefore difficult to comprehend and test.
EXAMPLE
int sample_function(int p)
{
int x, y;
// Violation
// L-SLOCs number = 1
// ...
x++;
// L-SLOCs number = 99
for(y = 10; y > 0; y--){
// L-SLOCs number = 100
x = y;
// L-SLOCs number = 101
}
// ...
x = x + p; y = y + p;
151
// ...
return x;
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
SINCE
v7.1
NOTES
Tab is counted as one character.
White spaces at the end of line are counted in the same way as other
characters.
Comments with 'parasoft-suppress' are not counted.
To change the default limit of characters modify the variable
'lineLengthLimit'
at the begin of python method 'check'.(e.g. 'lineLengthLimit = 100' means
that
the maximal allowed number of characters in a physical line is 100)
BENEFITS
The rule improves readability of code.
EXAMPLE
int
/*
..........................................................................
..........*/ i1 ; /* Violation */
int
/* ..........white spaces at the end of
line.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........Violation.......
*
..........................................................................
............................Violation.....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* Violation
*/
REPAIR
int
/*
..........................................................................
................*/ i1 ; /* OK */
int
/* ..........There is no spaces at the
end.......................................*/ i2 ; /* Violation */
/* multiline comment
..........................................................................
..........OK......
*
..........................................................................
............................OK....*/
#define MACCCCC(xxxxxxxxxxxxxxxxxxxxxxxxxxxx) xxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ xxxxxxxxxxxxxxxxxxxxxxxxxxxx + \
xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* OK */
int
/*
..........................................................................
...............*/ i3 ; /* parasoft-suppress ITEM ... OK */
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 41
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
//
SINCE
v7.1
NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 20" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for
N.
BENEFITS
Studies have found that methods with high Cyclomatic Complexity are errorprone.
EXAMPLE
void foo2(int i, int a, int b, int j, int k)
{
switch (i)
{
case 1: // 1
i++;
default:
i++;
}
switch (j)
{
case 1: // 2
j++;
default:
j++;
}
switch (k)
{
case 1: // 3
k++;
default:
k++;
}
if(a||b)
// 4, 5
{
}
if((a||b)&&(a&&b)) // 6, 7, 8, 9
{
}
do
// 10
{
}while(0);
// Violation - CC value: 21
switch (i)
{
case 1: // 11
i++;
default:
i++;
}
switch (j)
{
case 1: // 12
j++;
default:
j++;
}
switch (k)
{
case 1: // 13
k++;
default:
k++;
}
if(a||b)
// 14, 15
{
}
if((a||b)&&(a&&b)) // 16, 17, 18, 19
{
}
do
// 20
{
}while(0);
}
REPAIR
Keep a Cyclomatic Complexity value on the level lower than 20.
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 3.2 Code Size and Complexity, AV Rule 3
SINCE
v7.1
NOTES
To change the default limit of the Cyclomatic Complexity modify the main
"Count" expression of the rule (Collector A) from "$$ > 0" to "$$ > N"
using desired threshold value for N. Rule's header should be also changed
accordingly.
To ignore switch statements in the computation of the Cyclomatic
Complexity,
modify the "Count" expression for the cases (Collector C) from "$$ > 0"
to "$$ == 0".
To ignore switch statements having more than N cases in the computation
of the Cyclomatic Complexity, modify the "Count" expression for the cases
(Collector C) from "$$ > 0" to "$$ <= N" using desired threshold value for
N.
BENEFITS
Studies have found that methods with high Cyclomatic Complexity are errorprone.
EXAMPLE
void foo(int a, int b) // Violation - CC value: 8
{
if(a||b)
// 1, 2
{
}
if((a||b)&&(a&&b)) // 3, 4, 5, 6
{
}
do
// 7
{
}while(0);
}
REPAIR
This rule is an informational rule and reports message
on each function implementation.
REFERENCES
Recommended by ParaSoft
SINCE
v7.3
NOTES
The rule counts non-empty lines inside body of function.
Lines containing only comment are not counted.
BENEFITS
"Each function should be a logical unit in the code that is understandable
and verifiable as a unit. It is much harder to understand a logical unit
that
spans multiple screens on a computer display or multiple pages when
printed.
Excessively long functions are often a sign of poorly structured code."
EXAMPLE
void foo( int x )
// Violation
{
// ...
// more than 60 lines of constants, declarations, expressions,
// statements, types
// ...
}
REPAIR
Refactor long functions into several smaller functions.
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 4
The assertion density of the code should average to a minimum of two assertions per function
[METRICS-31-3]
DESCRIPTION
"The assertion density of the code should average to a minimum of two
assertions
per function. Assertions are used to check for anomalous conditions that
should
never happen in real-life executions."
The rule reports a violation if A < 2*F where A is the number of
assertions
and F is the number of defined functions.
SINCE
v7.3
NOTES
The rule detects all using of macros which names are ended by 'assert'
e.g. 'assert', 'c_assert', 'checkAssert' etc.
The rule checks one file at time.
BENEFITS
"Statistics for industrial coding efforts indicate that unit tests often
find at least one defect per 10 to 100 lines of code written. The odds
of intercepting defects increase with assertion density. Use of assertions
is often also recommended as part of a strong defensive coding strategy.
Assertions can be used to verify pre- and post-conditions of functions,
parameter values, return values of functions, and loop-invariants.
Because assertions are side-effect free, they can be selectively disabled
after testing in performance-critical code."
EXAMPLE
/* Violation - 2 functions defined and 1 assertion used */
#define c_assert(x) ((x) ? 1 : 0);
void foo(int x)
/* Some code
c_assert(x);
}
void bar(int x,
/* Some code
}
int baz();
{
*/
/* Use of assertion */
int y) {
*/
REPAIR
/* OK - 2 functions defined and 4 assertions used (density: 2) */
#define c_assert(x) ((x) ? 1 : 0);
void foo(int x) {
c_assert(x); /* Use of assertion */
/* Some code */
}
void bar(int x, int y) {
c_assert(x); /* Use of assertion */
c_assert(y); /* Use of assertion */
/* Some code */
c_assert(x+y); /* Use of assertion */
}
int baz();
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 5
All functions with more than 20 lines should contain at least 2 assertions [METRICS-32-3]
DESCRIPTION
The rule checks if a function that has more than M lines has at least
N assertions. M and N are parameters that could be set inside rule in
python method 'setValue'.
They are default set to:
MinimalNumberOfAssertions = 2
MinimalNumberOfFunctionLines = 20
In this case the rule reports a violation if a function that has more than
20
lines does not contain at least 2 assertions.
See also: METRICS-31
SINCE
v7.3
NOTES
As assertion the rule sees any use of macro with name that
ends with 'assert', e.g. 'assert', 'c_assert', 'checkAssert' etc.
The first line of function is a line containing opening brace '{'
and the last is line containing closing brace '}'. All lines are
counted, including empty and commented out.
BENEFITS
"Statistics for industrial coding efforts indicate that unit tests often
find at least one defect per 10 to 100 lines of code written. The odds
of intercepting defects increase with assertion density. Use of assertions
is often also recommended as part of a strong defensive coding strategy.
Assertions can be used to verify pre- and post-conditions of functions,
parameter values, return values of functions, and loop-invariants.
Because assertions are side-effect free, they can be selectively disabled
after testing in performance-critical code."
EXAMPLE
REPAIR
#define c_assert(x) ((x) ? 1 : 0);
void foo(int x,
/* Some code
c_assert(x);
c_assert(x);
/*
* code
*
*
*
*
*
*
*
*
* code
*
*
*
*
*/
}
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 5
SINCE
v7.3
NOTES
Rule does not consider exception handling ('catch') as a decision.
BENEFITS
"Structured programming avoids unmaintainable "spaghetti code" by
restricting the usage
of control structures to those that are easily analyzed and decomposed."
By comparing Essential Complexity with Cyclomatic Complexity it's possible
to find
functions that are complicated but well structured, which means they can
be refactored.
EXAMPLE
void Example(int x, int y) /* Violation: Essential Complexity = 8
{
for(;x || y;) {
// +2
switch (x*y) {
case 1:
// +1
while (--x > 0) { // +1
if (x % y) {
// +1
return;
}
}
if (x > y) {
// +1
goto OUT;
}
break;
case 2:
// +1
do {
x++;
} while (x && y && (x * y < 100));
break;
}
OUT:
if (y) {
++y;
}
}
if (y) {
goto END;
}
END:
return;
}
REPAIR
*/
REFERENCES
1. A Complexity Measure
Thomas J. McCabe
308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. SE-2, NO.4, DECEMBER
1976
2. Structured Testing: A Testing Methodology Using the Cyclomatic
Complexity Metric
NIST Special Publication 500-235
Chapter 10 Essential Complexity
http://hissa.nist.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera.htm#446037
SINCE
v7.3
NOTES
Rule does not consider exception handling ('catch') as a decision.
BENEFITS
"Structured programming avoids unmaintainable "spaghetti code" by
EXAMPLE
void Example(int x, int y) /* Violation: Essential Complexity = 8
{
for(;x || y;) {
// +2
switch (x*y) {
case 1:
// +1
while (--x > 0) { // +1
if (x % y) {
// +1
return;
}
}
if (x > y) {
// +1
goto OUT;
}
break;
case 2:
// +1
do {
x++;
} while (x && y && (x * y < 100));
break;
}
OUT:
if (y) {
++y;
}
}
if (y) {
goto END;
}
END:
return;
}
*/
REPAIR
This rule is an informational rule and reports Essential Complexity
on each function implementation.
REFERENCES
1. A Complexity Measure
Thomas J. McCabe
308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. SE-2, NO.4, DECEMBER
1976
2. Structured Testing: A Testing Methodology Using the Cyclomatic
Complexity Metric
NIST Special Publication 500-235
Chapter 10 Essential Complexity
http://hissa.nist.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera.htm#446037
SINCE
v7.3
NOTES
Rule does not consider exception handling ('catch') as a decision.
BENEFITS
"Structured programming avoids unmaintainable "spaghetti code" by
EXAMPLE
void Example(int x, int y)
/* Violation: Essential Complexity = 12
{
for(;x || y;) {
// +2
switch (x*y) {
case 1:
// +1
for(;x && y && x < y;) {
// +3
while (--x > 0) {
// +1
if (y && x % y) {
// +2
return;
}
}
if (x > y) {
// +1
goto OUT;
}
}
break;
case 2:
// +1
do {
x++;
} while (x && y && (x * y < 100));
break;
}
OUT:
if (y) {
++y;
}
}
if (y) {
goto END;
}
END:
return;
}
*/
REPAIR
This rule is an informational rule and reports Essential Complexity
on each function implementation.
REFERENCES
1. A Complexity Measure
Thomas J. McCabe
308 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. SE-2, NO.4, DECEMBER
1976
2. Structured Testing: A Testing Methodology Using the Cyclomatic
Complexity Metric
NIST Special Publication 500-235
Chapter 10 Essential Complexity
http://hissa.nist.gov/HHRFdata/Artifacts/ITLdoc/235/chaptera.htm#446037
A function should not be called from more than 5 different functions [METRICS-36-3]
DESCRIPTION
A function should not be called from more than 5 different functions.
All calls within the same function are counted as 1.
The rule is limited to translation unit scope.
SINCE
v7.3
EXAMPLE
void foo(){} /* Violation */
void goo1(){
foo(); /* 1
}
void goo2(){
foo(); /* 2
}
void goo3(){
foo(); /* 3
}
void goo4(){
foo(); /* 4
}
void goo5(){
foo(); /* 5
}
void goo6(){
foo(); /* 6
}
*/
*/
*/
*/
*/
*/
REPAIR
void foo(){} /* OK */
void goo1(){
foo();
foo();
foo();
foo();
foo();
foo();
}
REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "CALLING"
SINCE
v7.3
EXAMPLE
void
void
void
void
void
void
void
void
goo1(){}
goo2(){}
goo3(){}
goo4(){}
goo5(){}
goo6(){}
goo7(){}
goo8(){}
void foo2()
{
goo1();
goo2();
goo3();
goo4();
goo5();
goo6();
goo7();
goo8();
}
REPAIR
void
void
void
void
void
goo1(){}
goo2(){}
goo3(){}
goo4(){}
goo5(){}
/* Violation */
void goo6(){}
void goo7(){}
void goo8(){}
void foo1()
{
goo1();
goo2();
goo3();
goo4();
}
/* OK */
void foo2()
{
foo1();
goo5();
goo6();
goo7();
goo8();
}
/* OK */
REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "CALLS"
SINCE
v7.3
EXAMPLE
void foo(){} /* Violation */
void foo2(){} /* Violation */
int goo1(int i){ /* Violation
int e;
foo();
/*
foo2();
/*
if(i){
/*
i++;
/*
return i;
/*
}else{
i--;
/*
return 0;
/*
}
for(e = 0; e < 1; e++){ /*
while(i < 4)
/*
i = i + 4;
/*
}
switch (i){
/*
case 0:
i = 7;
/*
case 1:
i = 30;
/*
case 2:
i = 50;
/*
default:
return i;
/*
*/
1
2
3
4
5
*/
*/
*/
*/
*/
6 */
7 */
8 */
9 */
10 */
11 */
12 */
13 */
14 */
15 */
}
;
a:
foo();
foo2();
if(i){
i++;
return i;
}else{
i--;
return 0;
}
for(e = 0; e
while(i <
i = i
}
switch (i){
case 0:
i = 7;
case 1:
i = 30;
case 2:
i = 50;
default:
return i;
}
;
foo();
foo2();
for(e = 0; e
;
if(i){
i++;
return i;
}else{
i--;
i--;
i--;
return 0;
}
for(e = 0; e
while(i <
i = i
}
/* 16 */
/*
/*
/*
/*
/*
17
18
19
20
21
*/
*/
*/
*/
*/
/* 22 */
/* 23 */
< 1; e++){ /* 24 */
4)
/* 25 */
+ 4;
/* 26 */
/* 27 */
/* 28 */
/* 29 */
/* 30 */
/* 31 */
< 1; e++)
/*
/*
/*
/*
/*
/*
/*
/*
32
33
34
35
36
37
38
39
*/
*/
*/
*/
*/
*/
*/
*/
/*
/*
/*
/*
40
41
42
43
*/
*/
*/
*/
< 1; e++){ /* 44 */
4)
/* 45 */
+ 4;
/* 46 */
i = i + 5 + 4 * (2 / 3);
do{
i = (i < 4) ? 2 : 5;
}while(i < 5);
goto a;
return 10;
/* 47 */
/* 48 */
/* 49 */
/* 50 */
/* 51 */
REPAIR
The function should have at least 1 statement and the number of statements
within function body should be limited to 50.
REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "STMT"
The value of VOCF metric for a function should not be higher than 4 [METRICS-39-3]
DESCRIPTION
The rules checks the value of VOCF metric for a function.
Rule reports a violation if the value of VOCF metric
is higher than 4.
VOCF is
VOCF
where:
N1 N2 n1 n2 -
number
number
number
number
of
of
of
of
SINCE
v7.3
EXAMPLE
/* operators: brace{}(1), parentheses()(10), return(2), = (2), ;(6),
* + (8), * (5), if (2), >= (2),
* - N1 (38), n1 (9)
* operands: int(4), foo(1), i(9), a(3), b (3), 1 (2), 2 (6), 3 (3)
* - N2 (31), n2 (8)
* VOCF = (N1 + N2) / (n1 + n2) = (38 + 31) / (9 + 8) = 4.06 */
int foo(int i){
int a;
int b;
/* Violation */
a = i + (2 * (i + 1)) + (3 * (i + 2));
b = (i + (2 * (i + 1)) + (3 * (i + 2))) * 2;
if(i >= 3)
return a;
if(i >= 2)
return b;
}
REPAIR
/* operators: brace{}(1), parentheses()(5), return(2), = (2), ;(6),
* + (4), * (3), if (2), >= (2),
* - N1 (27), n1 (9)
* operands: int(4), foo(1), i(6), a(4), b (3), 1 (1), 2 (4), 3 (2)
* - N2 (25), n2 (8)
* VOCF = (N1 + N2) / (n1 + n2) = (27 + 25) / (9 + 8) = 3.06 */
int foo1(int i){
int a;
int b;
/* OK */
a = i + (2 * (i + 1)) + (3 * (i + 2));
b = a * 2;
if(i >= 3)
return a;
if(i >= 2)
return b;
}
REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "VOCF"
Statements within function should not be nested deeper than 4 levels [METRICS-40-3]
DESCRIPTION
Statements should not be nested deeper than 4 levels.
The rule as a level detects a block of code enclosed with curly braces
'{}'
SINCE
v7.3
BENEFITS
Rule improves easier code understanding, and maintain, and often
needlessly so.
EXAMPLE
int foo2( int x ) {
/* level-0 */
if (x > 0) {
/* level-1 */
if (x > 1) {
/* level-2 */
if (x > 2) {
/* level-3 */
if (x > 3) {
/* level-4 */
if (x > 4) {
starts */
/* level-5 */
if (x > 5) {
higher level */
/* level-6 */
return x;
}
}
}
}
}
}
}
/*
/*
/*
/*
/*
OK */
OK */
OK */
OK */
Violation - level 5
/* OK - Violation on
REPAIR
Do not use excessive block nesting depth (more than 4 levels)
REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "LEVEL"
The number of blocks of comments before and inside function to the number of statements in
function should be > 0.2 [METRICS-41-3]
DESCRIPTION
The rule reports a violation if the number of blocks of comments in
function
body (BCOM) and before function (BCOB) to number of statements in function
(STMT) is not higher than 0.2
(BCOM + BCOB)/STMT <= 0.2 /* Violation */
Counted statements are: asm, break, continue, do...while, empty, for,
goto,
if, return, switch, while and the top level expressions.
SINCE
v7.3
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
/* 1 block */
/* 1 block */
int comm /* Violation - function 'comm' contains 20 statements
and 4 blocks of comments - COMF = 0.2
2 block */
(
unsigned short s
)
{
int i;
if (s > 0)
i = 3;
else
i = 4;
if (s > 0)
i = 3;
else
i = 4;
if (s > 0)
i = 3;
else
/* 3 block */
i = 4;
if (s > 0)
i = 3;
else
i = 4;
if (s > 0)
i = 3;
else
i = 4;
/* 4 block */
if (s > 0){
i = 3;
i = 5;
}
else
i = 4;
return i;
}
REPAIR
/* 1 block */
/* 1 block */
int comm1 /* OK - function 'comm' contains 20 statements
and 10 blocks of comments - COMF = 0.5
2 block */
(
unsigned short s /* 3 block */
/* 4 block */
)
{
int i;
if (s > 0)
i = 3;
else
i = 4;
if (s > 0)
i = 3;
else
i = 4;
if (s > 0)
i = 3;
/* 5 block */
/* 6 block */
else
/* 7 block */
i = 4;
if (s > 0)
/* 8 block */
/* 8 block */
/* 8 block */ i = 3;
else
i = 4;
if (s > 0)
i = 3;
/* 9 block */
else
i = 4;
if (s > 0){
i = 3;
i = 5;
}
else
i = 4;
return i;
}/* 10 block */
REFERENCES
HIS Source Code Metriken, version 1.3.1
Metrik "COMF"
}
int y;
};
class C { // CBO = 2
public:
int bar(A a) {
B b;
a.foo(); // coupling to A
a.x = 0; // coupling to A
return b.bar2(); // coupling to B
}
};
REFERENCES
1. Shyam R. Chidamber, Chris F. Kemerer
A Metrics Suite for Object Oriented Design
IEEE Transactions on Software Engineering, Vol 20., No. 6, June 1994
class A { // LCOM = 0
void foo1() {
x = 0;
y = 0;
}
void foo2() {
x = y;
}
int x;
int y;
};
class B { // LCOM = 1
void foo1() {
x = 0;
}
void foo2() {
y = 0;
}
int x;
int y;
};
class C { // LCOM = 0.5
void foo1() {
x = 0;
}
void foo2() {
y = x;
}
int x;
int y;
};
REPAIR
Consider splitting classes into separate, more targetted, classes.
For example:
class B1 { // LCOM = 0
void foo1() {
x = 0;
}
int x;
};
class B2 { // LCOM = 0
void foo2() {
y = 0;
}
int y;
};
REFERENCES
1. Henderson-Sellers, B.
Object-oriented metrics: measures of complexity
Prentice-Hall, pp.142-147, 1996.
2. Lack of Cohesion in Methods
http://eclipsemetrics.sourceforge.net/descriptions/pages/cohesion/LackOfCohesionInMethod
s.html
// NSF = 3
int I;
float F;
long L;
struct C { // NSF = 0
int i;
float f;
};
// NSM = 3
int foo();
float bar();
long foo(int i);
class C { // NSM = 0
};
MISRA
MISRA C
RULES
Provisions should be made for appropriate run-time checking [MISRA-004_a5]
Provisions should be made for appropriate run-time checking [MISRA-004_b5]
Only use characters defined in ISO C standard [MISRA-005-3]
Values of character types shall be restricted to a defined and documented
subset of ISO 10646-1 [MISRA-006-3]
Do not use wide string literals [MISRA-008-3]
The basic types of char, int, short, long, float and double should not be
used, but specific-length equivalents should be typedef'd [MISRA-013-3]
Explicitly declare 'char' type as signed or unsigned [MISRA-014-3]
The underlying bit representations of floating point numbers shall not be
used [MISRA-016-3]
Use type suffix for numeric constants [MISRA-018_a-5]
Use type suffix for numeric constants [MISRA-018_b-5]
Use type suffix for numeric constants [MISRA-018_c-5]
Use type suffix for numeric constants [MISRA-018_d-5]
All functions shall be declared before use [MISRA-020-3]
Declare objects at function scope [MISRA-022-5]
Make declarations at file scope static where possible [MISRA-023-5]
Use consistent linkage for identifiers [MISRA-024-3]
External object should not be declared in more than one file [MISRA-027-3]
Do not use register storage class [MISRA-028-5]
The use of a tag shall agree with its declaration [MISRA-029-3]
All automatic variables shall have been assigned a value before being used
[MISRA-030-3]
Invalid range of the right hand operand of a shift operator [MISRA-038-3]
Document integer division [MISRA-041-5]
The comma operator shall not be used, except in the control expression of
a for loop [MISRA-042-3]
Implicit conversions which may result in a loss of information shall not
be used [MISRA-043-3]
Avoid mixing arithmetic of different precisions in the same expression
[MISRA-043_b-3]
Redundant explicit cast to the same type is not allowed [MISRA-044-3]
Do not use the volatile keyword [MISRA-046_a-3]
Evaluation order of an expression is implementation dependent [MISRA046_c-3]
Evaluation order of an expression is implementation dependent [MISRA046_d-3]
BENEFITS
This rule prevents from getting/putting values which are out of range.
EXAMPLE
void foo()
{
int j;
int k[10];
int m;
m = k[j]; /* Violation */
}
REPAIR
void moo()
{
int j;
int k[10];
int m;
if ((j < 10) && (j >= 0)) /* OK */
{
m = k[j];
}
}
REFERENCES
Origin: Misra Guidelines - Rule 4
BENEFITS
Prevents from overflow.
EXAMPLE
void main()
{
int i = 4;
int j = 2;
int k = j << i;
}
/* Violation */
REPAIR
Do not use left shifting of an integer.
REFERENCES
Origin: Misra Guidelines - Rule 4
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
BENEFITS
Minimal required character set.
EXAMPLE
void foo() {
char c1 = '$';
char c2 = '`';
}
/* Violation */
/* Violation */
REPAIR
Do not use characters no defined in the ISO C standard.
REFERENCES
1. Origin: Misra Guidelines - Rule 5
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 9
Values of character types shall be restricted to a defined and documented subset of ISO
10646-1 [MISRA-006-3]
DESCRIPTION
"The chosen implementation of C shall conform to a subset of
ISO 10646-1, and the chosen subset shall be documented."
Explicitly specified numeric value of character may not conform to
chosen subset of ISO 10646-1.
BENEFITS
Values of character types are defined and documented as subset of ISO
10646-1.
EXAMPLE
void foo()
{
const char * s[] = {"a",
"\012" /* Violation */
};
}
REPAIR
Define character types as subset of ISO 10646-1.
REFERENCES
1. Origin: Misra Guidelines - Rule 006
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 10
BENEFITS
Prevents from various undefined and implementation-defined behaviours
associated with
them and they shall not be used.
EXAMPLE
#include <stddef.h>
void foo() {
wchar_t* x = L"Fred";/* Violation */
}
REPAIR
#include <stddef.h>
void foo() {
char* x = "Fred";/* OK */
}
REFERENCES
1. Origin: Misra Guidelines - Rule 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 13
The basic types of char, int, short, long, float and double should not be used, but specificlength equivalents should be typedef'd [MISRA-013-3]
DESCRIPTION
"The storage length of types can vary from compiler to compiler. It is
safer
if programmers work with types which they know to be of a given length."
Rule reports a violation message if basic numerical type is used
(e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA2004-6_3
EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)
BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."
EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
char* p_char,
float& r_float)
{
double h;
const int z = 1;
return 1;
REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}
/* OK (plain char) */
/* OK (typedef name starts with 'bool'
/* OK (bit-bield type) */
/*
/*
/*
/*
OK
OK
OK
OK
(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
REFERENCES
1. Misra Guidelines - Rule 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-9-2
NOTES
If a type of variable is a typedef to char, then a violation is reported
only
on a typedef declaration.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
typedef char CHAR; // Violation
char foo(char)
{
char var1;
CHAR var2;
}
// Violation x 2
// Violation
// OK - Violation is reported on a typedef declaration
char (*fptr1)();
void (*fptr2)(char);
// Violation
// Violation
REPAIR
typedef unsigned char CHAR;
// OK
// OK
// OK
}
unsigned char (*fptr1)();
void (*fptr2)(unsigned char);
// OK
// OK
REFERENCES
1. Origin: Misra Guidelines - Rule 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 4
The underlying bit representations of floating point numbers shall not be used [MISRA-016-3]
DESCRIPTION
The underlying bit representations of floating point numbers shall not be
used
in any way by the programmer.
BENEFITS
Prevents from casting with possible data losing.
EXAMPLE
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
long * pl;
pi
pi
ps
pl
=
=
=
=
(int*)pf;
(int*)pd;
(short*)pf;
(long*)pf;
/*
/*
/*
/*
Violation
Violation
Violation
Violation
REPAIR
void foo()
{
int* pi;
float* pf;
double* pd;
short int* ps;
pf = (float*)pd;
ps = (short*)pi;
}
/* OK */
/* OK */
*/
*/
*/
*/
REFERENCES
1. Origin: Misra Guidelines - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.17 Types, AV Rule 147
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
unsigned long lVar = 65537; /* Violation */
REPAIR
unsigned long lVar = 65537L; /* OK */
REFERENCES
Origin: Misra Guidelines - Rule 18
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
unsigned long arrL[] = {
0,
1,
32767,
32768,
65535,
65536, /* Violation */
2147483547,/* Violation */
2147483648,
4294967295
};
REPAIR
unsigned long arrL[] = {
0,/* OK */
1, /* OK */
32767, /* OK */
32768, /* OK */
65535,/* OK */
65536L, /* OK */
2147483547L,/* OK */
2147483648,/* OK */
4294967295/* OK */
};
REFERENCES
Origin: Misra Guidelines - Rule 18
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
unsigned long lVar = 32768; /* Violation */
REPAIR
unsigned long lVar = 32768U; /* OK */
unsigned long lVar3 = 32767; /* OK */
unsigned long lVar4 = 65536; /* OK */
REFERENCES
Origin: Misra Guidelines - Rule 18
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
unsigned long arrL[] = {
0,
1,
32767,
32768, /* Violation */
65535, /* Violation */
65536,
2147483547,
2147483648,
4294967295
};
REPAIR
unsigned long arrL[] = {
0,/* OK */
1, /* OK */
32767, /* OK */
32768U, /* OK */
65535U,/* OK */
65536, /* OK */
2147483547,/* OK */
2147483648,/* OK */
4294967295/* OK */
};
REFERENCES
Origin: Misra Guidelines - Rule 18
NOTES
This rule active for C code only.
BENEFITS
The rule prevents undefined behaviours.
EXAMPLE
void goo()
{
foo1();
foo2();
}
void foo2();
REPAIR
//--------file.h----------------void foo1_h();
void foo2_h(){}
//--------file.c----------------#include "file.h"
void foo1();
void foo2(){}
void goo()
{
foo1();
foo2();
foo1();
foo2();
}
/*
/*
/*
/*
OK
OK
OK
OK
function
function
function
function
REFERENCES
1. Misra Guidelines - Rule 20
2. Multiplatform Porting to 64 Bits
http://www.ddj.com/showArticle.jhtml;jsessionid=GJEIYBMN14LMIQSNDBCSKHSCJU
MEKJVN?articleID=184406427
BENEFITS
Prevents using global variables.
EXAMPLE
int globalVar;
// Violation
REPAIR
void foo( ) {
int localVar;
}
// OK
REFERENCES
1. Misra Guidelines - Rule 22
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 57
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 136
4. ISO/DIS 26262
point 8.4.4
BENEFITS
Prevents from accidentally overwriting of functions or variables
EXAMPLE
int g1; /* Violation */
void foo1() {}; /* Violation */
REPAIR
static int g2; /* OK */
static void foo2(){}; /* OK */
REFERENCES
1. Origin: Misra Guidelines - Rule 23
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 137
BENEFITS
Rule prevents variable-name hiding which can be confusing.
EXAMPLE
static unsigned short x;
static unsigned short y;
void foo( ) {
extern unsigned short x;
// Violation
extern unsigned short y;
// Violation
{
extern unsigned short y; // Violation
}
}
REPAIR
Do not declare variables simultaneously with internal and external
linkage in the same translation unit.
REFERENCES
1. Origin:
External object should not be declared in more than one file [MISRA-027-3]
DESCRIPTION
External objects should be declared in header files which are then
included in all
those source files which use these objects. This rule will inform about
multiple
declarations of symbols.
BENEFITS
Rule improves readability, clarity of code and prevents errorneous code.
EXAMPLE
/* misra_027.h */
/* Do not declare external object in more than one file. */
extern int a;
/* Violation */
/* misra_027.c */
#include "misra_027.h"
extern int a;
REPAIR
/* misra_027.h */
extern int a;
/* OK */
/* misra_027.c */
#include "misra_027.h"
int a;
REFERENCES
1. Origin: Misra Guidelines - Rule 27
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 139
BENEFITS
Prevents from dependencies on compiler.
EXAMPLE
void foo()
{
register int a;
}
// Violation
REPAIR
Do not use the 'register' storage class specifier.
REFERENCES
1. Origin:
BENEFITS
Rule improves readability, clarity of code and prevents error prone code.
EXAMPLE
struct tagSTRUCT {
int _x;
};
struct tagSTRUCT t = { "abc" }; /* Violation - 'char *' initialiser does
not match type of field _x: */
REPAIR
struct tagSTRUCT {
int _x;
};
struct tagSTRUCT s = { 123 }; /* OK - initialiser of type int matches type
of field _x: */
REFERENCES
Origin: Misra Guidelines - Rule 29
All automatic variables shall have been assigned a value before being used [MISRA-030-3]
DESCRIPTION
"The intent of this rule is that all variables shall have been written to
before
they are read. This does not necessarily require initialisation at
declaration.
Ideally a static check should be performed for any automatic variables
which
might be used without having first been assigned a value"
See also: INIT-06, INIT-10, INIT-14, BD-PB-NOTINIT
NOTES
The rule assumes that local variable might be initialized
by passing its non-const pointer to an external function.
BENEFITS
Prevents reading from uninitialized variables.
EXAMPLE
void foo( ) {
int b;
b++;
}
// Violation
REPAIR
void foo( ) {
int b = 0;
b++;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
#ifndef uint8_t
typedef unsigned char
#endif
#ifndef uint16_t
typedef unsigned short
#endif
#ifndef uint32_t
typedef unsigned int
#endif
void foo( )
uint8_t
uint16_t
uint32_t
it8
it16
it32
it16
<<
<<
>>
>>
uint8_t;
uint16_t;
uint32_t;
{
it8;
it16;
it32;
8; //
16; //
32; //
it8;//
Violation
Violation
Violation
Violation
REPAIR
#ifndef uint8_t
typedef unsigned char
uint8_t;
#endif
#ifndef uint16_t
typedef unsigned short
#endif
#ifndef uint32_t
typedef unsigned int
#endif
void foo( )
uint8_t
uint16_t
uint32_t
uint16_t;
uint32_t;
{
it8;
it16;
it32;
it8 << 7;
it16 << 15;
it32 >> 31;
if (it8 > 0
it16 >>
// OK
// OK
// OK
&& it8 < sizeof( it8 ))
it8; // OK
REFERENCES
Origin: Misra Guidelines - Rule 38
BENEFITS
Prevents unexpected loss of data/precision.
EXAMPLE
void foo()
{
int i=2;
int j=3;
int k;
k=j/i;
REPAIR
void boo()
{
int i=2;
int j=3;
int k;
/*
REFERENCES
1. Origin: Misra Guidelines - Rule 41
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
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
REFERENCES
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 */
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 */
REFERENCES
Origin: Misra Guidelines - Rule 100
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
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*, ...);
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*, ...);
/* OK */
p1 = (PTF1)foo1; /* OK */
p3 = foo3;
/* OK */
p4 = (PTF4)foo4; /* OK */
}
REFERENCES
Misra Guidelines - Rule 105
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
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
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
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
REFERENCES
1. Origin:
BENEFITS
Prevents writing error prone code and provides maintainability.
EXAMPLE
double sqrt(double arg)
{
return (arg);
}
/* Violation - redefined */
/* Violation - redefined */
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
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
BENEFITS
Prevents changing the locate from the standard C locate.
EXAMPLE
#include <locale.h> /* Violation */
void foo(void)
{
/* Set the locale back to the default environment */
setlocale(LC_ALL, "C");
}
REPAIR
Do not use 'setlocale' functions.
REFERENCES
Origin: Misra Guidelines - Rule 121
MISRA2004
MISRA C 2004
RULES
Avoid implicit conversions between signed and unsigned integer types
[MISRA2004-10_1_a-3]
Avoid implicit conversions between integer and floating types [MISRA200410_1_b-3]
Avoid implicit conversions of complex expressions [MISRA2004-10_1_c-3]
Avoid implicit conversions from wider to narrower types [MISRA2004-10_1_d3]
Avoid implicit conversions of function return expressions [MISRA200410_1_e-3]
Avoid implicit conversions of complex expressions [MISRA2004-10_1_f-3]
Avoid implicit conversions of function arguments [MISRA2004-10_1_g-3]
Avoid implicit conversions between signed and unsigned integer types
[MISRA2004-10_1_h-3]
Avoid implicit conversions of complex expressions [MISRA2004-10_1_i-3]
Avoid implicit conversions of float type resulting in a loss of
information [MISRA2004-10_2-3]
Avoid implicit conversions of float type resulting in a loss of
information [MISRA2004-10_2_b-3]
The value of a complex expression of integer type shall only be cast to a
type of the same signedness that is no wider than the underlying type of
the expression [MISRA2004-10_3-3]
The value of a complex expression of floating type may only be cast to a
narrower floating type [MISRA2004-10_4-3]
If the bitwise operators ~ and << are applied to an operand of underlying
type unsigned char or unsigned short, the result shall be immediately cast
to the underlying type of the operand [MISRA2004-10_5-3]
A 'U' suffix shall be applied to all constants of unsigned type
[MISRA2004-10_6-5]
Conversions shall not be performed between a pointer to a function and any
type other than an integral type [MISRA2004-11_1-3]
Conversions shall not be performed between a pointer to object and any
type other than an integral type, another pointer to object type or a
pointer to void [MISRA2004-11_2-3]
Conversions shall not be performed between a pointer to object and any
type other than an integral type, another pointer to object type or a
pointer to void [MISRA2004-11_2_b-3]
Conversions shall not be performed between a pointer to object and any
type other than an integral type, another pointer to object type or a
pointer to void [MISRA2004-11_2_c-3]
A cast should not convert a pointer type to an integral type [MISRA200411_3_a-3]
signed and unsigned char type shall be used only for the storage and use
of numeric values [MISRA2004-6_2-3]
typedefs that indicate size and signedness should be used in place of the
basic types [MISRA2004-6_3-3]
Bit fields shall only be defined to be of type unsigned int or signed int
[MISRA2004-6_4-3]
Bit fields of signed types shall be at least 2 bits long [MISRA2004-6_5-3]
Octal constants (other than zero) and octal escape sequences shall not be
used [MISRA2004-7_1-3]
The static storage class specifier shall be used in definitions and
declarations of objects and functions that have internal linkage
[MISRA2004-8_11-3]
When an array is declared with external linkage, its size shall be stated
explicitly or defined implicitly by initialisation [MISRA2004-8_12-3]
Whenever a function is declared or defined, its type shall be explicitly
stated [MISRA2004-8_2_a-3]
Whenever an object is declared or defined, its type shall be explicitly
stated [MISRA2004-8_2_b-3]
Use identical types in declaration and definition [MISRA2004-8_3_a-3]
Use identical types in declaration and definition [MISRA2004-8_3_b-3]
There shall be no definitions of objects or functions in a header file
[MISRA2004-8_5-3]
Always declare functions at file scope [MISRA2004-8_6-3]
Objects shall be defined at block scope if they are only accessed from
within a single function [MISRA2004-8_7-3]
Braces shall be used to indicate and match the structure in the non-zero
initialization of arrays and structures [MISRA2004-9_2-3]
In an enumerator list, the "=" construct shall not be used to explicitly
initialise members other than the first, unless all items are explicitly
initialised [MISRA2004-9_3-3]
Avoid implicit conversions between signed and unsigned integer types [MISRA2004-10_1_a-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used.
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = u32a;
s32b = s32a + u32a;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = (signed int)u32a;
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
float f32a;
unsigned int u32a;
f32a = u32a;
f32a = f32a + u32a;
f32a = u32a + 2.5f;
}
REPAIR
void Conv1_int( ) {
float f32a;
unsigned int u32a;
/* Violation */
/* Violation */
/* Violation */
f32a = (float)u32a;
f32a = f32a + (float)u32a;
f32a = (float)u32a + 2.5f;
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
u32a = u32b + u16b + u16a;
u32a = u16b + (u16a + u32b);
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
The underlying type of an integer constant is determined according
to its magnitude and signedness.
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = u32a;
u8a = u32a;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = (unsigned short)u32a;
u8a = (unsigned char)u32a;
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
unsigned int Conv_ret1( signed char a )
{
return a;
/* Violation */
}
REPAIR
unsigned int Conv_ret1( signed char a )
{
return (unsigned int)a;
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.
EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;
/* Violation */
REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;
u32a = (unsigned int)(u16b + u16a);
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double(si);
/* Violation */
takes_unsigned_int(uc);
/* Violation */
takes_signed_int(ui);
/* Violation */
}
REPAIR
void takes_signed_double(double);
void takes_unsigned_int(unsigned int);
void takes_signed_int(signed int);
void foo(signed int si, unsigned int ui) {
unsigned char uc;
takes_signed_double((double) si);
takes_unsigned_int(ui);
takes_signed_int((int) ui);
}
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. ISO/DIS 26262
point 8.4.4
Avoid implicit conversions between signed and unsigned integer types [MISRA2004-10_1_h-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used
when variables are initialized.
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = u32a;
}
/* Violation */
REPAIR
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = (signed int)u32a;
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.
EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = u16b + u16a;
}
/* Violation */
REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = (unsigned int)(u16b + u16a);
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a
=
=
=
=
f32a;
f32a;
f64a;
f32b + f32a + f64b;
REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
//
//
//
//
Violation
Violation
Violation
Violation
u32b
s32b
f32a
f64a
=
=
=
=
(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}
REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
// Violation
// Violation
// Violation
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
The value of a complex expression of integer type shall only be cast to a type of the same
signedness that is no wider than the underlying type of the expression [MISRA2004-10_3-3]
DESCRIPTION
Rule reports violation if the value of a complex expression of integer
type
is cast to a type that has different signedness or is wider than
the underlying type of the expression.
"The term 'complex expression' is defined to mean any expression that is
not:
- a constant expression
- an lvalue (i.e. an object)
- the return value of a function
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
BENEFITS
The rule prevents behaviours inconsistent with developer expectations.
EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}
REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =
/*
/*
/*
/*
OK
OK
OK
OK
*/
*/
*/
*/
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9
The value of a complex expression of floating type may only be cast to a narrower floating
type [MISRA2004-10_4-3]
DESCRIPTION
"If a cast is to be used on any complex expression,
the type of cast that may be applied is severely restricted.
Conversions on complex expressions are often a source of
confusion and it is therefore wise to be cautious."
BENEFITS
Prevents loss of data.
EXAMPLE
typedef float
typedef double
typedef long double
float32_t;
float64_t;
float128_t;
void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float64_t)(f32a + f32b);
/* Violation */
REPAIR
typedef float
typedef double
typedef long double
float32_t;
float64_t;
float128_t;
void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float32_t)(f64a + f64b);
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
If the bitwise operators ~ and << are applied to an operand of underlying type unsigned char
or unsigned short, the result shall be immediately cast to the underlying type of the operand
[MISRA2004-10_5-3]
DESCRIPTION
"When these operators (~ and <<) are applied to small integer types
(unsigned char or unsigned short),
the operations are preceded by integral promotion,
and the result may contain high order bits which have not been
anticipated.
A similar problem exists when the << operator is used on small integer
types
and high order bits are retained."
BENEFITS
Rule prevents high order bits retaining.
EXAMPLE
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = (~port) >> 4;
*/
result_16 = ((port << 4) & mode) >> 6;
*/
}
REPAIR
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
/* Violation
/* Violation
void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = ((uint8_t)(~port)) >> 4 ;
result_16 = (
(uint16_t) (~(uint16_t)port)
) >> 4 ;
result_16 = ((uint16_t)((uint16_t)port << 4) & mode) >> 6;
}
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-10
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
/* the type depends from the implemented size of the various integer types
*/
long lVar = 2147483648;
/* Violation */
REPAIR
long lVar = 2147483648U;
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. Origin: Misra Guidelines - Rule 18
Conversions shall not be performed between a pointer to a function and any type other than
an integral type [MISRA2004-11_1-3]
DESCRIPTION
"Conversion of a function pointer to a different type of pointer results
in undefined behaviour. This means that a function pointer can be
converted
to or from and integral type. No other conversion involving function
pointers
are permitted."
This rule allows conversions between two pointers to function if these
pointers
have exactly the same type.
As integral types the rule detects the following types: bool, char, short,
int, long, long long, wchar_t and typedefs to mentioned types.
BENEFITS
Prevents undefined behaviour and loss of data.
EXAMPLE
/* Examples of incorrect code */
typedef int (*func_t1)();
typedef short (*func_t2)();
void foo()
{
int (*fp1)(char* c);
func_t1 t1 ;
func_t2 t2 ;
int* ptr_int;
t1 = t2;
t1 = fp1;
t1 = (func_t2)t1;
fp1 = t2;
ptr_int = t1;
}
/*
/*
/*
/*
/*
Violation
Violation
Violation
Violation
Violation
*/
*/
*/
*/
*/
REPAIR
/* Examples of correct code */
typedef int (*func_t1)();
typedef int (*func_t2)();
int func ();
void foo()
{
func_t1 t1 ;
func_t2 t2 ;
int i;
t1 = t2;
t1 = func;
i = t1;
/* OK */
/* OK */
/* OK */
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11
Conversions shall not be performed between a pointer to object and any type other than an
integral type, another pointer to object type or a pointer to void [MISRA2004-11_2-3]
DESCRIPTION
A pointer to object can be only converted to or from:
a) an integral type
b) another pointer to object type
c) a pointer to void
See also: MISRA2004-11_2_b, MISRA2004-11_2_c
BENEFITS
Rule prevents undefined conversions.
EXAMPLE
typedef int (*FunctionPointer)(void);
struct A;
void foo(int* int_p, float fl, FunctionPointer funct_ptr) {
struct A *incomplete_type_ptr;
int_p = (int*)fl;
REPAIR
Do not perform illegal conversions.
REFERENCES
Conversions shall not be performed between a pointer to object and any type other than an
integral type, another pointer to object type or a pointer to void [MISRA2004-11_2_b-3]
DESCRIPTION
A pointer to object can be only converted to or from:
a) an integral type
b) another pointer to object type
c) a pointer to void
This rule is a complementary rule to rule MISRA2004-11_2 and reports
a violation message if illegal conversions between type of declared
function parameter and type of passed argument is found.
See also: MISRA2004-11_2, MISRA2004-11_2_c
BENEFITS
Rule prevents undefined conversions.
EXAMPLE
typedef int (*FunctionPointer)(void);
struct A;
void someFunction(int *);
REPAIR
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11
Conversions shall not be performed between a pointer to object and any type other than an
integral type, another pointer to object type or a pointer to void [MISRA2004-11_2_c-3]
DESCRIPTION
A pointer to object can be only converted to or from:
a) an integral type
b) another pointer to object type
c) a pointer to void
This rule is a complementary rule to rule MISRA2004-11_2 and reports
a violation message if illegal conversions between function return
type and type of returned expression is found.
See also: MISRA2004-11_2, MISRA2004-11_2_b
BENEFITS
Rule prevents undefined conversions.
EXAMPLE
typedef int (*FunctionPointer)(void);
struct A;
int* someFunction(FunctionPointer funct_ptr, int flag)
{
struct A *incomplete_type_ptr;
if(flag)
{
return incomplete_type_ptr;
}else{
return funct_ptr;
}
}
REPAIR
Do not perform illegal conversions.
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11
EXCEPTIONS
The rule allows to cast to UINT_PTR or INT_PTR type. These types are
integral
types that scale to the size of a pointer for both 32-bit and 64-bit
Windows.
BENEFITS
Prevents undefined or implementation-defined behaviour.
EXAMPLE
void foo( ) {
int* pi;
int i;
i = (int) pi;
}
// Violation
REPAIR
Do not cast pointers to non-pointers.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
2. Misra Guidelines rule 45
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 7
4. http://msdn2.microsoft.com/en-gb/library/aa489560.aspx
5. http://www.codeproject.com/system/64BitOSAndPortingIssues.asp
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
7. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-9
8. ISO/DIS 26262
point 8.4.4
EXCEPTIONS
The rule allows to cast integer constant '0' to pointer type.
BENEFITS
Rule prevents undefined or implementation-defined behaviour.
EXAMPLE
void foo( ) {
int* pi;
int i;
pi = (int*)i;
}
// Violation
REPAIR
Do not cast non-pointers to pointers.
REFERENCES
1. Origin: Misra Guidelines rule 45
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
4. ISO/DIS 26262
point 8.4.4
A cast should not be performed between a pointer to object type and a different pointer to
object type [MISRA2004-11_4-3]
DESCRIPTION
"A cast should not be performed between a pointer to object type and a
different
pointer to object type. Conversions of this type may be invalid if the new
pointer type requires a stricter alignment.
Pointer types can be classified as follows:
- Pointer to object
- Pointer to function
- Pointer to void
- The null pointer constant (the value 0 cast to type void *)"
NOTES
Pointers which are different only const or volatile qualifier are not
checked
by this rule.
BENEFITS
Prevents incorrect pointer alignment.
EXAMPLE
void foo( )
{
unsigned int* ui;
signed char* sc;
/* Examples of incorrect code */
ui = (unsigned int*) sc;
ui = (unsigned int*) ≻
}
REPAIR
/* Violation */
/* Violation */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
2. Origin: Misra Guidelines rule 45
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-7
4. ISO/DIS 26262
point 8.4.4
A cast shall not be performed that removes any const or volatile qualification from the type
addressed by a pointer [MISRA2004-11_5-3]
DESCRIPTION
"Any attempt to remove the qualification associated with the addressed
type by
using casting is a violation of the principle of type qualification.
Notice that the qualification referred to here is not the same as any
qualification that may be applied to the pointer itself."
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
typedef unsigned short uint16_t;
void foo( )
{
uint16_t *pi, **ppi;
uint16_t * const * pcpi; /* pointer
const uint16_t * * ppci; /* pointer
const uint16_t * pci;
/* pointer
volatile uint16_t * pvi; /* pointer
pi = (uint16_t *)pci;
pi = (uint16_t *)pvi;
ppi = (uint16_t * *)pcpi;
ppi = (uint16_t * *)ppci;
/*
/*
/*
/*
to
to
to
to
Violation
Violation
Violation
Violation
const pointer */
pointer to const */
const */
volatile */
*/
*/
*/
*/
REPAIR
Do not cast from 'const' or 'volatile' type addressed by a pointer to
'non-const'
or 'non-volatile' type.
REFERENCES
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int x, y;
x = 0, y = 0;
}
// Violation
REPAIR
void foo() {
int x, y;
x = 0;
y = 0;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-18-1
The underlying bit representations of floating-point values shall not be used [MISRA200412_12-3]
DESCRIPTION
"The storage layout used for floating-point values may vary from one
compiler to
another, and therefore no floating-point manipulations shall be made which
rely
directly on the way the values are stored. The in-built operators and
functions,
which hide the storage details from the programmer, should be used."
NOTES
In many cases floating point bit fields will be flagged as syntax errors.
BENEFITS
Prevents implementation-defined behaviour.
EXAMPLE
struct S {
float f:6; // Violation
};
union U {
float f:6; // Violation
};
REPAIR
struct S {
int f:6; // OK
};
union U {
int f:6; // OK
};
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 3-9-3
The increment (++) and decrement (--) operators should not be mixed with other operators in
an expression [MISRA2004-12_13-3]
DESCRIPTION
"It is the intention of the rule that when the increment or decrement
operator
is used, it should be the only side-effect in the statement.
The use of increment and decrement operators in combination with other
arithmetic operators is not recommended because:
- It can significantly impair the readability of the code
- It introduces additional side effects into a statement with the
potential for
undefined behaviour
It is safer to use these operations in isolation from any other arithmetic
operators."
BENEFITS
Improves readability and maintainability.
Reduces risk of potential undefined behaviour
caused by additional side effects
EXAMPLE
void foo() {
int x, y;
x = --y + x++;
}
/* Violation */
REPAIR
void foo() {
int x, y;
--y;
x = y + x;
x++;
}
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-10
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int a, b;
b = a = 0;// Violation
}
REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
NOTES
Macro's body is excluded from checking.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int a, b;
b = (a = 0);// OK
b = (a + 0);// Violation
}
REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
b = a + 0;// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( )
{
int a, b;
b = a * (-1);
}
// Violation
REPAIR
void foo( )
{
int a, b;
b = a * -1;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
SINCE
v7.0
BENEFITS
Rule increases safety in arithmetic operations.
EXAMPLE
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
REPAIR
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus(
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a + (b
}
) {
10;
65535;
0;
+ c); /* OK d is 65545 */
void fooMultiply( ) {
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a * (b
10;
65535;
0;
* c); /* OK d is 655350 */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
Use parentheses unless all operators in the expression are the same [MISRA2004-12_1_e-3]
DESCRIPTION
"In addition to the use of parentheses to override default operator
precedence,
parentheses should also be used to emphasise it. It is easy to make a
mistake
with the rather complicated precedence rules of C, and this approach helps
to
avoid such errors, and helps to make the code easier to read. However, do
not
add too many parentheses so as to clutter the code and make it unreadable.
Use parentheses unless all operators in the expression are the same."
See also: MISRA2004-12_5, CODSTA-90
NOTES
The operands of a logical && and || are checked by the rule MISRA2004-12_5
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( ) {
int a, b;
b = a * a + a;
}
// Violation
REPAIR
void foo( ) {
int a, b;
b = (a * a) + a;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
Note:
Nested parentheses level is set on 10 but can be changed. To change the
default level of the nested parentheses modify the main "Count" expression
of the rule (Collector A) from "$$ > 9" to "$$ > N" using desired
threshold
value for N. Rule's header should be also changed accordingly.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( )
{
int a, b,c,d;
a=(((((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8)/(b+d))+3; // Violation
REPAIR
void foo( )
{
int a, b,c,d;
int h;
h = (((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8;
a =(h*(b+d))+3;
}
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2004-12_2_a-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
As an example of what can go wrong, consider x = b[i] + i++; This will
give
different results depending on whether b[i] is evaluated before i++ or
vice
versa. The problem could be avoided by putting the increment operation
in a separate statement."
The rule reports a violation if a variable is used and
incremented/decremented
in the same statement.
See also: MISRA2004-12_4_a, MISRA2004-12_4_b
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
void foo( )
{
int a, b[10];
a = b[a] + a++; // Violation
}
REPAIR
void foo( )
{
int a, b[10];
a = b[a] + a;
a++;
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
Don't write code that depends on the order of evaluation of function arguments [MISRA200412_2_b-1]
DESCRIPTION
The order of evaluation of function arguments is unspecified. This means
that
if arguments contain side effects then the order in which side effects
take
place is unspecified. A function call can give different results depending
on which of the function's arguments is evaluated first.
By side effect we understand accessing a volatile object, modifying an
object
or calling a function that does any of those operations.
Rule checks calls of functions that have at least two arguments.
A violation is reported if
* a volatile object is read or modified, or
* a non-volatile object is modified
during evaluation of a function argument and the same object is read or
modified during evaluation of function's other argument.
EXCEPTIONS
Only one level of function calls is checked.
BENEFITS
Rule prevents writing source code which might produce different results
between compilers.
EXAMPLE
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
Transmogrify(Bump(count),Bump(count)); // Violation
Transmogrify(count++,count);
// Violation
REPAIR
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
int temp1 = Bump(count);
Transmogrify(temp1,Bump(count)); // OK
Transmogrify(count,count);
// OK
count++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 31
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
5. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2004-12_2_c-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur. Those points in the evaluation of
an
expression at which all previous side effects can be guaranteed to have
taken
place are called sequence points. Sequence points and side effects are
described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].
Note that the order of evaluation problem is not solved by the use of
parentheses, as this is not a precedence issue."
"If a function is called via a function pointer there shall be no
dependence on
the order in which function designator and function arguments are
evaluated.
p->task_start_fn(p++);"
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p++ );
}
// Violation
REPAIR
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p );
p++;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
Don't write code that depends on the order of evaluation of expression that involves a
function call [MISRA2004-12_2_d-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
Rule reports a violation if in an expression a function is called that
takes as
an argument a pointer or a reference to a non-const variable and modifies
this
variable, and in the same expression the variable is used in some other
way.
NOTES
Rule assumes that a variable is modified in function if it is directly
modified
by assignment or body of function is not defined in current translation
unit.
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
int foo(int* ptr)
{
(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
i = foo(&j) + bar(j);
}
// Violation
REPAIR
int foo(int* ptr)
{
(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
int temp = foo(&j);
i = temp + bar(j);
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2004-12_2_e-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Assignments nested within expressions cause additional side effects. The
best
way to avoid any chance of this leading to a dependence on order of
evaluation
is to not embed assignments within expressions."
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
void foo( int x, int y, int z ) {
x = y = z / 3; // Violation
}
REPAIR
void foo( int x, int y, int z ) {
y = z / 3; // OK
x = y;
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
SINCE
v7.0
NOTES
Rule does not report violation if in a function call are used as arguments
more than one volatile. In this case should be used rule MISRA2004-12_2_b.
void goo(int, int);
void foo()
{
volatile int v;
goo(v, v); // Violation - MISRA2004-12_2_b
}
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
void foo( )
{
volatile int x;
int y;
y = x * x; // Violation
}
REPAIR
void foo( )
{
volatile int x;
int y;
y = x;
// OK
y = y * y;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
Don't write code that depends on the order of evaluation of function calls [MISRA2004-12_2_g3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
The rule reports a violation if in one expression are called two functions
that
use the same global or static variable and at least one function modifies
this
variable.
EXCEPTIONS
Only one level of function calls is checked.
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
int global;
int modify_global()
{
global++;
return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global() + use_global();
}
// Violation
REPAIR
int global;
int modify_global()
{
global++;
return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global();
a += use_global();
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The sizeof operator shall not be used on expressions that contain side effects [MISRA200412_3-3]
DESCRIPTION
"A possible programming error in C is to apply the sizeof operator to an
expression and expect the expression to be evaluated. However the
expression
is not evaluated: sizeof only acts on the type of the expression. To avoid
this
error, sizeof shall not be used on expressions that contain side effects,
as the side effects will not occur."
"The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
NOTES
Rule checks only three nested level of function calls.
EXCEPTIONS
An operand of the form sizeof(i) where i is volatile is permitted.
BENEFITS
Prevents error that are caused by believing that operand of sizeof is
evaluated.
EXAMPLE
int glob;
int fun_with_se(){
glob++; // side-effect
return glob;
}
void foo1(int i){
int
j =
l =
m =
j, k, l, m;
sizeof(k = 2);
// Violation - k is not set to 2
sizeof(i++);
// Violation - i is not incremented
sizeof(fun_with_se()); // Violation - glob is not incremented
REPAIR
int fun_without_se(){
// no side-effect
return 1;
}
void foo1(int i){
int j, k, l, m, n, o;
volatile int vol;
k = 2;
j = sizeof(k);
i++;
l = sizeof(i);
// examples of correct code
m = sizeof(fun_without_se());
n = sizeof(int);
o = sizeof(vol);
}
// OK
// OK
// OK
// OK
// OK - volatile objects are permitted
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 166
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-4
The right-hand operand of a logical && or || operator shall not contain side effects
[MISRA2004-12_4_a-3]
DESCRIPTION
"There are some situations in C or C++ where certain parts of expressions
may
not be evaluated. If these sub-expressions contain side effects then those
side
effects may or may not occur, depending on the values of other sub
expressions.
The operators which can lead to this problem are && and || where the
evaluation
of the right-hand operand is conditional on the value of the left-hand
operand.
The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
See also: MISRA2004-12_2_a, MISRA2004-12_4_b
NOTES
Rule checks only three nested level of function calls.
BENEFITS
Rule prevents conditional evaluation of the right-hand operand that can
easily
cause problems if the developer relies on a side effect occurring.
EXAMPLE
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i++)) ; // Violation
}
REPAIR
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i)) i++; // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 33
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 157
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-14-1
5. ISO/DIS 26262
point 8.4.4
The second or third operand of a ternary operator '?:' shall not contain side effects
[MISRA2004-12_4_b-4]
DESCRIPTION
"There are some situations in C or C++ code where certain parts of
expressions
may not be evaluated. If these sub-expressions contain side effects then
those
side effects may or may not occur, depending on the values of other
sub-expressions.
The operators which can lead to this problem are &&, || and ?:. In the
case of
the ?: operator, either the second or third operands are evaluated but not
both.
The ?: operator is specifically provided to choose between two subexpressions,
and is therefore less likely to lead to mistakes."
See also: MISRA2004-12_2_a, MISRA2004-12_4_a
NOTES
Rule checks only two nested level of function calls.
BENEFITS
Rule prevents conditional evaluation of the second or third operand of
ternary
operator that can easily cause problems if the developer relies on a side
effect
occurring.
EXAMPLE
int i;
int j;
int foo( ) {
return (i > j) ? j++ : i++; // Violation - developer expects 2nd and
3rd
// operand to be evaluated
}
REPAIR
int i;
int j;
int foo( ) {
if (i > j) {
++i;
return j++;
} else {
++j;
return i++;
}
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. ISO/DIS 26262
point 8.4.4
BENEFITS
"Parentheses are important in this situation both for readability
of code and for ensuring that the behaviour is as the programmer
intended."
EXAMPLE
int foo( int
{
if ( x ||
if ( x &&
if ( foo(
return 0;
}
x, int y, int z )
y && z );
// Violation
!y );
// Violation
x, y, z ) && x ); // Violation
REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
// OK
if ( x && ( !y ) );
// OK
if ( ( foo( x, y, z ) ) && x ); // OK
return 0;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Misra Guidelines - Rule 34
The operands of logical operators (&&, || and !) should be effectively Boolean [MISRA200412_6_a-3]
DESCRIPTION
"The operands of logical operators (&&, ||, !) should be 'effectively
Boolean'.
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule does not report violation if as an operand of logical operator is
used:
- Boolean-by-construct values
- boolean constant
- integer or enum constant defined as '0' or '1'
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types
BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.
EXAMPLE
int goo();
void foo()
{
int x, y, z;
z = (x > y) && goo();
z = (x > y) || goo();
z = !(x = y);
// Violation
// Violation
// Violation
REPAIR
int goo();
void foo()
{
int x, y, z;
z
z
x
z
=
=
=
=
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 36
Expressions that are effectively Boolean should not be used as operands to operators other
than (&&, ||, !, =, ==, !=, ?:) [MISRA2004-12_6_b-3]
DESCRIPTION
"Expressions that are effectively Boolean should not be used as operands
to operators other than (&&, ||, !, =, ==, !=, ?:).
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule reports violation if as an operand of operator
other than (&&, ||, !, =, ==, !=, ?:) is used:
- Boolean-by-construct values
- boolean constant
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types
BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.
EXAMPLE
int goo();
void foo()
{
int x, y, z;
z = (x > y) & (goo()); // Violation
z = x | (goo() != 0); // Violation
z = ~(x == y);
// Violation
}
REPAIR
int goo();
void foo()
{
int x, y, z;
int tmp;
tmp = x > y;
z = tmp & goo();
// OK
tmp = goo() != 0;
z = x | tmp;
// OK
tmp = x == y;
z = ~tmp;
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 36
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 4, Rule 4-5-1
Bitwise operators shall not be applied to operands whose underlying type is signed
[MISRA2004-12_7-3]
DESCRIPTION
"Bitwise operations (~, <<, >>, &, ^ and |) are not normally meaningful on
signed integers. Problems can arise if, for example, a right shift moves
the
sign bit into the number, or a left shift moves a numeric bit
into the sign bit.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
int foo( int x, int y )
{
x = y >> 2;
// Violation
x = y & 0x0F;
// Violation
return x | 5;
// Violation
}
REPAIR
int foo( int x, int y )
{
/* Caller must make sure x and y are not negative */
x = (unsigned int)y >> 2u;
/* OK */
x = (unsigned int)y & 0x0Fu;
/* OK */
return (unsigned int)x | 5u;
/* OK */
}
REFERENCES
The right-hand operand of a shift operator shall lie between zero and one less than the width
in bits of the underlying type of the left-hand operand [MISRA2004-12_8-3]
DESCRIPTION
"If, for example, the left-hand operand of a left-shift or right-shift is
a
16-bit integer, then it is important to ensure that this is shifted only
by a
number between 0 and 15 inclusive.
There are various ways of ensuring this rule is followed. The simplest is
for
the right-hand operand to be a constant (whose value can then be
statically
checked). Use of an unsigned integer type will ensure that the operand is
non-negative, so then only the upper limit needs to be checked
(dynamically at
run-time or by review). Otherwise both limits will need to be checked."
The rule checks right-hand operand of shift operator and reports a
violation
in following cases:
- the operand is a constant with negative value or with value that exceeds
the length (in bits) of the left-hand operand
- the operand is a non-const variable and it's value is not checked by
specific
pattern.
The specific pattern recognized by the rule requires the shift operator
to be wrapped by an 'if' statement which checks the variable's value
using
comparison operators (both "greater then" and "less then" operators must
be used).
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
uint8_t;
uint16_t;
{
uint8_t u8a;
u8a = (uint8_t) (u8a << 9); /* Violation */
u8a = (uint8_t) (u8a << p); /* Violation */
}
REPAIR
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
{
uint8_t u8a;
uint16_t u16a;
uint8_t;
uint16_t;
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-8-1
The unary minus operator shall not be applied to an expression whose underlying type is
unsigned [MISRA2004-12_9-3]
DESCRIPTION
"Applying the unary minus operator to an expression of type unsigned int
or
unsigned long generates a result of type unsigned int or unsigned long
respectively and is not a meaningful operation. Applying unary minus to an
operand of smaller unsigned integer type may generate a meaningful signed
result
due to integral promotion, but this is not good practice."
BENEFITS
Prevents unexpected result due to integral promotion.
EXAMPLE
void foo() {
unsigned char ui1;
signed short si2;
si2 = -ui1;
}
// Violation
REPAIR
void foo() {
unsigned char ui1;
signed short si2;
si2 = -(signed short) ui1;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
Assignment operators shall not be used in expressions that yield a Boolean value
[MISRA2004-13_1-3]
DESCRIPTION
"No assignments are permitted in any expression which is considered to
have a
Boolean value. This precludes the use of both simple and compound
assignment
operators in the operands of a Boolean-valued expression. However, it does
not
preclude assigning a Boolean value to a variable. If assignments are
required
in the operands of a Boolean-valued expression then they must be performed
separately outside of those operands. This helps to avoid getting "=" and
"=="
confused, and assists the static detection of mistakes."
NOTES
An expression is considered to represent a Boolean value either because
it appears in a position where a Boolean value is expected or because it
uses an operator that gives rise to a Boolean value. Boolean values are
expected in the following contexts:
- the controlling expression of an if statement
- the controlling expression of an iteration statement
- the first operand of the conditional operator ?
BENEFITS
Rule prevents getting "=" and "==" confused.
EXAMPLE
void foo()
{
int x;
int y;
int z;
z = !(x = y);
// Violation
// Violation
// Violation
REPAIR
void foo()
{
int x;
int y;
int z;
z = !(x == y);
// OK
if ((x > y) && (x == 4)); // OK
if (!(x == y));
// OK
}
REFERENCES
1. Misra Guidelines - Rule 35
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 160
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-1
Tests of a value against zero should be made explicit, unless the operand is effectively
Boolean [MISRA2004-13_2-3]
DESCRIPTION
"Where a data value is to be tested against zero then the test should be
made
explicit. The exception to this rule is when data represents a Boolean
value,
even though in C this will in practice be an integer."
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule does not report violation if as an operand of logical operator is
used:
- Boolean-by-construct values
- boolean constant
- integer or enum constant defined as '0' or '1'
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types
NOTES
Rule does not report violations on constant expressions.
BENEFITS
"This rule is in the interests of clarity, and makes clear the distinction
between integers and logical values."
EXAMPLE
int goo()
{
return 1;
}
void foo( int x, int y )
{
if (goo()) {}// Violation
if (y) {}
// Violation
}
REPAIR
int goo()
{
return 1;
}
void foo( int x, int y )
{
if (goo() != 0) {}// OK
if (y != 0) {}
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 49
NOTES
Rule does not detect indirect tests of equality and inequality which are
equally
problematic and are also forbidden by Misra standard:
if ( ( x <= y ) && ( x >= y ) )
{
/* ... */
}
BENEFITS
"The inherent nature of floating-point types is such that comparisons of
equality will often not evaluate to true even when they are expected to.
In
addition the behaviour of such a comparison cannot be predicted before
execution, and may well vary from one implementation to another. "
EXAMPLE
void foo() {
float x, y;
if (x == y);
if (x == 0.0f);
}
// Violation
// Violation
REPAIR
void foo( float epsilon ) {
float x, y;
if (x - epsilon <= y && y <= x + epsilon);
if (-epsilon <= x && x <= epsilon);
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 50
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 202
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-2
The controlling expression of a for statement shall not contain any objects of floating type
[MISRA2004-13_4-3]
DESCRIPTION
"The controlling expression may include a loop counter, whose value is
tested to
determine termination of the loop. Floating-point variables shall not be
used
for this purpose. Rounding and truncation errors can be propagated through
the
iterations of the loop, causing significant inaccuracies in the loop
variable,
and possibly giving unexpected results when the test is performed. For
example
the number of times the loop is performed may vary from one implementation
to
another, and may be unpredictable."
BENEFITS
Rule prevents unpredictable behaviour.
EXAMPLE
void foo( float max ) {
float y;
for (y = 0; y < max; y++);
}
// Violation
REPAIR
void foo( int max ) {
int y;
for (y = 0; y < max; y++);
}
// OK
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 13
The three expressions of a for statement shall be concerned only with loop control
[MISRA2004-13_5-3]
DESCRIPTION
"When present, the three expressions of a for statement shall be used only
for these purposes:
- First expression - Initialising the loop counter (i in the following
example)
- Second expression - Shall include testing the loop counter (i), and
optionally
other loop control variables (flag)
- Third expression - Increment or decrement of the loop counter (i)"
This rule analyzes for statements to find any variables that are used
within
initialization or update sections of the statements, but do not seem to be
concerned with loop control. Often, variables are initialized within the
for
statement even though they have nothing to do with stop condition of the
loop.
In extreme cases entire for statement blocks can be moved into the for
statement, which makes the code both error-prone and hard to read.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
void foo( )
{
int x, j;
for ( x = 5; j < 2 ; x++ );
for ( x = 5; x < 2 ; j++ );
}
REPAIR
void foo( )
{
// Violation
// Violation
int x, j;
for ( x = 5; x < 2; x++);
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 66
Do not modify for loop counter within a body of the loop [MISRA2004-13_6-3]
DESCRIPTION
"Loop counters shall not be modified in the body of the loop.
However other loop control variables representing logical values
may be modified in the loop, for example a flag to indicate that something
has been completed, which is then tested in the for statement."
NOTES
A
-
BENEFITS
Modification 'for' loop counter within a body of the loop can lead to
errors and confusion.
EXAMPLE
void foo( ) {
int i;
for ( i = 0; i < 5; i++ ) {
i = i + 3;
}
}
/* Violation */
REPAIR
void foo( ) {
int i;
for ( i = 0; i < 5; i = i + 3 ) {} /* OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 67
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 201
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-5-3
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_a-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a <= 1)&&(a >= 2));
if((a < 1)&&(a > 2));
if((a >= 2)&&(a <= 1));
if((a > 2)&&(a < 1));
}
//
//
//
//
Violation
Violation
Violation
Violation
//
//
//
//
OK
OK
OK
OK
REPAIR
void myFunction(int a)
{
if((a <= 5)&&(a >= 2));
if((a < 5)&&(a > 2));
if((a >= 2)&&(a <= 5));
if((a > 2)&&(a < 5));
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_aa-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b >= 2)
if(b < 2) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b >= 2)
if(b < 7) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ab-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b < 2)
if(b >= 2) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b < 2)
if(b >= 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ac-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b <= 2)
if(b < 3) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b <= 2)
if(b < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ad-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b == 2)
if(b < 1) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b == 2)
if(a < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ae-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 > b)
if(b < 5) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 > b)
if(b < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_af-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 >= b)
if(b < 5) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 >= b)
if(b < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ag-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 < b)
if(b > 1) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 < b)
if(b > 5) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ah-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 <= b)
if(b > 1) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 <= b)
if(b > 5) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ai-3]
DESCRIPTION
The rule reports violation if a result of boolean operation with unsigned
variable is always true or always false.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunc()
{
unsigned int a;
if (a >= 0)
// Violation
a++;
}
REPAIR
void myFunc()
{
unsigned int a;
if (a >= 2)
// OK
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_aj-3]
DESCRIPTION
The rule reports violation if a result of boolean operation with variable
of char type is always true or always false.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 128)
b++;
if (a < 256)
a++;
// Violation
// Violation
REPAIR
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 127)
b++;
if (a < 255)
a++;
}
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_ak-3]
DESCRIPTION
The rule reports violation if a result of boolean operation with variable
of short type is always true or always false.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65536)
a++;
if (b <= 32767)
b++;
// Violation
// Violation
REPAIR
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65535)
a++;
if (b <= 32766)
b++;
}
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_b-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > -1)&&(a < -2));
if((a >= -1)&&(a <= -2));
if((a < -2)&&(a > -1));
if((a <= -2)&&(a >= -1));
}
//
//
//
//
Violation
Violation
Violation
Violation
//
//
//
//
OK
OK
OK
OK
REPAIR
void myFunction(int a)
{
if((a > -5)&&(a < -2));
if((a >= -5)&&(a <= -2));
if((a < -2)&&(a > -5));
if((a <= -2)&&(a >= -5));
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_c-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > 0)&&(a < -1));
if((a < -1)&&(a >= 0));
if((a == -5)&&(a == 5));
if((3 < a)&&(-3 > a));
}
//
//
//
//
Violation
Violation
Violation
Violation
//
//
//
//
OK
OK
OK
OK
REPAIR
void myFunction(int a)
{
if((a < 0)&&(a > -1));
if((a > -1)&&(a <= 0));
if((a != -5)&&(a != 5));
if((3 > a)&&(-3 < a));
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_d-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '&&' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a, int b)
{
if((a > b)&&(a < b));
// Violation
if((a < b)&&(a >= b)); // Violation
}
REPAIR
void myFunction(int a, int b, int c)
{
if((a > b)&&(a < c));
// OK
if((a < b)&&(a >= c)); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_j-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a >= 0)||(a < 0));
if((5 > a)||(a > 3));
if((a <= 4)||(a >= 3));
}
// Violation
// Violation
// Violation
REPAIR
void myFunction(int a)
{
if((a >= 10)||(a < 0));
if((5 > a)||(a > 13));
if((a <= 4)||(a >= 13));
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_k-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > -4)||(a < -3));
if((-1 > a)||(-3 < a));
if((a < -3)||(-5 < a));
}
// Violation
// Violation
// Violation
REPAIR
void myFunction(int a)
{
if((a > -4)||(a < -13));
if((-11 > a)||(-3 < a));
if((a < -13)||(-5 < a));
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_l-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > -2)||(a < 1));
if((4 > a)||(-3 < a));
if((a > -4)||(2 > a));
}
// Violation
// Violation
// Violation
REPAIR
void myFunction(int a)
{
if((a < -2)||(a > 1));
if((4 < a)||(-3 > a));
if((a < -4)||(2 < a));
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_m-3]
DESCRIPTION
Rule reports violation if a result of expression that use a logical
operator '||' is always 'true' or always 'false'.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a, int b)
{
if((a >= b)||(a <= b)); // Violation
if((a < b)||(a >= b));
// Violation
}
REPAIR
void myFunction(int a, int b, int c)
{
if((a >= b)||(a <= c));
// OK
if((a < c)||(a >= b));
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_n-3]
DESCRIPTION
The rule reports a violation if equality operators (== and !=) or
relational
operators (<, >, <= and >=) as both operands use only constant values
or the same variable.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE > 0);
if(10 <= ONE);
if(ci > 0);
for(i = 5; i < i; i++);
if(ZERO > 10 && i > 3);
}
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE);
for(i = 5; i < ci; i++);
if(ZERO == en);
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_s-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < GREEN); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < RED); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_t-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > YELLOW); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > RED); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_u-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(YELLOW < col); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN < col); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_v-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN > col); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(BLUE > col); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_w-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
< 0);
< 16);
<= 15);
<= 16);
> 15);
> 16);
>= 0);
>= 16);
//
//
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
< 1);
< 15);
<= 0);
<= 1);
> 0);
> 1);
>= 1);
//
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_x-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(15 < col1);
if(16 < col1);
if(0 <= col1);
if(16 <= col1);
if(0 > col1);
if(16 > col1);
if(15 >= col1);
if(16 >= col1);
}
//
//
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(0 < col1);
if(1 < col1);
if(1 <= col1);
if(15 <= col1);
if(1 > col1);
if(15 > col1);
if(0 >= col1);
//
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_y-3]
DESCRIPTION
"Boolean operations whose results are invariant shall not be permitted."
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 14 );
if(col1 != 14 );
if(14 == col1);
if(14 != col1);
//
//
//
//
Violation
Violation
Violation
Violation
REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 15);
if(col1 != 15);
if(15 == col1);
if(15 != col1);
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
Boolean operations whose results are invariant shall not be permitted [MISRA2004-13_7_z-3]
DESCRIPTION
Rule reports a violation on an 'if' statement nested in an 'if' statement
if the result of expression in nested 'if' condition is always true
or always false.
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int b)
{
if(b > 2)
if(b >= 1)
/* Violation */
b++;
}
REPAIR
void foo(int b)
{
if(b > 2)
if(b >= 5)
/* OK */
b++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.
EXAMPLE
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
}
// Violation
REPAIR
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
// OK
else
{
// comment or action
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 60
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 192
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-2
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo(int a, int b)
{
if(a == a){
a = a + b;
}
else{
// Violation
a = a - b;
}
}
REPAIR
void foo(int a, int b)
{
if(a == 3){
a = a + b;
}
else{
a = a - b;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
There shall be no unreachable code after 'return', 'break', 'continue', and 'goto' statements
[MISRA2004-14_1_b-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code after 'return', 'break',
'continue' and 'goto' statements.
See also: MISRA2004-14_1_a, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// Violation
foo();
case 2:
j = 3;
return j; // Violation
foo();
}
}
REPAIR
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// OK
case 2:
j = 3;
return j; // OK
}
foo();
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo()
{
int unreachable_code = 1;
if(0)
{
unreachable_code = 2;
}
}
// Violation
REPAIR
There shall be no unreachable code
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo( int i ) {
switch (i) {
// Violation
i = 0;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}
REPAIR
void foo( int i ) {
switch (i) {
// OK
case 0:
i = 0;
break;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo( int i, int j )
{
for ( i = 0; i < 0; i++ )
{
j = 1;
}
}
// Violation
REPAIR
void foo( int i, int j )
{
for ( i = 0; i < 5; i++ )
{
j = 1;
}
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
NOTES
This rule does not report violations on the code inside loop.
Rule MISRA2004-14_1_g reports violations on the code inside loop.
BENEFITS
Rule helps avoid useless code.
EXAMPLE
int foo1( int c ) {
if ( c > 2 ) {
// Violation
return 0;
} else {
return 1;
}
return c;
// unreachable code
}
int foo2( int i ) {
switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return 2;
}
return i;
}
// Violation
// unreachable code
REPAIR
int foo1( int
if ( c > 2
return
} else {
return
}
}
c ) {
) {
0;
// OK
c;
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
There shall be no unreachable code after "if" or "switch" statement inside while/for/do...while
loop [MISRA2004-14_1_g-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation on the code inside loop if:
- the code is after 'if/else' construction, where each branch has
unconditional
'break', 'continue' or 'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_f
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
int foo( int c ) {
while ( c > 1 ) {
if ( c > 2 ) {
continue;
} else {
break;
}
// Violation
c++;
// unreachable code
}
for (int i = 0; i > 1; i++ ) {
switch(i){
// Violation
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}
c++;
// unreachable code
}
return c;
}
REPAIR
int foo( int c ) {
while ( c > 1 ) {
c++;
if ( c > 2 ) {
continue;
} else {
break;
}
}
// OK
}
return c;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
All non-null statements shall either have at least one side-effect however executed or cause
control flow to change [MISRA2004-14_2-3]
DESCRIPTION
"Any statement (other than a null statement) which has no side effect and
does
not result in a change of control flow will normally indicate a
programming
error, and therefore a static check for such statements shall be
performed."
A side effect and null statement are defined by ISO/IEC 9899:1999
standard.
"Accessing a volatile object, modifying an object, modifying a file,
or calling a function that does any of those operations are all side
effects,
which are changes in the state of the execution environment."
"A null statement (consisting of just a semicolon) performs no
operations."
For example, if an expression evaluation result is not used, because
a programmer forgot to use assignment operator to store the value,
or because he accidentally wrote "==" instead of "=", the statement
is considered not to have a side effect. Such programming errors
are potentially disastrous.
NOTES
Empty function body is not considered as violating this rule.
For purposes of this rule any function call is considered as
having side effects, even if no variable is modified as a result
of the function call.
The rule does not report violations on empty blocks.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
struct tagStruct {
int _iField;
char * _p;
};
int bar( );
void foo( ) {
int i = 0;
struct tagStruct s, *ps;
/* Examples of incorrect code - no side effects: */
i + 3;
/* Violation - result not
3;
/* Violation - result not
i;
/* Violation - result not
i + bar();
/* Violation - result not
ps->_p + s._iField;
/* Violation - result not
ps->_iField << s._iField; /* Violation - result not
*(ps->_p);
/* Violation - result not
}
used
used
used
used
used
used
used
REPAIR
struct tagStruct{
int _iField;
char * _p;
};
volatile struct tagStruct volStr;
int bar( );
void foo( ) {
int i = 0;
volatile int j = 0;
struct tagStruct s, *ps;
/* Examples of correct code - with side effects: */
i = i + 3;
/* OK - assignment */
i <<= 3;
/* OK - assignment */
bar();
/* OK - function call */
j;
/* OK - volatile variable */
volStr._p;
/* OK - volatile variable */
*/
*/
*/
*/
*/
*/
*/
if(ps->_iField){}
;
{}
/* OK - null statement */
/* OK - empty block */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
system
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 53
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 187
Null statement shall only occur on a line by itself or it may be followed by a comment
[MISRA2004-14_3-3]
DESCRIPTION
"Null statements should not normally be deliberately included, but where
they
are used they shall appear on a line by themselves.
White-space characters may precede the null statement to preserve
indentation.
If a comment follows the null statement then at least one white-space
character
shall separate the null statement from the comment.
The use of a white-space character to separate the null statement from any
following comment is required on the grounds that it provides an important
visual cue to reviewers."
See also: MISRA-054.
BENEFITS
"Following this rule enables a static checking tool to
warn of null statements appearing on a line with other text,
which would normally indicate a programming error."
EXAMPLE
void foo()
{
/* Violation */ ;
;/* Violation */
}
REPAIR
void goo()
{
/* OK */
;
; /* OK */
;
/* OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-3
BENEFITS
The goto statement can lead to errors and confusion.
EXAMPLE
int foo( int a ) {
if (a < 0) {
goto end;
}
a = foo(a-1);
end:
return a+1;
}
/* Violation */
REPAIR
int foo( int a ) {
/* Code was changed and does not use goto anymore */
if (a >= 0) {
a = foo(a-1);
}
return a+1;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rule 49
BENEFITS
Rule prevents using 'continue' which can lead to errors and confusion.
EXAMPLE
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
continue;
}
i /= 2;
}
}
/* Violation */
REPAIR
int bar( int );
void foo( int i ) {
while (i--) {
if (bar( i )) {
/* OK - code was changed and does not use continue anymore */
} else {
i /= 2;
}
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 14 Flow Control Structures - Rec. 53
3. Origin: Misra Guidelines - Rule 57
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 190
5. ISO/DIS 26262
point 8.4.4
For any iteration statement there shall be at most one break statement used for loop
termination [MISRA2004-14_6-3]
DESCRIPTION
"For any iteration statement there shall be at most one break statement
used
for loop termination. One break statement is allowed in a loop since this
allows, for example, for dual outcome loops or for optimal coding."
BENEFITS
"This rules is in the interests of good structured programming."
EXAMPLE
void foo( ) {
int a;
for (a = 0; a < 10; a++) { /* Violation */
if (a == 5) {
break;
}
if (a == 7) {
break;
}
}
}
REPAIR
void foo( ) {
int a;
for (a = 0; a < 10; a++) { /* OK */
if (a == 5 || a == 7) {
break;
}
}
}
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 14
A function shall have a single point of exit at the end of the function [MISRA2004-14_7-3]
DESCRIPTION
Every function should have a single point of exit.
NOTES
Calls of functions exit, abort, and _Exit from standard library stdlib.h
are detected by rule as exit points.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
int foo(int i)
{
if (i == 0) {
return 0;
// Violation
} else if (i == 1) {
return 1;
// Violation
} else {
return 2;
// Violation
}
}
int foo2(int a) {
int result;
if (a > 0) {
return result;
}
}
REPAIR
int foo(int i)
{
int result = 0;
// Violation
if (i == 0) {
result = 0;
} else if (i == 1) {
result = 1;
} else {
result = 2;
}
return result;
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 82
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 113
4. ISO/DIS 26262
point 8.4.4
The statement forming the body of a 'switch', 'while', 'do...while' or 'for' statement shall be a
compound statement [MISRA2004-14_8-3]
DESCRIPTION
" The statement that forms the body of a switch statement or a while,
do ... while or for loop, shall be a compound statement (enclosed within
braces), even if that compound statement contains a single statement."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x ) {
int i;
switch(i)
;
// Violation
// Violation
REPAIR
void foo( int x ) {
int i;
switch(i)
{
}
// OK
{foo( x );}
while (1)
{foo( x );}
// OK
do
// OK
{foo( x );}
while(1);
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 59
3. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-3-1
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x, int
{
int i, j;
if(x > 0)
//
x = i;
else if(y > 0) //
y = i;
else
y = j;
//
x = j;
}
y )
Violation
Violation
Violation
REPAIR
void foo( int x, int y )
{
int i, j;
if(x > 0)
// OK
{
x = i;
}
else if(y > 0) // OK
{
y = i;
}
else
{
y = j;
x = j;
// OK
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Misra Guidelines - Rule 59
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-1
A switch statement shall only contain switch labels and switch clauses, and no other code
[MISRA2004-15_0_a-3]
DESCRIPTION
"A switch statement shall only contain switch labels and switch clauses,
and no other code."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo(int a,int b)
{
int c;
switch(a)
{
case 1:
break;
c = 1;
/* Violation */
case 2:
break;
c = 2;
/* Violation */
default:
break;
c = 3;
/* Violation */
}
}
REPAIR
void foo1(int a,int b)
{
int c;
switch(a)
{
case 1:
c = 1; /* OK */
break;
case 2:
c = 2; /* OK */
break;
default:
c = 3; /* OK */
break;
}
}
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15
A switch statement shall only contain switch labels and switch clauses, and no other code
[MISRA2004-15_0_b-3]
DESCRIPTION
"A switch statement shall only contain switch labels and switch clauses,
and no other code."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo(int a,int b)
{
int c;
switch(a)
{
c = 0; /* Violation */
case 1:
break;
case 2:
break;
default:
break;
}
}
REPAIR
void foo1(int a,int b)
{
int c;
c = 0;
/* OK */
switch(a)
{
case 1:
break;
case 2:
break;
default:
break;
}
}
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15
A switch statement shall only contain switch labels and switch clauses, and no other code
[MISRA2004-15_0_c-3]
DESCRIPTION
"A switch statement shall only contain switch labels and switch clauses,
and no other code."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
#define SWITCH(a)
\
switch (a)
\
{
\
case 1:
\
break;
\
a << 2; /* Violation */\
case 2:
\
break;
\
default:
\
break;
\
}
REPAIR
#define SWITCH(a)
\
switch (a)
\
{
\
case 1:
\
a << 2; /* OK */\
break;
\
case 2:
\
break;
\
default:
\
break;
\
}
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15
A switch label shall only be used when the most closely-enclosing compound statement is the
body of a switch statement [MISRA2004-15_1-3]
DESCRIPTION
"The scope of a case or default label shall be the compound statement,
which is the body of a switch statement.
All case clauses and the default clause shall be at the same scope."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int a, int b ) {
switch(a) {
case 1:
{
case 6:
/* Violation */
;
default:
/* Violation */
break;
}
break;
case 2:
if (b == 1) {
case 3:
/* Violation */
break;
}
break;
}
}
REPAIR
Do not use nested 'case'/'default' statements.
REFERENCES
An unconditional break statement shall terminate every non-empty switch clause [MISRA200415_2-3]
DESCRIPTION
"The last statement in every switch clause shall be a break statement,
or if the switch clause is a compound statement, then the last statement
in the compound statement shall be a break statement."
NOTES
This rule allows also to use return instead break statement.
BENEFITS
Prevents unpredictable program behaviour.
EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
case 2 :
{
i = 3;
}
default:
i = 8;
}
// Violation
// Violation
// Violation
// Violation
REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
break;
}
}
// OK
// OK
// OK
// OK - empty case
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Misra Guidelines - Rule 61
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
The final clause of a switch statement shall be the default clause [MISRA2004-15_3-3]
DESCRIPTION
All switch statements should contain a final default clause.
"The requirement for a final default clause is defensive programming.
This clause should either take appropriate action or contain a suitable
comment as to why no action is taken."
See also: CODSTA-35
BENEFITS
Rule improves readability and maintainability of 'switch' statement.
EXAMPLE
void foo(int i)
switch(i) /*
{
case 0 :
case 1 :
}
switch(i) /*
{
case 0 :
default:
case 1 :
}
}
{
Violation */
break;
break;
Violation */
break;
break;
break;
REPAIR
void foo(int i)
switch(i) /*
{
case 0 :
case 1 :
default:
}
}
{
OK */
break;
break;
break;
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 62
A switch expression shall not represent a value that is effectively Boolean [MISRA2004-15_43]
DESCRIPTION
Values which are effectively Boolean should not be represented in
'switch' condition.
The rule forbids following operators:
a) equality operators (== and !=)
b) logical operators (!, && and ||)
c) relational operators (<, >, <= and >=)
which produce boolean-by-construct values.
BENEFITS
Rule prevents using values that are effectively Boolean in switch.
EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}
// Violation
REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 63
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 195
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-7
Every switch statement shall have at least one case clause [MISRA2004-15_5-3]
DESCRIPTION
Every switch statement shall have at least one case.
See also: OPT-21, OPT-22, CODSTA-54
BENEFITS
Provides maintainability of 'switch' statement.
EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}
/* Violation */
REPAIR
void foo(int i)
{
switch(i)
{
case 1:
{
}
default:
;
}
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 64
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-8
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include <stdarg.h>
int average( int first, ... );
/* Violation */
/* OK - Violation on definition */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
Do not use functions with variable number of arguments.
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 16
If a function returns error information, then that error information shall be tested [MISRA200416_10-3]
DESCRIPTION
"A function (whether it is part of the standard library, a third party
library
or a user defined function) may provide some means of indicating the
occurrence
of an error. This may be via an error flag, some special return value or
some
other means. Whenever such a mechanism is provided by a function the
calling
program shall check for the indication of an error as soon as the function
returns.
However, note that the checking of input values to functions is considered
a more robust means of error prevention than trying to detect errors after
the function has completed (see Rule MISRA2004-20_3). Note also that the
use
of errno (to return error information from functions) is clumsy and should
be
used with care (see Rule MISRA2004-20_5)."
NOTES
Rules checks usage of function calls which returns char, short, int, enum,
or typedef to char, short, int, or enum value and reports violation when
this value is not assigned, checked or cast to void.
BENEFITS
Rule helps writing safety code.
EXAMPLE
int SomeFunctionReturningError( );
void foo( )
{
SomeFunctionReturningError( ); // Violation
}
REPAIR
int SomeFunctionReturningError( );
int foo( )
{
int x;
x = SomeFunctionReturningError( );
(void)SomeFunctionReturningError( );
if (SomeFunctionReturningError( ));
switch (SomeFunctionReturningError( )) {
}
return SomeFunctionReturningError( );
}
//
//
//
//
OK
OK
OK
OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 86
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 115
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-3-2
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 7
6. http://cwe.mitre.org/data/definitions/391.html
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 */
/* Violation */
REPAIR
void foo1( ) {
/* empty */
}
/* OK */
void foo2( );
/* OK */
void foo3( ) {
foo2( );
}
/* 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 70
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 119
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-4
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 1
6. HIS Source Code Metriken, version 1.3.1
Metrik "ap_cg_cycle"
7. ISO/DIS 26262
point 8.4.4
Identifiers shall be given for all of the parameters in a function prototype declaration
[MISRA2004-16_3-3]
DESCRIPTION
Names shall be given for all the parameters in the function declaration
for reasons of compatibility, clarity and maintainability.
BENEFITS
Rule improves readability and clarity of code.
EXAMPLE
void foo1( void );
void foo2( int a, int );
void foo3( int a, int ){}
/* OK */
/* Violation */
/* OK */
REPAIR
void foo1( void );
void foo2( int a, int b );
void foo3( int a, int ){}
/* OK */
/* OK */
/* OK */
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 16
The identifiers used in the declaration and definition of a function shall be identical
[MISRA2004-16_4-3]
DESCRIPTION
If identifiers are given for any of the parameters, then the identifiers
used
in the declaration and definition shall be identical.
BENEFITS
Rule improves readability and clarity of code.
EXAMPLE
void foo(int a, int b);
void foo(int x, int y ) {}
/* Violation */
REPAIR
void foo(int a, int b);
void foo(int a, int b) {}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 74
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-2
Functions with no parameters shall be declared with parameter type void [MISRA2004-16_5-3]
DESCRIPTION
"If the function has no parameters, the parameter list shall be declared
as void"
BENEFITS
Rule improves readability and clarity of code.
EXAMPLE
void foo();
/* Violation */
REPAIR
void foo(void);
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 76
The number of arguments passed to a function shall match the number of parameters
[MISRA2004-16_6-3]
DESCRIPTION
The number of parameters passed to a function shall match
prototype. According to the ISO/IEC 9989:1999 C standard,
prototype
is a declaration of a function that declares the types of
This rule requires that the number of arguments passed to
the function
a function
its parameters.
a function match
the number declared in the prototype. Rule is retained since compilers may
not
flag this constraint error.
BENEFITS
Rule improves readability and maintainability and prevents erroneous code.
EXAMPLE
void myFunction(int p)
{
foo(1);
/* Violation - no foo() prototype */
foo(2,p); /* Violation - inconsistent number of parameters:
first foo() call is treated here as foo() declaration
*/
}
void foo0( void );
void foo3( int, int, int );
void goo( ) {
foo0( 7 );
foo3( 6, 6, 6, 6);
}
REPAIR
void myFunction(int p)
{
/* Violation */
/* Violation */
/* OK prototype */
/* OK */
}
void foo0( void );
void foo2( int, int, ... );
void foo3( int, int, int );
void goo( )
foo0( );
foo2( 6,
foo2( 6,
foo3( 6,
}
{
6 );
6, 6, 6 );
6, 6 );
/*
/*
/*
/*
OK
OK
OK
OK
*/
*/
*/
*/
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Misra Guidelines - Rule 78
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
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
Declare a type of parameter as typedef to pointer to const if the pointer is not used to modify
the addressed object [MISRA2004-16_7_b-3]
DESCRIPTION
The rule reports a violation if a parameter in a function prototype is
declared
as typedef to pointer to non-const object and the pointer is not used to
modify
the addressed object. Then the type of parameter could be changed to
typedef
to pointer to const object.
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104
NOTES
It is not sufficient to add 'const' identifier before typedef's
name in a function declaration, because it is applied to pointer
not to pointed object.
There can already be overloaded function with parameter declared as
typedef
to pointer to const. Then changing the type of parameter to typedef to
pointer
to const will make the code non-compilable.
BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.
EXAMPLE
typedef int* PINT;
typedef const int* CINT;
int function1(PINT ptr)
{
return (*ptr) + 1;
}
// Violation
// Violation
{
return (*ptr) + 1;
}
REPAIR
typedef int* PINT;
typedef const int* CINT;
int function1(CINT ptr)
{
return (*ptr) + 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 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
All exit paths from a function with non-void return type shall have an explicit return statement
with an expression [MISRA2004-16_8-3]
DESCRIPTION
"All exit paths from a function with non-void return type
shall have an explicit return statement with an expression.
This expression gives the value that the function returns.
The absence of a return with an expression leads to undefined
behaviour (and the compiler may not give an error)."
NOTES
"goto" statement is considered as exit point.
The rule does not track the flow. It assumes that each path could
be reachable independently from conditions in conditional statements.
BENEFITS
Rules prevents unpredictable function behaviour.
DRAWBACKS
Rule skips "while", "for", and "catch" sections.
EXAMPLE
int foo1(int x){ // Violation
// in second 'if' statement, 'return' statement is missing
if (x==0) {
if (x==0) {
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // Violation
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;
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-3
Do not apply arithmetic to pointers that don't address an array or array element [MISRA200417_1-3]
DESCRIPTION
"Pointer arithmetic shall only be applied to pointers that address an
array or
array element.
Addition and subtraction of integers (including increment and decrement)
from
pointers that do not point to an array or array element results in
undefined
behaviour."
The rule reports a violation when both following conditions are met:
- variable of pointer type is used as operand in arithmetic
expression (addition, subtraction, incrementation, decrementing)
- the variable was not assigned at all in current function or
last assignment before the arithmetic expression was not from an "array
expression"
An "array expression" is an expression or variable which
- has array type (e.g. int[]), or
- expression which takes address of array or array element, or
- was previusly assigned an "array expression"
See also: PB-51
NOTES
Limitation of rule:
- complex expressions might be incorrectly recognized as "array
expression" if
it contains expression with array type. In result a valid violation might
not be reported.
- control flow ('if' etc) is not taken into consideration, only line
number,
when checking for last assignment
- violations on members (a->b, a.b) are not reported.
- recursive check of "array expression" is limited to 10 levels
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
/* example of incorrect code */
void func(int* ptr1, int a[5]){
int i;
int* ptr2 = 0;
int* ptr3 = &i;
ptr1++;
/* Violation - ptr1 may points to whatever*/
ptr1 = ptr2 + 1; /* Violation - ptr2 is a null pointer */
ptr3++;
/* Violation - ptr3 points to variable of non-array
type*/
}
REPAIR
/* example of correct code */
void func(int* ptr3, int a[5]){
int* ptr1 = &a;
int* ptr2 = &a[3];
ptr1++;
/* OK - ptr1 points to an array */
ptr3 = ptr2 + 1; /* OK - ptr2 points to an array element */
ptr3++;
/* OK - ptr3 points to an array element */
}
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 17
Pointer arithmetic shall only be applied to pointers that address an array or array element
[MISRA2004-17_2-3]
DESCRIPTION
"Subtraction of pointers only gives well-defined results if the two
pointers
point (or at least behave as if they point) into the same array object."
Drawbacks: For more complex code rule may not be able to check if there is
applied pointer arithmetic to pointers that address an array or array
element.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
=
=
=
=
=
a; i
p1;i
p2;i
p3;i
p4;i
=
=
=
=
=
p1
p2
p3
p4
p5
a;
a;
a;
a;
a;
//
//
//
//
//
OK
OK
OK
Violation - false positive
Violation - false positive
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 - p2;
i = p2 - a;
i = p3 - a;
}
// Violation
// Violation
// OK
REPAIR
Do not apply pointer subtraction to pointers that address elements
of different arrays.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-17
>, >=, <, <= shall not be applied to pointer types except where they point to the same array
[MISRA2004-17_3-3]
DESCRIPTION
"Attempting to make comparisons between pointers will produce undefined
behaviour."
NOTES
"It is permissible to address the next element beyond the end of an array,
but accessing this element is not allowed."
EXCEPTIONS
"Both operands are of the same type and point to the same array"
BENEFITS
Rule makes the code more readable and less confusing.
DRAWBACKS
For more complex code rule may not be able to check if there is
applied pointer comparison to pointers which point the same array.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
}
=
=
=
=
=
a; i
p1;i
p2;i
p3;i
p4;i
=
=
=
=
=
p1
p2
p3
p4
p5
<
<
<
<
<
a;
a;
a;
a;
a;
//
//
//
//
//
OK
OK
OK
Violation - false positive
Violation - false positive
EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 < p2;
i = p2 < a;
i = p3 < a;
// Violation
// Violation
// OK
REPAIR
Do not apply pointer comparison to pointers that address elements
of different arrays
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 103
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 171
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-18
Array indexing shall be the only allowed form of pointer arithmetic [MISRA2004-17_4-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
BENEFITS
Rule improves safety of the code.
DRAWBACKS
For more complex code rule may not be able to check if there is indexed
pointer
which points to array. For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10];
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
=
=
=
=
=
a;
p1;
p2;
p3;
p4;
p1[0]
p2[0]
p3[0]
p4[0]
p5[0]
=
=
=
=
=
0;
0;
0;
0;
0;
//
//
//
//
//
OK
OK
OK
Violation - false positive
Violation - false positive
EXAMPLE
void my_fn(int * p1, int p2[]) {
int index = 0;
int * p3;
int * p4;
*p1 = 0;
p1 ++;
/* Violation
p1 = p1 + 5; /* Violation
p1[5] = 0;
/* Violation
p3 = &p1[5]; /* Violation
p2[0] = 0;
index ++;
index = index + 5;
p2[index] = 0; /* OK */
p4 = &p2[5];
/* OK */
pointer increment */
pointer increment */
p1 was not declared as an array */
p1 was not declared as an array */
}
void foo() {
int a1[16];
int a2[16];
int a[10];
int * p;
my_fn(a1, a2);
my_fn(&a1[4], &a2[4]);
p = a;
*(p+5) = 0; /* Violation */
p[5] = 0;
/* OK */
}
REPAIR
Do not increment/decrement pointers that does not point to an array
Do not apply array indexing to pointers that does not point to array
elements.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-15
The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_a-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int * INTPTR;
struct s {
int *** s3;
};
struct s *** ps3;
int ** (***pfunc3)();
int *** ( **pfunc4)();
void function( int * par1,
int *** par3,
INTPTR * const * const par5
)
{
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4
The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_b-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int* apInt[] ;
apInt* rule12;
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4
The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_c-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
int*** (*rule13)();
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4
The declaration of objects should contain no more than 2 levels of pointer indirection
[MISRA2004-17_5_d-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int* INTPTR;
void function(int ** par7[])
{
}
int*** (*xx5[])() = {0};
typedef int INTARR[];
INTARR* (**xx9[])() = {0};
int** rule21[] = {0};
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4
The address of an object with automatic storage shall not be assigned to another object that
may persist after the first object has ceased to exist [MISRA2004-17_6-3]
DESCRIPTION
"If the address of an automatic object is assigned to another automatic
object
of larger scope, or to a static object, or returned from a function then
the
object containing the address may exist beyond the time when the original
object
ceases to exist (and its address becomes invalid). For example:
int * foo( void ) {
int local_auto;
return (&local_auto);
}"
BENEFITS
Prevents loss of data
EXAMPLE
int* global;
int* foo() {
int iLocal;
static int* siLocal;
siLocal = &iLocal;
global = &iLocal;
return &iLocal;
}
void goo() {
int* piLocal;
{
int iiLocal;
piLocal = &iiLocal;
}
}
// Violation
// Violation
// Violation
// Violation
REPAIR
Do not assign local address of object to more global,
or static object or return from function.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 106
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 173
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-2
All structure and union types shall be complete at the end of a translation unit [MISRA200418_1-3]
DESCRIPTION
"A complete declaration of the structure or union shall be included within
any translation unit that reads from or writes to that structure.
A pointer to an incomplete type is itself complete and is permitted,
and therefore the use of opaque pointers is permitted"
References are treated the same way as pointers so the use of opaque
references is permitted as well.
BENEFITS
Rule prevents undefined behaviour and improves readability
and maintainability of code
EXAMPLE
extern struct st *pst1;
extern struct st *pst2;
void mc2_1801 ( void )
{
//
struct st1 s;
*/
struct {
int a;
int b [ ];
/* Violation */
} mc2_1801_st = { 1, { 2, 3, 4 } };
pst2 = pst1;
//
*/
}
*pst2 = *pst1;
REPAIR
struct st{
int stm;
};
struct st1{
int st1m;
};
extern struct st *pst1;
extern struct st *pst2;
void mc2_1801 ( void )
{
struct st1 s;
/* OK */
struct {
int a;
int b [3];
/* OK */
} mc2_1801_st = { 1, { 2, 3, 4 } };
pst2 = pst1;
*pst2 = *pst1;
/* OK */
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 18
BENEFITS
Rule prevents undefined behaviour and data loss.
EXAMPLE
union U {
int
long
double
};
iValue;
lValue;
dValue;
void main( ) {
union U a, b;
union U *p;
a.dValue = a.lValue;
p->dValue = p->iValue;
/* Violation */
/* Violation */
REPAIR
union U {
int
long
double
};
iValue;
lValue;
dValue;
void main( ) {
union U a, b;
union U *p, *q;
a.dValue = b.lValue;
/* OK */
p->dValue = q->iValue;
/* OK */
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 18
BENEFITS
Rule prevents undefined behaviour and data loss.
EXAMPLE
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {
union U a, b;
union U *p;
(void)memcpy( &a.dValue, &a.lValue, 8 );
(void)memcpy( &p->dValue, &p->iValue, 8 );
return 0;
}
REPAIR
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {
/* Violation */
/* Violation */
union U a, b;
union U *p, *q;
(void)memcpy( &a.dValue, &b.lValue, 8 );
(void)memcpy( &p->dValue, &q->iValue, 8 );
return 0;
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-2-1
Note:
Rule reports a violation message on each union's declaration.
BENEFITS
Rule prevents undefined behaviour and erroneous code.
EXAMPLE
union U {
/* Violation */
int _i;
char _buf[ sizeof( int ) ];
};
REPAIR
Do not use union.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 97
3. Origin: Misra Guidelines - Rule 109
BENEFITS
It is important to prevent the situation of executable code coming before
a #include directive, otherwise there is danger that the code may try to
use
items which would be defined in the header.
EXAMPLE
void foo();
int g;
#include "test.h"
// Violation
REPAIR
#include "test.h"
void foo();
int g;
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-1
3. Origin: Misra Guidelines - Rule 87
EXCEPTIONS
If an argument of macro is used in body after '.', '->', '::' or before
'::',
then violation is not reported, because the use of paranthesis in such
cases
makes a code non-compilable. For example:
#define INIT1(member) a->member = 0 // No violation reported
#define CALL(ns,fn) ns::fn() // No violation reported
BENEFITS
Improves the readability of code and ensures operations order.
DRAWBACKS
In some cases a violation is reported, but the use of parenthesis causes a
compilation error. For example:
#define MTYPE(type, a) (type *)(a) // Violation reported
#define MT(classtype, type) classtype<type> // Violation reported
EXAMPLE
#define abs(x) ((x >= 0) ? x : -x)
void foo(int a, int b){
int z = abs(a - b);
// Violation
REPAIR
#define abs(x) (((x) >= 0) ? (x) : -(x))
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-6
All macro identifiers in preprocessor directives shall be defined before use, except in #ifdef
and #ifndef preprocessor directives and the defined() operator [MISRA2004-19_11-3]
DESCRIPTION
If an attempt is made to use an identifier in a preprocessor directive,
and that identifier has not been defined,
the preprocessor will sometimes not give any warning but will assume
the value zero.
#ifdef, #ifndef and defined() are provided to test the existence of a
macro,
and are therefore excluded.
BENEFITS
Complying with this rule leads to safer code
and prevents hard-to-detect errors.
DRAWBACKS
1) Currently the implementation of the rule assumes that the compliance
with
the rule is provided by following MISRA 2004 19-11 advice (p. 78):
"Consideration should be given to the use of a /#ifdef/" test before
an identifier is used."
2) If #1 is not followed, due to technical limitations we are not able
to recognize cases where preprocessor identifier is defined in different
file from that where the identifier is used. Also, we are unable to
detect
that given identifier was defined as compiler command line option.
3) If tested macro identifier was earlier defined by #define preprocessor
directive, it can not be defined in more nested #if / #elif / #else /
#endif
directives. In such cases rule can report false positives.
3) If tested macro identifier is defined within complex conditional
statement (containing
few branches #elif/#else) we cannot be sure if branch containing
definition of macro
being tested is executed. In such case rule may report false positives.
EXAMPLE
#if X
/* Violation - X undefined at this point */
#endif
#if Y
/* Violation - Y undefined at this point */
#endif
#if X + Y
/* Violation - X and Y undefined at this point */
#endif
#ifdef X
#define Y 1
#else
#define Y 3
#endif
#if Y > 2
#endif
REPAIR
#define X 1
#if X
/* OK */
#endif
#ifdef Y
#if Y
/* OK - check is done in the #ifdef above */
#endif
#endif
#ifdef X
#define Y 1
#else
#define Y 3
#endif
#ifdef Y
#if Y > 2
#endif
#endif
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 97
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-7
There shall be at most one occurrence of the # or ## preprocessor operators in a single macro
definition [MISRA2004-19_12-3]
DESCRIPTION
"There is an issue of unspecified order of evaluation associated
with the # and ## preprocessor operators.
To avoid this problem only one occurrence of either operator
shall be used in any single macro definition
(i.e. one #, or one ## or neither)."
BENEFITS
Rule improves readability and clarity of code.
EXAMPLE
#define TEST1(A,B,C) A # B # C
#define TEST2(A,B,C) A ## B # C
#define TEST3(A,B,C) A ## B ## C
/* Violation */
/* Violation */
/* Violation */
REPAIR
#define TESTa(A,B) A # B
#define TESTb(A,B) A ## B
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 98
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-1
BENEFITS
Rule prevents inconsistent implementation of # and ## operators.
EXAMPLE
#define stringer( x ) printf( #x "\n" ) /* Violation */
REPAIR
Do not use # and ## preprocessor operators.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-2
The defined preprocessor operator shall only be used in one of the two standard forms
[MISRA2004-19_14-3]
DESCRIPTION
"The only two permissible forms for the defined preprocessor operator are:
- defined ( identifier )
- defined identifier
Any other form leads to undefined behaviour.
Generation of the token defined during expansion of a #if or #elif
preprocessing directive also leads to undefined behaviour and shall be
avoided,"
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#if defined X > Y
#endif
#define DEFINED defined
#if DEFINED(X)
#endif
// Violation
// Violation
REPAIR
#if defined X
#endif
#if defined (X)
#endif
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-1-1
Precautions shall be taken in order to prevent the contents of a header file being included
twice [MISRA2004-19_15-3]
DESCRIPTION
"When a translation unit contains a complex hierarchy of nested header
files
it can happen that a particular header file is included more than once.
This can be, at best, a source of confusion. If it leads to multiple or
conflicting definitions, the result can be undefined or erroneous
behaviour."
Rule checks if any of described below mechanisms preventing the file
contents
from being included more than once is present.
#ifndef AHDR_H
#define AHDR_H
/* The following lines will be excluded by the
preprocessor if the file is included more
than once */
...
#endif
Alternatively, the following may be used:
#ifdef AHDR_H
#error Header file is already included
#else
#define AHDR_H
/* The following lines will be excluded by the
preprocessor if the file is included more
than once */
...
#endif
See also: PFO-02, PFO-07, and PFO-08.
BENEFITS
Rule prevents undefined and erroneous behaviour.
EXAMPLE
/* foo.h */
/* Violation - file contains no multi inclusion mechanism */
/* foo.hh */
/* Violation - file contains no multi inclusion mechanism */
/* foo.c */
#include "foo.h"
#include "foo.hh"
REPAIR
/* foo.h */
/* OK */
#ifndef FOO_H
#define FOO_H
/* code here */
#endif
/* foo.hh */
/* OK */
#ifdef FOO_HH
#error Header file is already included
#else
#define FOO_HH
#endif
/* foo.c */
#include "foo.h"
#include "foo.hh"
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 19
BENEFITS
Rule prevents erroneous behaviour.
EXAMPLE
#define MAX 2
int foo(void)
{
int x = 0;
#ifndef MAX
x = 1;
#else1
x = MAX;
#endif
return x;
}
REPAIR
#define MAX 2
int foo(void)
{
int x = 0;
/* Violation */
#ifndef MAX
x = 1;
#else
x = MAX;
#endif
return x;
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-8
All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if or
#ifdef directive to which they are related [MISRA2004-19_17-3]
DESCRIPTION
"When the inclusion and exclusion of blocks of statements is controlled
by a series of preprocessor directives, confusion can arise
if all of the relevant directives do not occur within one file."
This rule requires that the number of preprocessor directives
#if/ifdef/ifndef
matches the number of #endif directives in the file.
BENEFITS
Rule improves good code structure and
prevents maintenance problems.
EXAMPLE
/* Violation */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"
REPAIR
/* OK */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"
#endif
REFERENCES
Non-standard characters should not occur in header file names in #include directives
[MISRA2004-19_2-3]
DESCRIPTION
"If the ', \, ", or /* characters are used between < and >
delimiters or the ', \, or /* characters are used
between the " delimiters in a header name preprocessing token,
then the behaviour is undefined."
BENEFITS
Ensures only standard characters in header file names.
EXAMPLE
#include <sys\types.h>
#include "incl\header.h"
/* Violation */
/* Violation */
REPAIR
#include <sys/types.h>
#include "incl/header.h"
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 88
NOTES
Storage class specifiers and type qualifiers include keywords such as:
typedef, extern, static, auto, register, const, volatile, restrict.
BENEFITS
Prevents from redefining the syntax of the language.
EXAMPLE
#define PI 3.14159F
#define DOUBLE_PI 2*PI
#define int64_t
long
/* OK */
/* Violation */
/* Violation */
REPAIR
#define PI 3.14159F
#define DOUBLE_PI (2*PI)
typedef long int64_t;
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
BENEFITS
Improves the readability of code.
EXAMPLE
void foo( int* x ) {
#define CHECKPARAM(p) (p != 0)
if (CHECKPARAM(x)) {
/* ... */
}
#undef CHECKPARAM
}
// Violation
// Violation
REPAIR
#define CHECKPARAM(p) (p != 0) // OK - macro is defined outside of any
blocks
void foo( int* x ) {
if (CHECKPARAM(x)) {
/* ... */
}
}
#undef CHECKPARAM
// OK - macro is undefined outside of any
blocks
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 91
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-2
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
#undef TEST
/* Violation */
REPAIR
Do not use #undef.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 92
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-3
BENEFITS
"While macros can provide a speed advantage over functions, functions
provide
a safer and more robust mechanism. This is particularly true with respect
to the type checking of parameters, and the problem of function-like
macros
potentially evaluating parameters multiple times.
See also: CODSTA-03, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40
EXAMPLE
#define SUM(A,B) ((A)+(B))
/* Violation */
REPAIR
int sum( int a, int b ) {
return (a + b);
}
void foo( int x, int y ) {
/* ... */
sum( x, y );
/* ... */
}
REFERENCES
/* OK */
A function-like macro shall not be invoked without all of its arguments [MISRA2004-19_8-3]
DESCRIPTION
"This is a constraint error, but preprocessors have been known to ignore
this
problem. Each argument in a function-like macro must consist of at least
one
preprocessing token otherwise the behaviour is undefined."
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#define MAX(a, b, c)
((a < b) ? b : a)
REPAIR
#define MAX(a, b, c)
((a < b) ? b : a)
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
Arguments to a function-like macro shall not contain tokens that look like preprocessing
directives [MISRA2004-19_9-3]
DESCRIPTION
"If any of the arguments act like preprocessor directives,
the behaviour when macro substitution is made can be unpredictable."
NOTES
Rule works only within file scope.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( #foo );
MACRO2( i, #foo );
MACRO2( i, "#foo" );
}
/* Violation */
/* Violation */
/* Violation */
REPAIR
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( i );
MACRO2( i, i );
}
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 95
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-5
The library functions atof, atoi and atol from library stdlib.h shall not be used [MISRA200420_10-3]
DESCRIPTION
'atof', 'atoi' and 'atol' functions from library <stdlib.h> have undefined
behaviour associated with them when the string cannot be converted.
BENEFITS
Prevents using functions which have sometimes undefined behaviour.
EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *s; double x; int i; long l;
s = " -2309.12E-15";
x = atof( s );
/* Violation */
s = " -9885 pigs";
i = atoi( s );
/* Violation */
s = "98854 dollars";
l = atol( s );
/* Violation */
}
REPAIR
Do not use atof, atoi and atol functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 125
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 23
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-2
The library functions abort, exit, getenv and system from library stdlib.h shall not be used
[MISRA2004-20_11-3]
DESCRIPTION
'abort', 'exit', 'getenv' and 'system' functions from stdlib.h, cstdlib,
or stdlib_iso.h libraries shall not be used.
BENEFITS
Prevents using functions which are not required in an embedded system.
EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *libvar;
libvar = getenv( "LIB" );
system( "dir" );
abort( );
exit( 0 );
}
/*
/*
/*
/*
Violation
Violation
Violation
Violation
*/
*/
*/
*/
REPAIR
Do not use abort, exit, getenv and system functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 126
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 24
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-3
The time handling functions of library time.h shall not be used [MISRA2004-20_12-3]
DESCRIPTION
"This library is associated with clock times.
Various aspects are implementation dependent
or unspecified, such as the formats of times."
Rule prevents inclusion of <time.h> and <ctime> headers.
See also: SECURITY-01
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include <time.h>
/* Violation */
REPAIR
Do not include time.h header.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 127
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 25
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 18, Section 7, Rule 18-0-4
Reserved identifiers, macros and functions in the standard library, shall not be defined,
redefined or undefined [MISRA2004-20_1_a-3]
DESCRIPTION
"It is generally bad practice to #undef a macro which is defined in the
standard library. It is also bad practice to #define a macro name which
is a C reserved identifier or C keyword which is the name of any macro,
object or function in the standard library.
For example, there are some specific reserved words and function names
which are known to give rise to undefined behaviour if they are redefined
or
undefined, including defined, _ _LINE_ _, _ _FILE_ _, _ _DATE_ _, _ _TIME_
_,
_ _STDC_ _, errno and assert. Generally, all identifiers that begin with
the underscore character are reserved."
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#define __A 1
// Violation
#define assert 1
// Violation
#undef __AA
// Violation
#undef assert
// Violation
REPAIR
Do not #define or #undef reserved identifiers
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1
BENEFITS
Redefinition of reserved words can lead to errors and confusion.
EXAMPLE
#define break 1
#define continue 1
#undef while
#undef return
//
//
//
//
Violation
Violation
Violation
Violation
REPAIR
Do not #define or #undef reserved words
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1
The names of standard library macros, objects and functions shall not be reused [MISRA200420_2-3]
DESCRIPTION
"Where new versions of standard library macros, objects or functions are
used
by the programmer (e.g. enhanced functionality or checks of input values)
the
modified macro, object or function shall have a new name. This is to avoid
any
confusion as to whether a standard macro, object or function is being used
or
whether a modified version of that function is being used. So, for
example, if
a new version of the sqrt function is written to check that the input is
not
negative, the new function shall not be named sqrt, but shall be given a
new
name."
Rule checks if the following reserved names are used:
- macro, function, and typedef names from C standard library headers:
assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- identifiers that begin with the underscore character
See also: NAMING-33, CODSTA-92, CODSTA-93
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
int memset();
REPAIR
// Violation
int my_memset(); // OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
BENEFITS
Prevents writing error prone code.
EXAMPLE
void* memcpy( void *, void*, int n );
void test( void *v ) {}
int getSomeIntValue( ) {
return 0;
}
void foo( void *p, void *q ) {
int n;
memcpy( p, q, n );
/* Violation test( q );
/* consider it
memcpy( p, q, n );
/* Violation switch( n ) {
/* consider it
case 0:
break;
}
if (p == 0) {}
/* consider it
complain about p,
a validation of q
complain about p,
a validation of n
q and n */
*/
and n */
*/
a validation of p */
memcpy( p, q, getSomeIntValue( ) );
getSomeIntValue call */
}
REPAIR
void* memcpy( void *, void*, int n );
void test( void *v ) {}
int getSomeIntValue( ) {
return 0;
}
void foo( void *p, void *q ) {
int n;
test( p );
/* consider it
test( q );
/* consider it
if (n != 0) {
memcpy( p, q, n );
/* OK */
memcpy( p, q, n );
/* OK */
}
switch( n ) {
/* consider it
case 0:
break;
}
if (p == 0) {}
/* consider it
n = getSomeIntValue( );
if (n != 0) {
memcpy( p, q, n );
/* OK */
}
}
a validation of p */
a validation of q */
a validation of n */
a validation of p */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 117
EXCEPTIONS
The rule allows to use a placement new.
BENEFITS
"There is a range of unspecified,
behaviour associated with dynamic
of
other potential pitfalls. Dynamic
memory
leaks, data inconsistency, memory
behaviour."
EXAMPLE
void foo()
{
int * p = new int[10]; // Violation
/* ... */
delete[] p;
// Violation
REPAIR
Do not use neither 'new' and 'delete' operators nor 'calloc', 'malloc',
'realloc' and 'free' functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Misra Guidelines - Rule 118
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-4-1
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 206
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 3
BENEFITS
The rule prevents undefined behaviours.
EXAMPLE
#include <errno.h>
int err_check( ) {
errno = 1;
return (errno);
}
/* Violation */
/* Violation */
REPAIR
Do not use errno.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 119
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 17
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 19, Rule 19-3-1
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
// Violation - The macro offsetof shall not be used. Macro is in line:
[10]
#include <stddef.h>
struct S {
int x, y, z;
char buffer[ 128 ];
};
int main( ) {
int i = offsetof( struct S, buffer );
return 0;
}
REPAIR
Do not use offsetof.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
The setjmp macro and the longjmp function shall not be used [MISRA2004-20_7-3]
DESCRIPTION
"setjmp and longjmp allow the normal function call mechanisms to be
bypassed,
and shall not be used."
Rule reports a violation message if setjmp or longjmp is used and the file
includes any of the following headers: setjmp.h, setjmp, or csetjmp.
BENEFITS
Rule prevents normal function call mechanisms from being bypassed.
EXAMPLE
#include <setjmp.h>
jmp_buf mark;
int
fperr;
void foo( void ) {
int jmpret;
jmpret = setjmp( mark );
}
/* Violation */
REPAIR
Do not use the setjmp macro and the longjmp function.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 122
BENEFITS
Prevents from problems associated with implementation-defined
and undefined behaviour in signal handling.
EXAMPLE
#include <signal.h>
/* Violation */
REPAIR
Do not use <signal.h> header.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 123
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 21
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-7-1
BENEFITS
Prevents form problems associated with a large number of unspecified,
undefined and implementation-defined behaviour associated
with streams and file I/O.
EXAMPLE
#include <stdio.h>
/* Violation */
REPAIR
Do not use <stdio.h> library.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 124
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 22
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 27, Rule 27-0-1
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
/* compilable by cl.exe g++*/
void asmCall( ) {
/* Violation */
int g = 0;
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (
"mov %eax, 0x01\n\t"
"int $0x10"
);
#endif
}
REPAIR
void asmCall( ) {
/* OK */
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Misra Guidelines - Rule 3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-4-3
BENEFITS
The use of // in preprocessor directives (e.g. #define) can vary.
Also the mixing of /* ... */ and // is not consistent.
This is more than a style issue,
since different (pre C99) compilers may behave differently.
EXAMPLE
#define MAX 100 // Violation: bad comment
// Violation: bad comment
void foo()
{
int x;
// Violation: bad comment
}
REPAIR
#define MAX 100 /* OK */
/* OK */
void foo()
{
int x;
/* OK */
}
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 2
BENEFITS
Nested comments are not supported by C and can lead to confusion.
EXAMPLE
/* some comment, end comment marker accidentally omitted
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is not compliant - Violation */
REPAIR
/* some comment, end comment marker accidentally omitted */
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is compliant - OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 9
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-1
NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.
BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."
EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}
// Violation
REPAIR
void foo()
{
int x = 5;
/* Comment without
// OK
code within */
#if 0
if (x==0){
x++;
}
#endif
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3
All uses of the #pragma directive shall be documented and explained [MISRA2004-3_4-3]
DESCRIPTION
All uses of #pragma directive shall be documented and explained.
BENEFITS
Provides readability and maintainability.
EXAMPLE
#pragma TEST
/* Violation */
/* Violation */
*/
#pragma TEST
/* Violation */
REPAIR
// OK
#pragma TEST
/* OK */
#pragma TEST
/* OK - multiline comment
*/
#pragma TEST
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 3
2. Origin: Misra Guidelines - Rule 99
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-6-1
Do not mix bit-fields and other data within the same structure [MISRA2004-3_5-3]
DESCRIPTION
It is recommended that structures should be declared specifically
to hold the sets of bit fields, and do not include any other data
within the same structure.
BENEFITS
Rule prevents from the potential pitfalls and areas of implementationdefined
(i.e.non-portable) behaviour such as:
- the alignment of the bit fields in the storage unit is implementationdefined,
that is whether they are allocated from the high end or low end of the
storage
unit (usually a byte).
- whether or not a bit field can overlap a storage unit boundary is also
implementation-defined
(e.g. if a 6-bit field and a 4-bit field are declared in that order,
whether the 4-bit field
will start a new byte or whether it will be 2 bits in one byte and 2 bits
in the next).
EXAMPLE
struct message { /* Violation */
signed int little: 4;
unsigned int x_set: 1;
int size;
};
REPAIR
struct message { /* OK */
signed int little: 4;
unsigned int x_set: 1;
};
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 3
Only those escape sequences that are defined in the ISO C standard shall be used
[MISRA2004-4_1-3]
DESCRIPTION
Only those escape sequences that are defined in the ISO C standard
shall be used.
Section 5.2.2 of the ISO C standards defines 7 escape sequences which
may be used in source code:
1. \a (alert)
2. \b (backspace)
3. \f (form feed)
4. \n (new line)
5. \r (carriage return)
6. \t (horizontal tab)
7. \v (vertical tab)
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
#include <stdio.h>
void foo( ) {
printf("ABCD\u1111");
printf("abcd\hgf");
printf("\k");
}
// Violation
// Violation
// Violation
REPAIR
Do not use escape sequences not defined in the ISO C standard.
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 4
BENEFITS
Trigraphs can cause accidental confusion with other uses of two question
marks and lead to unexpected behaviour.
EXAMPLE
??=define TEST 1
/* Violation
*/
void foo() {
const char* s = "(Date should be in the form ??-??-??)"; /* Violation */
}
REPAIR
#define TEST 1
OK */
void foo() {
/*
const char* s = "(Date should be in the form " "??" "-??" "-??" ")"; /*
OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 4
2. Origin: Misra Guidelines - Rule 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 11
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-3-1
Identifiers (internal and external) shall not rely on the significance of more than 31 characters
[MISRA2004-5_1-3]
DESCRIPTION
Identifiers shall not have more than 31 characters.
BENEFITS
Rule ensures porting of code between compilers/linkers without requiring
modification (shortening) of identifier names.
EXAMPLE
void this_is_not_ok_11111111111111111( );
/* Violation */
struct ThisClassHasANameThatIsTooBig11111
{
int a;
};
/* Violation */
REPAIR
void this_is_ok_11111111111( );
/* OK */
struct ThisClassHasANameThatIsOK
{
int a;
};
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 11
Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [MISRA2004-5_2_a-3]
DESCRIPTION
Do not hide names of global variables and parameters.
BENEFITS
Hiding names of global variables or parameters
can lead to errors and confusion.
EXAMPLE
int x;
void foo( ) {
int x;
/* Violation */
x = 3;
}
REPAIR
Avoid hiding names of global variables and parameters.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4
Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,
and therefore hide that identifier [MISRA2004-5_2_b-3]
DESCRIPTION
Do not hide names of local variables.
BENEFITS
Hiding names of local variables can lead to errors and confusion.
EXAMPLE
int foo( ) {
int a;
{
int a;
}
}
/* Violation */
REPAIR
Avoid hiding names of local variables.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4
BENEFITS
Reuse of typedef names can lead to errors and confusion.
EXAMPLE
typedef int MyInt;
void foo()
{
double MyInt; /* Violation */
}
REPAIR
typedef int MyInt;
void foo()
{
double MyVar; /* OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 17
BENEFITS
Reuse of typedef names can lead to errors and confusion.
EXAMPLE
typedef unsigned char uint8_t;
void foo()
{
typedef signed char uint8_t; /* Violation */
}
REPAIR
typedef unsigned char uint8_t;
void foo()
{
typedef signed char int8_t; /* OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 17
A tag name shall not be reused for other purpose within the program [MISRA2004-5_4_a-3]
DESCRIPTION
"No tag name shall be reused for any other purpose within the program.
ISO 9899:1990 does not define the behaviour when an aggregate declaration
uses a tag in different forms of type specifier."
BENEFITS
Reuse of tag names can lead to errors and confusion.
EXAMPLE
struct stag { int a; };
void stag(void){}
// Violation
REPAIR
struct stag { int a; };
void foo(void){}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4
BENEFITS
Reuse of tag names can lead to errors and confusion.
EXAMPLE
struct stag { int a; int b; };
void foo1()
{
union stag
}
void foo2(void)
{
struct stag { int a; };
}
// Violation
REPAIR
struct stag { int a; int b; };
void foo1()
{
union union_tag
}
void foo2(void)
{
{ int a; float b; }; // OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4
No object or function identifier with static storage duration should be reused [MISRA20045_5_a-4]
DESCRIPTION
Static object or function identifier shall not be reused for any other
purpose within the program.
BENEFITS
Reuse of static identifiers can lead to errors and confusion.
EXAMPLE
static float a;
static void foo()
{
int a;
/* Violation */
int foo; /* Violation */
}
REPAIR
Do not use static identifiers for any other purpose within the program.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4
No object or function identifier with static storage duration should be reused [MISRA20045_5_b-4]
DESCRIPTION
Object or function identifier with static storage duration should be
unique.
BENEFITS
Reuse of identifier names can lead to errors and confusion.
EXAMPLE
static
static
{
static
static
}
float a;
void foo()
int a ; /* Violation */
int foo; /* Violation */
REPAIR
Do not use the same names for different static object or functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4
No identifier in one name space should have the same spelling as an identifier in another
name space, with the exception of structure and union member names [MISRA2004-5_6-4]
DESCRIPTION
"ISO C defines a number of different name spaces. It is technically
possible to use the same name in separate name spaces to represent
completely different items. However this practice is deprecated because
of the confusion it can cause, and so names should not be reused, even
in separate name spaces."
There are four namespaces in the C Language
1. Label names
2. Tags of structure, unions and enumerations
3. Members of structs and unions; each struct/union as a separate
namespace
4. All other identifiers; e.g. enum constants, variables, functions,
typedefs
NOTES
The output message shows only the first place (line) where the same
name is used in the other name space.
EXCEPTIONS
"An exception to this rule is the naming of members of structures,
where members names may be reused within separate structures."
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
typedef struct MyStruct // tags name space
{
int Member;
// members name space
} MyStruct;
// Violation - identifiers name space
REPAIR
typedef struct MyStruct
{
int Member;
} MyStructObj;
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 12
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-6
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
struct air_speed
{
int speed;
} * x;
struct gnd_speed
{
int speed;
} * y;
/* Violation */
REPAIR
Do not use the same names for different members.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. ISO/DIS 26262
point 8.4.4
The plain char type shall be used only for the storage and use of character values
[MISRA2004-6_1-3]
DESCRIPTION
"The plain char type shall be used only for the storage and use of
character values.
The only permissible operators on plain char types are assignment
and equality operators (=, ==, != )"
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
char a = 65;
/* Violation */
void foo( ) {
a = 66;
/* Violation */
a++;
/* Violation */
if (a < 67) /* Violation */
{
}
}
REPAIR
char a = 'A';
/* OK */
void foo( ) {
a = 'B';
/* OK */
if (a == 'C') /* OK */
{
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-11
signed and unsigned char type shall be used only for the storage and use of numeric values
[MISRA2004-6_2-3]
DESCRIPTION
signed and unsigned char type shall be used only for the storage
and use of numeric values. The signedness of the plain char type is
implementation-defined and should not be relied upon.
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
signed char a = 'A';
void foo( ) {
unsigned char a = 'B';
if (a == 'C')
{
}
if (a < 'D')
{
}
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
signed char a = 65;
void foo( ) {
unsigned char a = 66;
if (a == 67)
{
}
if (a < 68)
{
}
}
/* OK */
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-12
typedefs that indicate size and signedness should be used in place of the basic types
[MISRA2004-6_3-3]
DESCRIPTION
"The basic numerical types of signed and unsigned variants of char, int,
short, long, and float, double should not be used, but specific-length
typedefs should be used."
Rule reports a violation message if basic numerical type is used
( e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA-013
EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- plain char, boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)
BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."
EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
short* v_short,
float& r_float)
{
double h;
const int z = 1;
return 1;
REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
char ch;
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}
/* OK (plain char) */
/* OK (typedef name starts with 'bool'
/* OK (bit-bield type) */
/*
/*
/*
/*
/*
OK
OK
OK
OK
OK
(plain char) */
(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 18 Portable Code - 18.1 Data Abstraction - Port. Rec. 1
Bit fields shall only be defined to be of type unsigned int or signed int [MISRA2004-6_4-3]
DESCRIPTION
"Bit fields shall only be defined to be of type unsigned int or signed
int.
Using int is implementation-defined because bit fields of type int can be
either signed or unsigned. The use of enum, short or char types for bit
fields
is not allowed because the behaviour is undefined."
BENEFITS
Prevents implementation-defined behaviour.
EXAMPLE
enum Enum { E1, E2};
struct Struct
{
unsigned char f1:2;
unsigned short f2:2;
unsigned long f3:2;
enum Enum
f4:2;
int
f5:2;
};
/*
/*
/*
/*
/*
Violation
Violation
Violation
Violation
Violation
REPAIR
struct Struct
{
unsigned int
unsigned int
unsigned int
signed int
signed int
};
REFERENCES
f1:2;
f2:2;
f3:2;
f4:2;
f5:2;
/*
/*
/*
/*
/*
OK
OK
OK
OK
OK
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
BENEFITS
Rule prevents the potential pitfalls and erroneous code.
EXAMPLE
struct MyStruct {
signed int si01:1;
signed int si02:1;
};
/* Violation */
/* Violation */
REPAIR
struct MyStruct {
signed int si01:2;
unsigned int si02:1;
};
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. Origin: Misra Guidelines - Rule 112
Octal constants (other than zero) and octal escape sequences shall not be used [MISRA20047_1-3]
DESCRIPTION
"Any integer constant beginning with a '0' (zero) is treated as octal.
So there is a danger, for example, with writing fixed length constants.
Octal escape sequences can be problematic because the inadvertent
introduction of a decimal digit ends the octal escape and introduces
another character. It is better not to use octal constants or escape
sequences at all and to statically check for any occurrences.
The integer constant zero (written as a single numeric digit) is, strictly
speaking, an octal constant, but is a permitted exception to this rule.
Additionally \0 is the only permitted octal escape sequence."
EXCEPTIONS
Rule ignores any #pragma parasoft / codewizard directives.
Rule ignores any values inside asm blocks.
BENEFITS
Rule increases readability and maintainability.
Rule prevents using implementation-defined values.
EXAMPLE
void foo()
{
int code1;
int code2;
int code3;
code1 = 052;
/* Violation */
code2 = 071;
/* Violation */
code3 = '\100'; /* Violation */
}
REPAIR
void foo1()
{
int code1;
int code2;
int code3;
code1 = 42;
code2 = 57;
code3 = 64;
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 7
2. Origin: Misra Guidelines - Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 149
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-2
The static storage class specifier shall be used in definitions and declarations of objects and
functions that have internal linkage [MISRA2004-8_11-3]
DESCRIPTION
"It is good practice to apply the static keyword consistently to
all declarations of objects and functions with internal linkage."
See also: CODSTA-81
BENEFITS
Rule improves good programming style and readability.
EXAMPLE
/* file.h */
static int x;
/* file.c */
#include "file.h"
extern int x;
/* Violation */
REPAIR
/* file.h */
static int x;
/* file.c */
#include "file.h"
static int x;
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 138
When an array is declared with external linkage, its size shall be stated explicitly or defined
implicitly by initialisation [MISRA2004-8_12-3]
DESCRIPTION
"When an array is declared with external linkage, its size shall be stated
explicitly or defined implicitly by initialisation.
Although it is possible to declare an array of incomplete type and access
its elements, it is safer to do so when the size of the array may be
explicitly determined."
BENEFITS
Rule prevents undefined behaviour and improves safety of code.
EXAMPLE
extern int array2[ ]; /* Violation */
extern int array1[ ]; /* Violation */
REPAIR
int array2[ ] = { 0, 10, 15 };
extern int array1[ 10 ];
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-3
Whenever a function is declared or defined, its type shall be explicitly stated [MISRA20048_2_a-3]
DESCRIPTION
If return types are not explicitly declared, functions will implicitly
receive
int as the return type. However, the compiler will still generate a
warning
for a missing return type. To avoid confusion, functions that do not
return
a value should specify void as the return type. This rule detects if you
do not
explicitly declare return types in functions.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
foo1( void );
/* Violation */
static foo2( void ); /* Violation */
const foo3( void ); /* Violation */
foo4(int i){
return i;
}
/* Violation */
foo5(int i){
return;
}
/* Violation */
REPAIR
int foo1( void );
/* OK */
static int foo2( void ); /* OK */
const int foo3( void ); /* OK */
int foo4(int i){
return i;
/* OK */
}
void foo5(int i){
return;
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Misra Guidelines - Rule 75
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 6 Style - 6.2 Functions - Rec. 20
From: 9 Functions - 9.4 Return types and Values - Rule. 33
Whenever an object is declared or defined, its type shall be explicitly stated [MISRA20048_2_b-3]
DESCRIPTION
The rule reports violations on declarations of parameters and variables
where
the type is not explicitly stated.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
extern x;
const y;
z;
/* Violation
/* Violation
/* Violation
*/
*/
*/
*/
*/
REPAIR
extern int x;
const int y;
int z;
/* OK
/* OK
/* OK
*/
*/
*/
*/
*/
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 8
BENEFITS
Rule prevents undefined behaviour and improves readability.
EXAMPLE
typedef int MyInt;
typedef MyInt MyInt2;
int foo1( );
MyInt foo1( ) {
return 0;
}
/* Violation */
MyInt2 foo2( );
int foo2( ) {
return 0;
}
/* Violation */
REPAIR
typedef int MyInt;
typedef MyInt MyInt2;
int foo1( );
int foo1( ) {
return 0;
}
/* OK */
MyInt2 foo2( );
MyInt2 foo2( ) {
return 0;
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 72
BENEFITS
Rule prevents undefined behaviour and improves readability.
EXAMPLE
typedef int MyInt1;
typedef MyInt1 MyInt2;
void
void
void
void
foo1(
foo1(
foo2(
foo2(
MyInt1
int a,
int a,
int a,
a, int
MyInt1
MyInt1
MyInt2
b
b
b
b
);/* Violation */
) {}
);/* Violation */
) {}
b
b
b
b
);
/* OK */
) {}
);
/* OK */
) {}
REPAIR
typedef int MyInt1;
typedef MyInt1 MyInt2;
void
void
void
void
foo1(
foo1(
foo2(
foo2(
MyInt1
MyInt1
int a,
int a,
a, int
a, int
MyInt2
MyInt2
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 72
NOTES
Rule is enabled only for C language.
"A header file is defined as any file that is included via #include,
as opposed to any file with the .h suffix."
BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.
EXAMPLE
/* file.h */
int var1;
const int var2;
static int var3;
static const int var4;
extern const int var5 = 5;
/*
/*
/*
/*
/*
Violation
Violation
Violation
Violation
Violation
*/
*/
*/
*/
*/
void foo1(){}
extern void foo2(){}
inline void foo3(){}
static void foo4(){}
/*
/*
/*
/*
Violation
Violation
Violation
Violation
*/
*/
*/
*/
/* file.c */
#include "file.h"
REPAIR
/* file.h */
extern int var1;
extern const int var2;
extern const int var5;
/* OK */
/* OK */
/* OK */
void foo1();
extern void foo2();
inline void foo3();
/* OK */
/* OK */
/* OK */
/* file.c */
#include "file.h"
int var1;
const int var2;
static int var3;
static const int var4;
const int var5 = 5;
void foo1(){}
void foo2(){}
inline void foo3(){}
static void foo4(){}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
BENEFITS
Rule prevents undefined behaviour and improves readability.
EXAMPLE
void foo1( ) {
void foo2( );
}
/* Violation */
REPAIR
void foo2( );
void foo1( ) {
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 68
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 107
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-2
Objects shall be defined at block scope if they are only accessed from within a single function
[MISRA2004-8_7-3]
DESCRIPTION
"The scope of objects shall be restricted to functions where possible.
It is considered good practice to avoid making identifiers global
except where necessary. Whether objects are declared at the outermost
or innermost block is largely a matter of style."
NOTES
Rule checks only variables with internal linkage.
No violation is reported if variable is not used at all.
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
static int max = 10; /* Violation */
void foo( ) {
while(max >= 0) {
max--;
}
}
REPAIR
void foo( ) {
int max = 10; /* OK */
while(max >= 0) {
max--;
}
}
REFERENCES
Braces shall be used to indicate and match the structure in the non-zero initialization of arrays
and structures [MISRA2004-9_2-3]
DESCRIPTION
"ISO C requires initializer lists for arrays, structures and union types
to be
enclosed in a single pair of braces (though the behaviour if this is not
done
is undefined). The rule given here goes further in requiring the use
of additional braces to indicate nested structures.
The zero initialization of arrays or structures shall only be applied
at the top level. The non-zero initialization of arrays or structures
requires an explicit initializer for each element."
NOTES
Rule checks only up to three-level nested bracket initialization.
EXCEPTIONS
"All the elements of arrays or structures can be initialized (to zero or
NULL)
by giving an explicit initializer for the first element only. If this
method
of initialization is chosen then the first element should be initialized
to zero (or NULL), and nested braces need not be used."
BENEFITS
"This forces the programmer to explicitly consider and demonstrate the
order
in which elements of complex data types are initialized"
EXAMPLE
int y[3][2] = { 1, 2, 3, 4, 5, 6 }; // Violation
struct S {
int i;
struct T {
int j;
}t;
} s = {1, 2}; // Violation
REPAIR
int y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // OK
struct S {
int i;
struct T {
int j;
}t;
} s = {1, { 2 }}; // OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Misra Guidelines - Rule 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 144
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-2
In an enumerator list, the "=" construct shall not be used to explicitly initialise members other
than the first, unless all items are explicitly initialised [MISRA2004-9_3-3]
DESCRIPTION
"In enumerator list, the '=' construct shall not be used
to explicitly initialize members other than the first,
unless all items are explicitly initialized."
BENEFITS
Helps avoid errors and confusion.
EXAMPLE
enum TEST { /* Violation */
X = 1,
Y,
Z = 3,
};
enum TEST2 { /* Violation */
X2,
Y2 = 2,
Z2,
};
enum TEST3 { /* Violation */
X3,
Y3,
Z3 = 3,
};
REPAIR
enum TEST { /* OK */
X,
Y,
Z,
};
enum TEST2 { /* OK */
X2 = 1,
Y2,
Z2,
};
enum TEST3 { /* OK */
X3 = 1,
Y3 = 2,
Z3 = 3,
};
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Origin: Misra Guidelines - Rule 32
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-3
MISRA2008
MISRA C++ 2008
RULES
Every defined function shall be called at least once [MISRA2008-0_1_10-3]
There shall be no unused parameters (named or unnamed) in nonvirtual
functions [MISRA2008-0_1_11-3]
A project shall not contain unreachable code in 'else' block [MISRA20080_1_1_a-3]
A project shall not contain unreachable code after 'return', 'break',
'continue', and 'goto' statements [MISRA2008-0_1_1_b-3]
A project shall not contain unreachable code in 'if/else/while/for' block
[MISRA2008-0_1_1_c-3]
A project shall not contain unreachable code in switch statement
[MISRA2008-0_1_1_d-3]
A project shall not contain unreachable code in 'for' loop [MISRA20080_1_1_e-3]
A project shall not contain unreachable code after 'if' or 'switch'
statement outside 'for/while/catch' block [MISRA2008-0_1_1_f-3]
A project shall not contain unreachable code after 'if' or 'switch'
statement inside 'while/for/catch' block [MISRA2008-0_1_1_g-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_a-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_b-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_c-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_d-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_e-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_f-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_g-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_h-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_i-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_j-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_k-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_l-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_m-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_n-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_o-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_p-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_q-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_r-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_rz-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_s-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_sz-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_t-3]
A project shall not contain infeasible paths [MISRA2008-0_1_2_u-3]
[MISRA2008-14_5_3-3]
In a class template with a dependent base, any name that may be found in
that dependent base shall be referred to using a qualified-id or this->
[MISRA2008-14_6_1-3]
All partial and explicit specializations for a template shall be declared
in the same file as the declaration of their primary template [MISRA200814_7_3-3]
Overloaded function templates shall not be explicitly specialized
[MISRA2008-14_8_1-3]
The viable function set for a function call should either contain no
function specializations, or only contain function specializations
[MISRA2008-14_8_2-4]
An exception object should not have pointer type [MISRA2008-15_0_2-4]
Control shall not be transferred into a try or catch block using a goto or
a switch statement [MISRA2008-15_0_3-3]
The assignment-expression of a throw statement shall not itself cause an
exception to be thrown [MISRA2008-15_1_1-3]
NULL shall not be thrown explicitly [MISRA2008-15_1_2-3]
An empty throw (throw;) shall only be used in the compound statement of a
catch handler [MISRA2008-15_1_3-3]
Exceptions shall be raised only after start-up and before termination of
the program [MISRA2008-15_3_1-3]
There should be at least one exception handler to catch all otherwise
unhandled exceptions [MISRA2008-15_3_2-4]
Handlers of a function-try-block implementation of a class constructor or
destructor shall not reference non-static members from this class or its
bases [MISRA2008-15_3_3-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point
[MISRA2008-15_3_4_a-3]
Each exception explicitly thrown in the code shall have a handler of a
compatible type in all call paths that could lead to that point
[MISRA2008-15_3_4_b-3]
A class type exception shall always be caught by reference [MISRA200815_3_5-3]
Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases, the
handlers shall be ordered most-derived to base class [MISRA2008-15_3_6-3]
A class destructor shall not exit with an exception [MISRA2008-15_5_1-3]
Where a function's declaration includes an exception-specification, the
function shall only be capable of throwing exceptions of the indicated
type(s) [MISRA2008-15_5_2-3]
The terminate() function shall not be called implicitly [MISRA2008-15_5_33]
3]
The plain char type shall only be used for the storage and use of
character values [MISRA2008-5_0_11-3]
signed char and unsigned char type shall only be used for the storage and
use of numeric values [MISRA2008-5_0_12-3]
The condition of an if-statement and the condition of an iterationstatement shall have type bool [MISRA2008-5_0_13-3]
The first operand of a conditional-operator shall have type bool
[MISRA2008-5_0_14-3]
Array indexing shall be the only form of pointer arithmetic [MISRA20085_0_15-3]
Subtraction between pointers shall only be applied to pointers that
address elements of the same array [MISRA2008-5_0_17-3]
>, >=, <, <= shall not be applied to objects of pointer type, except where
they point to the same array [MISRA2008-5_0_18-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_a-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_b-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_c-3]
The declaration of objects shall contain no more than two levels of
pointer indirection [MISRA2008-5_0_19_d-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_a-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_b-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_c-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_d-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_e-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_f-3]
The value of an expression shall be the same under any order of evaluation
that the standard permits [MISRA2008-5_0_1_g-3]
Non-constant operands to a binary bitwise operator shall have the same
underlying type [MISRA2008-5_0_20-3]
Bitwise operators shall only be applied to operands of unsigned underlying
type [MISRA2008-5_0_21-3]
Limited dependence should be placed on C++ operator precedence rules in
expressions [MISRA2008-5_0_2_a-4]
The continue statement shall only be used within a well-formed for loop
[MISRA2008-6_6_3-3]
For any iteration statement there shall be no more than one break or goto
statement used for loop termination [MISRA2008-6_6_4-3]
A function shall have a single point of exit at the end of the function
[MISRA2008-6_6_5-3]
A variable which is not modified shall be const qualified [MISRA20087_1_1-3]
A pointer parameter in a function shall be declared as pointer to const if
the corresponding object is not modified [MISRA2008-7_1_2_a-3]
A reference parameter in a function shall be declared as reference to
const if the corresponding object is not modified [MISRA2008-7_1_2_b-3]
Declare a type of parameter as typedef to pointer to const if the pointer
is not used to modify the addressed object [MISRA2008-7_1_2_c-3]
The global namespace shall only contain main, namespace declarations and
extern "C" declarations [MISRA2008-7_3_1-3]
The identifier main shall not be used for a function other than the global
function main [MISRA2008-7_3_2-3]
There shall be no unnamed namespaces in header files [MISRA2008-7_3_3-3]
using-directives shall not be used [MISRA2008-7_3_4-3]
Multiple declarations for an identifier in the same namespace shall not
straddle a using-declaration for that identifier [MISRA2008-7_3_5-3]
All usage of assembler shall be documented [MISRA2008-7_4_1-3]
Assembler instructions shall only be introduced using the asm declaration
[MISRA2008-7_4_2-3]
Assembly language shall be encapsulated and isolated [MISRA2008-7_4_3-3]
A function shall not return a reference or a pointer to an automatic
variable (including parameters), defined within the function [MISRA20087_5_1-3]
The address of an object with automatic storage shall not be assigned to
another object that may persist after the first object has ceased to exist
[MISRA2008-7_5_2-3]
A function shall not return a reference or a pointer to a parameter that
is passed by reference or const reference [MISRA2008-7_5_3-3]
Functions should not call themselves, either directly or indirectly
[MISRA2008-7_5_4-4]
An init-declarator-list or a member-declarator-list shall consist of a
single init-declarator or member-declarator respectively [MISRA2008-8_0_13]
Parameters in an overriding virtual function shall either use the same
default arguments as the function they override, or else shall not specify
any default arguments [MISRA2008-8_3_1-3]
Functions shall not be defined using the ellipsis notation [MISRA20088_4_1-3]
SINCE
v7.2
NOTES
The rule checks following functions:
- in C:
- static functions,
- in C++:
- non-template global static functions,
- non-template global functions in anonymous namespaces,
- non-template non-static non-operator private member functions
BENEFITS
"Functions or procedures that are not called may be symptomatic of a
serious
problem, such as missing paths."
EXAMPLE
static void foo() // Violation
{
/* ... */
}
int main()
{
return (0);
}
REPAIR
static void foo() // OK
{
/* ... */
}
int main()
{
foo();
return (0);
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-10
SINCE
v7.2
EXCEPTIONS
"An unnamed parameter in the definition of a function that is used as
a callback does not violate this rule."
BENEFITS
"Unused function parameters are often due to design changes and can
lead to mismatched parameter lists."
EXAMPLE
int Foo(int i, int k)
{
i = 5;
return i;
}
// Violation
REPAIR
int Foo(int i)
{
i = 5;
return i;
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-11
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo(int a, int b)
{
if(a == a){
a = a + b;
}
else{
// Violation
a = a - b;
}
}
REPAIR
void foo(int a, int b)
{
if(a == 3){
a = a + b;
}
else{
a = a - b;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
A project shall not contain unreachable code after 'return', 'break', 'continue', and 'goto'
statements [MISRA2008-0_1_1_b-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
Rule detects unreachable code after 'return', 'break',
'continue' and 'goto' statements.
See also: MISRA2004-14_1_a, MISRA2004-14_1_c, MISRA2004-14_1_d, MISRA200414_1_e,
MISRA2004-14_1_f, MISRA2004-14_1_g
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// Violation
foo();
case 2:
j = 3;
return j; // Violation
foo();
}
}
REPAIR
void foo();
int myFunction(int i, int j)
{
switch(i)
{
case 1:
j = 5;
break;
// OK
case 2:
j = 3;
return j; // OK
}
foo();
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo()
{
int unreachable_code = 1;
if(0)
{
unreachable_code = 2;
}
}
// Violation
REPAIR
There shall be no unreachable code
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 52
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo( int i ) {
switch (i) {
// Violation
i = 0;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}
REPAIR
void foo( int i ) {
switch (i) {
// OK
case 0:
i = 0;
break;
case 1:
i = 1;
break;
default:
i = 2;
break;
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
void foo( int i, int j )
{
for ( i = 0; i < 0; i++ )
{
j = 1;
}
}
// Violation
REPAIR
void foo( int i, int j )
{
for ( i = 0; i < 5; i++ )
{
j = 1;
}
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
A project shall not contain unreachable code after 'if' or 'switch' statement outside
'for/while/catch' block [MISRA2008-0_1_1_f-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation if:
- the code is after 'if/else' construction, where each branch has
unconditional
'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_g
SINCE
v7.0
NOTES
This rule does not report violations on the code inside loop.
Rule MISRA2004-14_1_g reports violations on the code inside loop.
BENEFITS
Rule helps avoid useless code.
EXAMPLE
int foo1( int c ) {
if ( c > 2 ) {
return 0;
} else {
return 1;
}
return c;
// Violation
// unreachable code
}
int foo2( int i ) {
switch(i){
case 1:
i++;
return 0;
case 2:
i = i + 2;
return 1;
default:
return 2;
}
return i;
}
// Violation
// unreachable code
REPAIR
int foo1( int
if ( c > 2
return
} else {
return
}
}
c ) {
) {
0;
// OK
c;
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
A project shall not contain unreachable code after 'if' or 'switch' statement inside
'while/for/catch' block [MISRA2008-0_1_1_g-3]
DESCRIPTION
"This rule refers to code which cannot under any circumstances be reached,
and which can be identified as such at compile-time. Code that can be
reached
but may never be executed is excluded from the rule (e.g. defensive
programming
code). A portion of code is unreachable if there is no control flow path
from
the relevant entry point to that code."
The rule reports a violation on the code inside loop if:
- the code is after 'if/else' construction, where each branch has
unconditional
'break', 'continue' or 'return'
- the code is after switch which has unconditional 'return' inside each
'case'
and 'default'
See also: MISRA2004-14_1_a, MISRA2004-14_1_b, MISRA2004-14_1_c,
MISRA2004-14_1_d, MISRA2004-14_1_e, MISRA2004-14_1_f
SINCE
v7.0
BENEFITS
Rule helps avoid useless code.
EXAMPLE
int foo( int c ) {
while ( c > 1 ) {
if ( c > 2 ) {
continue;
} else {
break;
}
// Violation
c++;
// unreachable code
}
for (int i = 0; i > 1; i++ ) {
switch(i){
// Violation
case 1:
i++;
return i;
case 2:
i = i + 2;
return i;
default:
return i;
}
c++;
// unreachable code
}
return c;
}
REPAIR
int foo( int c ) {
while ( c > 1 ) {
c++;
if ( c > 2 ) {
continue;
} else {
break;
}
}
// OK
}
return c;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 186
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-1
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a <= 1)&&(a >= 2));
if((a < 1)&&(a > 2));
if((a >= 2)&&(a <= 1));
if((a > 2)&&(a < 1));
}
//
//
//
//
Violation
Violation
Violation
Violation
//
//
//
//
OK
OK
OK
OK
REPAIR
void myFunction(int a)
{
if((a <= 5)&&(a >= 2));
if((a < 5)&&(a > 2));
if((a >= 2)&&(a <= 5));
if((a > 2)&&(a < 5));
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b >= 2)
if(b < 2) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b >= 2)
if(b < 7) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b < 2)
if(b >= 2) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b < 2)
if(b >= 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b <= 2)
if(b < 3) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b <= 2)
if(b < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(b == 2)
if(b < 1) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(b == 2)
if(a < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 > b)
if(b < 5) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 > b)
if(b < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 >= b)
if(b < 5) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 >= b)
if(b < 1) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 < b)
if(b > 1) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 < b)
if(b > 5) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int a, int b)
{
if(2 <= b)
if(b > 1) /* Violation */
a++;
}
REPAIR
void foo(int a, int b)
{
if(2 <= b)
if(b > 5) /* OK */
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunc()
{
unsigned int a;
if (a >= 0)
// Violation
a++;
}
REPAIR
void myFunc()
{
unsigned int a;
if (a >= 2)
// OK
a++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 128)
b++;
if (a < 256)
a++;
// Violation
// Violation
REPAIR
void myFunc()
{
unsigned char a;
signed char b;
if (b >= 127)
b++;
if (a < 255)
a++;
}
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65536)
a++;
if (b <= 32767)
b++;
// Violation
// Violation
REPAIR
void myFunc()
{
unsigned short a;
signed short b;
if (a < 65535)
a++;
if (b <= 32766)
b++;
}
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > -1)&&(a < -2));
if((a >= -1)&&(a <= -2));
if((a < -2)&&(a > -1));
if((a <= -2)&&(a >= -1));
}
//
//
//
//
Violation
Violation
Violation
Violation
//
//
//
//
OK
OK
OK
OK
REPAIR
void myFunction(int a)
{
if((a > -5)&&(a < -2));
if((a >= -5)&&(a <= -2));
if((a < -2)&&(a > -5));
if((a <= -2)&&(a >= -5));
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > 0)&&(a < -1));
if((a < -1)&&(a >= 0));
if((a == -5)&&(a == 5));
if((3 < a)&&(-3 > a));
}
//
//
//
//
Violation
Violation
Violation
Violation
//
//
//
//
OK
OK
OK
OK
REPAIR
void myFunction(int a)
{
if((a < 0)&&(a > -1));
if((a > -1)&&(a <= 0));
if((a != -5)&&(a != 5));
if((3 > a)&&(-3 < a));
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a, int b)
{
if((a > b)&&(a < b));
// Violation
if((a < b)&&(a >= b)); // Violation
}
REPAIR
void myFunction(int a, int b, int c)
{
if((a > b)&&(a < c));
// OK
if((a < b)&&(a >= c)); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a >= 0)||(a < 0));
if((5 > a)||(a > 3));
if((a <= 4)||(a >= 3));
}
// Violation
// Violation
// Violation
REPAIR
void myFunction(int a)
{
if((a >= 10)||(a < 0));
if((5 > a)||(a > 13));
if((a <= 4)||(a >= 13));
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > -4)||(a < -3));
if((-1 > a)||(-3 < a));
if((a < -3)||(-5 < a));
}
// Violation
// Violation
// Violation
REPAIR
void myFunction(int a)
{
if((a > -4)||(a < -13));
if((-11 > a)||(-3 < a));
if((a < -13)||(-5 < a));
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a)
{
if((a > -2)||(a < 1));
if((4 > a)||(-3 < a));
if((a > -4)||(2 > a));
}
// Violation
// Violation
// Violation
REPAIR
void myFunction(int a)
{
if((a < -2)||(a > 1));
if((4 < a)||(-3 > a));
if((a < -4)||(2 < a));
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Rule does not report violation if the variable used in both 'if' condition
is volatile or modified between statements.
Rule assumes that the variable passed to function could be modified.
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void foo(int b)
{
if(b > 2)
if(b >= 1)
/* Violation */
b++;
}
REPAIR
void foo(int b)
{
if(b > 2)
if(b >= 5)
/* OK */
b++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
'true'
or always 'false', it is highly likely that there is a programming error."
EXAMPLE
void myFunction(int a, int b)
{
if((a >= b)||(a <= b)); // Violation
if((a < b)||(a >= b));
// Violation
}
REPAIR
void myFunction(int a, int b, int c)
{
if((a >= b)||(a <= c));
// OK
if((a < c)||(a >= b));
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN > col); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(BLUE > col); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE > 0);
if(10 <= ONE);
if(ci > 0);
for(i = 5; i < i; i++);
if(ZERO > 10 && i > 3);
}
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
#define FALSE 0
const int ci = 10;
enum E{ZERO, ONE}en;
void foo(int i){
if(FALSE);
for(i = 5; i < ci; i++);
if(ZERO == en);
}
// OK
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < GREEN); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col < RED); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > YELLOW); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(col > RED); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(YELLOW < col); // Violation
}
REPAIR
void myFunctionEnum(){
enum ec {RED = 8, BLUE = 7, GREEN = 2, YELLOW = 10} col;
if(GREEN < col); // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
< 0);
< 16);
<= 15);
<= 16);
> 15);
> 16);
>= 0);
>= 16);
//
//
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
if(col1
< 1);
< 15);
<= 0);
<= 1);
> 0);
> 1);
>= 1);
//
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(15 < col1);
if(16 < col1);
if(0 <= col1);
if(16 <= col1);
if(0 > col1);
if(16 > col1);
if(15 >= col1);
if(16 >= col1);
}
//
//
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(0 < col1);
if(1 < col1);
if(1 <= col1);
if(15 <= col1);
if(1 > col1);
if(15 > col1);
if(0 >= col1);
//
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
BENEFITS
"If a Boolean operator yields a result that can be proven to be always
"true"
or always "false", it is highly likely that there is a programming error."
EXAMPLE
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 14 );
if(col1 != 14 );
if(14 == col1);
if(14 != col1);
//
//
//
//
Violation
Violation
Violation
Violation
REPAIR
void myFunctionEnum(){
enum ec1 {BLACK, WHITE, GREY, PINK = 15} col1;
if(col1 == 15);
if(col1 != 15);
if(15 == col1);
if(15 != col1);
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-2
NOTES
Objects can perform some actions in their constructors. Even if they are
not
used later they might have done their job during creation. This rule does
not
consider such objects as "used" and will report a violation.
BENEFITS
Eliminating unused local variables increases efficiency and legibility.
EXAMPLE
class A {
public:
void displBalance();
};
void foo( ) {
A a;
}
// Violation
int func(int j) {
int i = 0; // Violation
return j;
}
REPAIR
class A {
public:
void displBalance( );
};
void foo( ) {
A a;
a.displBalance( );
}
int func(int j) {
int i = j + 1;
return i;
}
// OK
// OK
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3
NOTES
The rule does not report violations on variables of type class/struct that
have explicitly declared constructor or destructor.
BENEFITS
Eliminating local variables that are not useful increases efficiency
and legibility of code.
EXAMPLE
class A {
};
int func(int p) {
A a;
// Violation
int i = 0; // Violation
i = p;
i++;
return p;
}
REPAIR
class A {
public:
A();
};
int func(int p) {
A a;
// OK - implicit call of constructor can cause additional
action
int i = 0; // OK
i = p;
i++;
return i;
}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3
The value returned by a function having a non-void return type that is not an overloaded
operator shall always be used [MISRA2008-0_1_7-3]
DESCRIPTION
"In C++ it is possible to call a function without using the return value,
which may be an error. The return value of a function shall always be
used."
SINCE
v7.2
EXCEPTIONS
"The return value of a function may be discarded by use of a (void) cast.
Overloaded operators are excluded, as they should behave in the same way
as built-in operators."
BENEFITS
Rule improves readability of code
EXAMPLE
short func ( short para1 )
{
return para1;
}
void discarded ( short para2 )
{
func ( para2 );
// Violation
}
REPAIR
short func ( short para1 )
{
return para1;
}
void discarded ( short para2 )
{
(void)func ( para2 );
// OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-7
All functions with void return type shall have external side effect(s) [MISRA2008-0_1_8-3]
DESCRIPTION
A function which does not return a value and which does not have external
side
effects will only consume time and will not contribute to the generation
of any
outputs, which may not meet developer expectations.
The following are examples of external side effects:
- Reading or writing to a file, stream, etc.;
- Changing the value of a non local variable;
- Changing the value of an argument having reference type;
- Using a volatile object;
- Raising an exception.
SINCE
v7.2
BENEFITS
Rule prevents unnecessary time consumption.
EXAMPLE
void foo( void ) // Violation
{
int local;
local = 0;
}
REPAIR
int foo( int p ) // OK
{
int local;
local = 10*p;
/* ... */
return local;
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-8
BENEFITS
Rule prevents undefined behaviour and data loss.
EXAMPLE
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {
union U a, b;
union U *p;
(void)memcpy( &a.dValue, &a.lValue, 8 );
(void)memcpy( &p->dValue, &p->iValue, 8 );
return 0;
}
REPAIR
#include <string.h>
union U {
int
iValue;
long
lValue;
double
dValue;
};
int main( ) {
/* Violation */
/* Violation */
union U a, b;
union U *p, *q;
(void)memcpy( &a.dValue, &b.lValue, 8 );
(void)memcpy( &p->dValue, &q->iValue, 8 );
return 0;
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-2-1
SINCE
v7.2
BENEFITS
"Assigning between objects that have an overlap in their physical storage
leads to undefined behaviour."
EXAMPLE
union U {
int
long
double
};
iValue;
lValue;
dValue;
void main( ) {
union U a, b;
union U *p;
a.dValue = a.lValue;
p->dValue = p->iValue;
}
REPAIR
union U {
int
long
double
};
iValue;
lValue;
dValue;
// Violation
// Violation
void main( ) {
union U a, b;
union U *p, *q;
a.dValue = b.lValue;
p->dValue = q->iValue;
}
// OK
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-2-1
If a function generates error information, then that error information shall be tested
[MISRA2008-0_3_2-3]
DESCRIPTION
"A function (whether it is part of the standard library, a third party
library
or a user defined function) may provide some means of indicating the
occurrence
of an error. This may be via an error flag, some special return value or
some
other means. Whenever such a mechanism is provided by a function the
calling
program shall check for the indication of an error as soon as the function
returns.
However, note that the checking of input values to functions is considered
a more robust means of error prevention than trying to detect errors after
the function has completed (see Rule MISRA2004-20_3). Note also that the
use
of errno (to return error information from functions) is clumsy and should
be
used with care (see Rule MISRA2004-20_5)."
NOTES
Rules checks usage of function calls which returns char, short, int, enum,
or typedef to char, short, int, or enum value and reports violation when
this value is not assigned, checked or cast to void.
BENEFITS
Rule helps writing safety code.
EXAMPLE
int SomeFunctionReturningError( );
void foo( )
{
SomeFunctionReturningError( ); // Violation
}
REPAIR
int SomeFunctionReturningError( );
int foo( )
{
int x;
x = SomeFunctionReturningError( );
(void)SomeFunctionReturningError( );
if (SomeFunctionReturningError( ));
switch (SomeFunctionReturningError( )) {
}
return SomeFunctionReturningError( );
}
//
//
//
//
OK
OK
OK
OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 86
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 115
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-3-2
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 7
6. http://cwe.mitre.org/data/definitions/391.html
SINCE
v7.2
BENEFITS
"The safe use of floating-point arithmetic requires a high level of
numerical
analysis skills and indepth knowledge of the compiler and target
hardware."
EXAMPLE
// Violation in line: double d = d1 + d2;
double add(double d1, double d2)
{
double d = d1 + d2;
}
REPAIR
double add(double d1, double d2)
{
double d = d1 + d2; // OK - floating point arithmetic
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-4-2
SINCE
v7.2
BENEFITS
"The use of virtual base classes can introduce a number of undefined
and potentially confusing behaviours."
EXAMPLE
class B {};
class D: public virtual B {}; // Violation
REPAIR
Do not inherit from virtual base classes
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-1-1
An accessible base class shall not be both virtual and non-virtual in the same hierarchy
[MISRA2008-10_1_3-3]
DESCRIPTION
A base class shall not be both virtual and non-virtual
in the same hierarchy.
SINCE
v7.1
BENEFITS
Hierarchy becomes easier to comprehend and use.
EXAMPLE
class A {};
class B : virtual A {};
class C : B, A {};
// Violation
REPAIR
class A {};
class B : virtual A {};
class C : B, virtual A {};
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 89
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-1-3
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
There shall be no more than one definition of each virtual function on each path through the
inheritance hierarchy [MISRA2008-10_3_1-3]
DESCRIPTION
"The main aim of this rule is clarity for maintainers and reviewers,
by ensuring that the version of a function that can be executed from
any point in a class hierarchy is unambiguous."
SINCE
v7.2
EXCEPTIONS
"Destructors may be declared virtual in multiple members of a class
hierarchy.
If a function is declared pure and defined in the same class, then that
definition is ignored for this rule."
BENEFITS
"Additionally, where classes form a diamond hierarchy, call
by dominance may occur resulting in a call to a function that
is inconsistent with developer expectations.
This rule also prevents call by dominance."
EXAMPLE
/* Examples of incorrect code */
class A
{
public:
virtual void f1 ( );
virtual void f2 ( ) { }
};
void A::f1 ( )
{
}
class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
};
void B::f2 ( )
{
}
// Violation
// Violation
REPAIR
/* Examples of
class A
{
public:
virtual
virtual
virtual
};
void A::f2 ( )
{
}
correct code */
void f1 ( );
void f2 ( ) = 0;
~A(){}
class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
virtual ~B(){}
};
void B::f2 ( )
{
}
// OK
// OK
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-1
Each overriding virtual function shall be declared with the virtual keyword [MISRA200810_3_2-3]
DESCRIPTION
Using the virtual keyword whenever a subclass implements a virtual
function
makes the code more readable, because the reader does not have to refer
back
to the base class to see that the function is virtual. This rule detects
if a subclass implements a virtual function without using a virtual
keyword.
BENEFITS
Readability, as well as more intuitive behavior for deep inheritance
hierarchies, in that functions that are virtual in a base class will
remain virtual in all inherited classes.
EXAMPLE
class A {
public:
virtual int foo( );
};
class B : public A {
public:
int foo( );
};
int B::foo() {
return 5;
}
REPAIR
class A {
public:
virtual int foo( );
};
// Violation
class B : public A {
public:
virtual int foo( );
};
// OK
int B::foo() {
return 5;
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-3-2
A virtual function shall only be overridden by a pure virtual function if it is itself declared as
pure virtual [MISRA2008-10_3_3-3]
DESCRIPTION
"A virtual function shall only be overridden by a pure
virtual function if it is itself declared as pure virtual."
SINCE
v7.2
BENEFITS
Rule prevents writing a code contrary to developer expectations.
EXAMPLE
class A
{
public:
virtual void foo ( );
};
class B: public A
{
public:
virtual void foo ( ) = 0; // Violation
};
REPAIR
Do not override non-pure virtual functions by pure virtual functions
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-3
SINCE
v7.2
BENEFITS
"By implementing class interfaces with member functions,
the implementation retains more control over how the object
state can be modified, and helps to allow a class to be
maintained without affecting clients.
EXAMPLE
typedef signed int int32_t;
class C
{
public:
int32_t b; // Violation
protected:
int32_t c; // Violation
};
REPAIR
typedef signed int int32_t;
class C
{
private:
int32_t b; // OK
int32_t c; // OK
protected:
const int32_t access_b();
const int32_t access_c();
};
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 11, Rule 11-0-1
An object's dynamic type shall not be used from the body of its constructor or destructor
[MISRA2008-12_1_1-3]
DESCRIPTION
"During construction and destruction of an object, its final type
may be different to that of the completely constructed object."
"Member functions (including virtual member functions) can be called for
an
object under construction. Similarly, an object under construction can be
the
operand of the typeid operator or of a dynamic_cast. However, if these
operations are performed in a ctor-initializer (or in a function called
directly or indirectly from a ctor-initializer) before all the meminitializers
for base classes have completed, the result of the operation is
undefined."
SINCE
v7.2
BENEFITS
"The result of using an object's dynamic type in a constructor or
destructor may not be consistent with developer expectations."
EXAMPLE
/* Examples of incorrect code */
#include <typeinfo>
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
typeid ( B2 );
// Violation
foo ( );
// Violation
dynamic_cast< B2* > ( this ); // Violation
}
};
REPAIR
/* Examples of correct code */
#include <typeinfo>
class B1
{
public:
B1 ( )
{
typeid ( B1 ); // OK - B1 not polymorphic
}
};
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
B2::foo ( );
// OK - not a virtual call
}
};
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-1
2. ISO/DIS 26262
point 8.4.4
All constructors of a class should explicitly call a constructor for all of its immediate base
classes and all virtual base classes [MISRA2008-12_1_2-4]
DESCRIPTION
"All constructors of a class should explicitly call a constructor for all
of
its immediate base classes and all virtual base classes."
SINCE
v7.2
NOTES
Rule will also report a violation if class does not define any
constructors
and has a base class with a constructor.
BENEFITS
This rule reduces confusion over which constructor will be used,
and with what parameters.
EXAMPLE
class A
{
public:
A ( )
{
}
};
class B : public A
{
public:
B ( ) // Violation
{
}
};
REPAIR
class A
{
public:
A ( )
{
}
};
class B : public A
{
public:
B ( ): A() // OK
{
}
};
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-2
All constructors that are callable with a single argument of fundamental type shall be declared
explicit [MISRA2008-12_1_3-3]
DESCRIPTION
"All constructors that are callable with a single argument
of fundamental type shall be declared explicit."
SINCE
v7.2
NOTES
The following types are fundamental: bool, char, short, int,
long, long long, float, double, long double, wchar_t.
BENEFITS
Rule prevents the constructor from being used to implicitly
convert from a fundamental type to the class type.
EXAMPLE
class C
{
public:
C ( int a ) // Violation
{
}
};
REPAIR
class C
{
public:
explicit C ( int a ) // OK
{
}
};
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-3
A copy constructor shall only initialize its base classes and the nonstatic members of the
class of which it is a member [MISRA2008-12_8_1-3]
DESCRIPTION
"If a compiler implementation detects that a call to a copy constructor
is redundant, then it is permitted to omit that call, even if the copy
constructor has a side effect other than to construct a copy of the
object."
Rule reports a violation if global or static member variable is modified
within a copy constructor.
SINCE
v7.2
NOTES
Rule checks only one nested level of function call.
BENEFITS
"It is therefore important to ensure that a copy constructor does not
modify
the program state as the number of such modifications may be
indeterminate."
EXAMPLE
class A
{
public:
A ( A const & rhs )
: m_i ( rhs.m_i )
{
++m_static;
// Violation
}
private:
int m_i;
static int m_static;
};
REPAIR
Do not modify global or static member variable within a copy constructor.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-1
The copy assignment operator shall be declared protected or private in an abstract class
[MISRA2008-12_8_2-3]
DESCRIPTION
"An abstract class represents the interface part of a hierarchy.
Invoking the copy assignment operator from the top of such
a hierarchy bypasses the underlying implementation resulting
in only the base subobjects being copied."
SINCE
v7.2
NOTES
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.
BENEFITS
"Making the abstract copy assignment operator protected allows
access from the derived classes but not from outside the hierarchy.
Making the copy assignment operator private is a common idiom used
to restrict copying objects of the class type."
EXAMPLE
typedef int int32_t;
class B1
{
public:
virtual void f( ) = 0;
B1 & operator= ( B1 const & rhs );
};
REPAIR
// Violation
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-2
A copy constructor shall be declared when there is a template constructor with a single
parameter that is a generic parameter [MISRA2008-14_5_2-3]
DESCRIPTION
"Contrary to possible developer expectations, a template constructor
will not suppress the compiler generated copy constructor."
SINCE
v7.2
NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].
BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.
EXAMPLE
typedef signed int int32_t;
class A
{
public:
A ( );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};
// Violation
REPAIR
typedef signed int int32_t;
class A
{
public:
A ( );
A ( A const & rhs );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
A copy assignment operator shall be declared when there is a template assignment operator
with a parameter that is a generic parameter [MISRA2008-14_5_3-3]
DESCRIPTION
"Contrary to possible developer expectations, a template assignment
operator will not suppress the compiler generated copy assignment
operator."
SINCE
v7.2
NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.
BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.
EXAMPLE
typedef signed int int32_t;
class A
// Violation
{
public:
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;
}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}
REPAIR
typedef signed int int32_t;
class A
// OK
{
public:
A & operator= ( A const & rhs )
{
i = rhs.i;
return *this;
}
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;
}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
In a class template with a dependent base, any name that may be found in that dependent
base shall be referred to using a qualified-id or this-> [MISRA2008-14_6_1-3]
DESCRIPTION
"In a class template with a dependent base, any name that may be found in
that
dependent base shall be referred to using a qualified-id or this->"
SINCE
v7.2
BENEFITS
"Using a qualified-id or prefixing the identifier with this-> ensures that
the entity chosen is consistent with developer expectations."
EXAMPLE
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
TYPE t = 0; // Violation
g ( );
// Violation
i++;
// Violation
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );
int i;
};
template class A<int>;
REPAIR
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
::TYPE t1 = 0; // OK ::g ( );
// OK ::i++;
// OK typename B<T>::TYPE t2
this->g ( );
this->i;
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );
int i;
};
template class A<int>;
explicit use
explicit use
explicit use
= 0; // OK // OK // OK -
global TYPE
global func
global var
explicit use base TYPE
explicit use base "g"
explicit use base "i"
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-6-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
All partial and explicit specializations for a template shall be declared in the same file as the
declaration of their primary template [MISRA2008-14_7_3-3]
DESCRIPTION
"It is undefined behaviour if, for a set of template-arguments, an
implicit
instantiation is generated by the compiler, and a partial or explicit
specialization is declared or defined elsewhere in the program that would
match the set of template-arguments."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
// file.h
template <typename T> void foo () {}
// file.cpp
#include "file.h"
template <> void foo<int> () {} // Violation
REPAIR
// file.h
template <typename T> void foo () {}
template <> void foo<int> () {} // OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-7-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
"Where a template is not overloaded with other templates, or is overloaded
with non-template functions then it can be explicitly specialized, as it
is
consistent with developer expectation that the explicit specializations
will only be considered if that primary template is chosen."
EXAMPLE
template <typename T> void f ( T );
template <typename T> void f ( T* );
template <> void f<int*> ( int* ); // Violation
REPAIR
template <typename T> void f ( T );
template <> void f<int*> ( int* ); // OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
The viable function set for a function call should either contain no function specializations, or
only contain function specializations [MISRA2008-14_8_2-4]
DESCRIPTION
"The viable function set for a function call should either contain no
function
specializations, or only contain function specializations. If a function
and a specialization of a function template are deemed equivalent after
overload resolution, the non-specialized function will be chosen over the
function specialization"
SINCE
v7.2
EXCEPTIONS
"Rule does not apply to copy constructors or copy assignment operators."
BENEFITS
Rule prevents writing of code that may be inconsistent
with developer expectations.
EXAMPLE
void f ( short b){}
template <typename T> void f ( T ){}
// Example 1
// Example 2
void b ( short s )
{
f ( s );
// Violation - Calls Example 1
f ( s + 1 ); // Violation - Calls Example 2
}
REPAIR
void f ( short b){}
// Example 1
// Example 2
void b ( short s )
{
f<> ( s );
// OK - Calls Example 2
f<> ( s + 1 ); // OK - Calls Example 2
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Prevents memory management problems
EXAMPLE
typedef short int16_t;
class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( &a1 ); // Violation pointer type thrown
}
else
{
throw ( a2 ); // Violation pointer type thrown
}
}
REPAIR
typedef short int16_t;
class A
{
// Implementation
};
void fn ( int16_t i )
{
static A a1;
A* a2 = new A;
if ( i > 10 )
{
throw ( a1 ); // OK
}
else
{
throw ( *a2 ); // OK
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. ISO/DIS 26262
point 8.4.4
Control shall not be transferred into a try or catch block using a goto or a switch statement
[MISRA2008-15_0_3-3]
DESCRIPTION
"A program is ill-formed if control is transferred into a try or catch
block
using a goto or switch statement; however, not all compilers issue
a diagnostic message."
SINCE
v7.2
BENEFITS
Rule detects errors not reported by all compilers
EXAMPLE
/* The code is compilable with MSVC 6.0 */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
try
{
Label_10: // Violation
case 2:
// Violation
break;
}
catch ( Exception e )
{
}
}
REPAIR
/* The example of correct code */
class Exception{};
void f ( int i )
{
if ( 10 == i )
{
goto Label_10;
}
switch ( i )
{
case 1:
// OK
try
{
// ...
}
catch ( Exception e )
{
}
case 2:
// OK
break;
}
Label_10:
// OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule improves readability of code
EXAMPLE
class E
{
public:
E ( )
{
throw 10;
}
};
int foo1()
{
try
{
if ( 0 )
{
throw E ( ); // Violation
}
}
catch(...)
{
}
}
REPAIR
class E
{
public:
E ( ){ }
};
int foo()
{
try
{
if ( 0 )
{
throw E ( ); // OK
}
}
catch(...)
{
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
#define NULL 0
void foo()
{
try
{
throw ( NULL ); // Violation
}
catch ( int i )
// NULL exception handled here
{
// ...
}
}
REPAIR
#define NULL 0
void foo()
{
try
{
throw ( 0 ); // OK
}
catch ( int i ) // NULL exception handled here
{
// ...
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
An empty throw (throw;) shall only be used in the compound statement of a catch handler
[MISRA2008-15_1_3-3]
DESCRIPTION
"An empty throw re-throws the temporary object that represents an
exception.
Its use is intended to enable the handling of an exception to be split
across
two or more handlers.
However, syntactically, there is nothing to prevent throw; being used
outside
a catch handler, where there is no exception object to re-throw. This may
lead
to an implementation-defined program termination."
SINCE
v7.2
BENEFITS
Rule prevents implementation-defined behaviour.
EXAMPLE
class Exception{};
void foo(int a)
{
Exception E;
if(a)
{
throw;
// Violation
}
}
REPAIR
class Exception{};
void foo(int a)
{
Exception E;
if(a)
{
throw E;
}
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-1-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Exceptions shall be raised only after start-up and before termination of the program
[MISRA2008-15_3_1-3]
DESCRIPTION
"Before the program starts executing the body of main, it is in a start-up
phase, constructing and initializing static objects. Similarly, after main
has
returned, it is in a termination phase where static objects are being
destroyed. If an exception is thrown in either of these phases it leads to
the
program being terminated in an implementation-defined manner."
SINCE
v7.2
NOTES
Rule checks only one level of nested function calls.
BENEFITS
"Throwing an exception during start-up or termination results in the
program
being terminated in an implementation-defined manner."
EXAMPLE
class C
{
public:
C ( )
{
throw ( 0 ); // Violation thrown before main starts
}
~C ( )
{
throw ( 0 ); // Violation thrown after main exits
}
};
C c;
int main( ... )
{
// ...
}
REPAIR
Exceptions should not be throwing during start-up or termination phase.
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
There should be at least one exception handler to catch all otherwise unhandled exceptions
[MISRA2008-15_3_2-4]
DESCRIPTION
"If a program throws an unhandled exception it terminates
in an implementation-defined manner. In particular, it is
implementation-defined whether the call stack is unwound, before
termination,
so the destructors of any automatic objects may or may not be executed.
By enforcing the provision of a "last-ditch catch-all", the developer can
ensure that the program terminates in a consistent manner."
Rule checks if outermost statement of the 'main' function is a try
statement
with catch-all handler.
SINCE
v7.2
NOTES
Rule check if a try statement with catch-all handler is implemented
directly
in 'main' function. Statements which are implemented in functions that are
called from 'main' function are not detected.
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
class Exception{};
int main( )
{
try // Violation
{
// ...
}
catch ( Exception e )
{
// ...
}
return 0;
}
REPAIR
class Exception{};
int main( )
{
try // OK
{
// ...
}
catch ( Exception e )
{
// ...
}
catch ( ... )
{
// ...
}
return 0;
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-2
2. http://cwe.mitre.org/data/definitions/391.html
SINCE
v7.2
BENEFITS
"The effect of accessing a non-static member of a class or a base class in
the
handler (i.e. the catch part) of a function-try-block of a class
constructor/destructor is undefined. For example, if a memory allocation
exception is thrown during creation of the object, the object will not
exist
when the handler attempts to access its members. Conversely, in the
destructor,
the object may have been successfully destroyed before the exception is
handled, so again will not be available to the handler. By contrast, the
lifetime of a static member is greater than that of the object itself, so
the
static member is guaranteed to exist when the handler accesses it."
EXAMPLE
typedef int int32_t;
class C
{
public:
int32_t x;
C( )
try
{
// Action that may raise an exception
}
REPAIR
Do not use non-static member of a class or a base class in the handler
of a function-try-block of a class constructor/destructor
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [MISRA2008-15_3_4_a-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown from body
of function 'main' or from body of function that does not have any
exception
on an exception specification list.
see also: EXCEPT-18
SINCE
v7.2
NOTES
Rule checks only one level of nested function calls.
BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."
EXAMPLE
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // Violation
}
}
catch ( A const & )
{
}
}
REPAIR
class A {};
class B {};
void main ( int i ) throw ( )
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( ); // OK
}
}
catch ( A const & )
{
}
catch ( B const & )
{
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Each exception explicitly thrown in the code shall have a handler of a compatible type in all
call paths that could lead to that point [MISRA2008-15_3_4_b-3]
DESCRIPTION
"If a program throws an unhandled exception, it terminates in an
implementation-defined manner. In particular, it is implementation-defined
whether the call stack is unwound before termination, so the destructors
of
any automatic objects may or may not be invoked. If an exception is thrown
as an object of a derived class, a "compatible type" may be either the
derived class or any of its bases."
Rule reports a violation if an unhandled exception is thrown while
a non-local object is declared or initialized.
see also: EXCEPT-13
SINCE
v7.2
NOTES
Rule checks only one level of nested function calls.
BENEFITS
"The objective of this rule is that a program should catch
all exceptions that it is expected to throw."
EXAMPLE
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10 )
{
throw A ( );
}
else
{
throw B ( );
}
}
catch ( A const & )
{
}
}
};
A a; // Violation - unhandled exception of class B
REPAIR
class B{};
class A {
int i;
A ( ) : i(1)
{
try
{
if ( i > 10
{
throw A
}
else
{
throw B
}
}
catch ( A const
{
}
catch ( B const
{
}
}
};
A a; // OK
)
( );
( );
& )
& )
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-4
SINCE
v7.2
BENEFITS
"If the exception is caught by reference, slicing does not occur."
EXAMPLE
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase b ) // Violation - derived type objects will be
// caught as the base type
{
}
}
REPAIR
class ExpBase
{
};
class ExpD1: public ExpBase
{
};
void foo()
{
try
{
throw ExpD1 ( );
throw ExpBase ( );
}
catch ( ExpBase &b ) // OK - exceptions caught by reference
{
}
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Where multiple handlers are provided in a single try-catch statement or function-try-block for
a derived class and some or all of its bases, the handlers shall be ordered most-derived to
base class [MISRA2008-15_3_6-3]
DESCRIPTION
"Where multiple handlers are provided in a single try-catch statement or
function-try-block for a derived class and some or all of its bases,
the handlers shall be ordered most-derived to base class.
When testing to see if the type of an exception matches the type of a
handler,
a derived class exception will match with a handler for its base class.
If the base class handler is found before the handler for the derived
class,
the base class handler will be used. The derived class handler is
unreachable
code and can never be executed."
SINCE
v7.2
BENEFITS
Rule prevents writing unreachable code.
EXAMPLE
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( B &b )
{
// ...
}
catch ( D &d ) // Violation
{
// ...
}
}
REPAIR
class B { };
class D: public B { };
void foo()
{
try
{
// ...
}
catch ( D &d ) // OK - Derived class caught before base class
{
// ...
}
catch ( B &b ) // OK - Base class caught after derived class
{
// ...
}
}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-3-6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Prevents throwing from within a destructor. It may lead to memory leaks
and improper object destruction.
EXAMPLE
class Foo {
public:
Foo( ) { }
~Foo( ) {
throw;
}
};
// Violation
REPAIR
class Exception {};
class Foo {
public:
Foo( ) { }
~Foo( ) {
try {
// OK
} catch (Exception& e) {
// caught all exceptions
}
}
};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
SINCE
v7.2
NOTES
Rule checks only two levels of nested function calls
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception )
{
foo ( );
}
// Violation
REPAIR
class Exception{};
void foo ( )
{
throw ( 21 );
}
void goo ( ) throw ( Exception, int ) // OK
{
foo ( );
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule prevents implementation-defined behaviour.
EXAMPLE
class C
{
public:
C() { throw 1; }
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}
REPAIR
class C
{
// Violation
public:
C()
{
try
{
/* ... */
throw 1;
}
catch(...)
{
/* ... */
}
}
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-3
BENEFITS
It is important to prevent the situation of executable code coming before
a #include directive, otherwise there is danger that the code may try to
use
items which would be defined in the header.
EXAMPLE
void foo();
int g;
#include "test.h"
// Violation
REPAIR
#include "test.h"
void foo();
int g;
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-1
3. Origin: Misra Guidelines - Rule 87
BENEFITS
Improves the readability of code.
EXAMPLE
void foo( int* x ) {
#define CHECKPARAM(p) (p != 0)
if (CHECKPARAM(x)) {
/* ... */
}
#undef CHECKPARAM
}
// Violation
// Violation
REPAIR
#define CHECKPARAM(p) (p != 0) // OK - macro is defined outside of any
blocks
void foo( int* x ) {
if (CHECKPARAM(x)) {
/* ... */
}
}
#undef CHECKPARAM
// OK - macro is undefined outside of any
blocks
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 91
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-2
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
#undef TEST
/* Violation */
REPAIR
Do not use #undef.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 92
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-3
BENEFITS
"While macros can provide a speed advantage over functions, functions
provide
a safer and more robust mechanism. This is particularly true with respect
to the type checking of parameters, and the problem of function-like
macros
potentially evaluating parameters multiple times.
See also: CODSTA-03, CODSTA-37, CODSTA-38, CODSTA-39, CODSTA-40
EXAMPLE
#define SUM(A,B) ((A)+(B))
/* Violation */
REPAIR
int sum( int a, int b ) {
return (a + b);
}
void foo( int x, int y ) {
/* ... */
sum( x, y );
/* ... */
}
REFERENCES
/* OK */
Arguments to a function-like macro shall not contain tokens that look like preprocessing
directives [MISRA2008-16_0_5-3]
DESCRIPTION
"If any of the arguments act like preprocessor directives,
the behaviour when macro substitution is made can be unpredictable."
NOTES
Rule works only within file scope.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( #foo );
MACRO2( i, #foo );
MACRO2( i, "#foo" );
}
/* Violation */
/* Violation */
/* Violation */
REPAIR
#define MACRO1(x)
#define MACRO2(x, y)
void foo( void ) {
int i = 0;
MACRO1( i );
MACRO2( i, i );
}
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 95
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-5
EXCEPTIONS
If an argument of macro is used in body after '.', '->', '::' or before
'::',
then violation is not reported, because the use of paranthesis in such
cases
makes a code non-compilable. For example:
#define INIT1(member) a->member = 0 // No violation reported
#define CALL(ns,fn) ns::fn() // No violation reported
BENEFITS
Improves the readability of code and ensures operations order.
DRAWBACKS
In some cases a violation is reported, but the use of parenthesis causes a
compilation error. For example:
#define MTYPE(type, a) (type *)(a) // Violation reported
#define MT(classtype, type) classtype<type> // Violation reported
EXAMPLE
#define abs(x) ((x >= 0) ? x : -x)
void foo(int a, int b){
int z = abs(a - b);
// Violation
REPAIR
#define abs(x) (((x) >= 0) ? (x) : -(x))
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-6
Undefined macro identifiers shall not be used in #if or #elif preprocessor directives, except as
operands to the defined operator [MISRA2008-16_0_7-3]
DESCRIPTION
If an attempt is made to use an identifier in a preprocessor directive,
and that identifier has not been defined,
the preprocessor will sometimes not give any warning but will assume
the value zero.
#ifdef, #ifndef and defined() are provided to test the existence of a
macro,
and are therefore excluded.
BENEFITS
Complying with this rule leads to safer code
and prevents hard-to-detect errors.
DRAWBACKS
1) Currently the implementation of the rule assumes that the compliance
with
the rule is provided by following MISRA 2004 19-11 advice (p. 78):
"Consideration should be given to the use of a /#ifdef/" test before
an identifier is used."
2) If #1 is not followed, due to technical limitations we are not able
to recognize cases where preprocessor identifier is defined in different
file from that where the identifier is used. Also, we are unable to
detect
that given identifier was defined as compiler command line option.
3) If tested macro identifier was earlier defined by #define preprocessor
directive, it can not be defined in more nested #if / #elif / #else /
#endif
directives. In such cases rule can report false positives.
3) If tested macro identifier is defined within complex conditional
statement (containing
few branches #elif/#else) we cannot be sure if branch containing
definition of macro
being tested is executed. In such case rule may report false positives.
EXAMPLE
#if X
/* Violation - X undefined at this point */
#endif
#if Y
/* Violation - Y undefined at this point */
#endif
#if X + Y
/* Violation - X and Y undefined at this point */
#endif
#ifdef X
#define Y 1
#else
#define Y 3
#endif
#if Y > 2
#endif
REPAIR
#define X 1
#if X
/* OK */
#endif
#ifdef Y
#if Y
/* OK - check is done in the #ifdef above */
#endif
#endif
#ifdef X
#define Y 1
#else
#define Y 3
#endif
#ifdef Y
#if Y > 2
#endif
#endif
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 97
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-7
If the # token appears as the first token on a line, then it shall be immediately followed by a
preprocessing token [MISRA2008-16_0_8-3]
DESCRIPTION
"When a section of source code is excluded by preprocessor directives,
the content of each excluded statement is ignored until a #else, #elif
or #endif directive is encountered (depending on the context).
If one of these excluded directives is badly formed, it may be ignored
without warning by a compiler with unfortunate consequences.
The requirement of this rule is that all preprocessor directives shall be
syntactically valid even when they occur within an excluded block of code.
Compilers are not always consistent in enforcing this ISO requirement."
BENEFITS
Rule prevents erroneous behaviour.
EXAMPLE
#define MAX 2
int foo(void)
{
int x = 0;
#ifndef MAX
x = 1;
#else1
x = MAX;
#endif
return x;
}
REPAIR
#define MAX 2
int foo(void)
{
int x = 0;
/* Violation */
#ifndef MAX
x = 1;
#else
x = MAX;
#endif
return x;
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-0-8
The defined preprocessor operator shall only be used in one of the two standard forms
[MISRA2008-16_1_1-3]
DESCRIPTION
"The only two permissible forms for the defined preprocessor operator are:
- defined ( identifier )
- defined identifier
Any other form leads to undefined behaviour.
Generation of the token defined during expansion of a #if or #elif
preprocessing directive also leads to undefined behaviour and shall be
avoided,"
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#if defined X > Y
#endif
#define DEFINED defined
#if DEFINED(X)
#endif
// Violation
// Violation
REPAIR
#if defined X
#endif
#if defined (X)
#endif
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-1-1
All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if or
#ifdef directive to which they are related [MISRA2008-16_1_2-3]
DESCRIPTION
"When the inclusion and exclusion of blocks of statements is controlled
by a series of preprocessor directives, confusion can arise
if all of the relevant directives do not occur within one file."
This rule requires that the number of preprocessor directives
#if/ifdef/ifndef
matches the number of #endif directives in the file.
BENEFITS
Rule improves good code structure and
prevents maintenance problems.
EXAMPLE
/* Violation */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"
REPAIR
/* OK */
#define A
#ifdef A
#include "file1.h"
#endif
#if 1
#include "file2.h"
#endif
REFERENCES
EXCEPTIONS
Macros are almost never necessary in C++. Exceptions to this rule are:
- #ifdef
- #ifndef
- #if
- #if defined
when used as include guards and for conditional compilation.
BENEFITS
Improves code reliability and maintainability.
EXAMPLE
#define PI 3.14
// Violation
REPAIR
const double PI = 3.14; // OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
The #ifndef and #endif pre-processor directives will only be used to prevent multiple
inclusions of the same header file [MISRA2008-16_2_1_b-3]
DESCRIPTION
The #ifndef and #endif pre-processor directives will only be used
as defined in below example to prevent multiple inclusions of the
same header file.
#ifndef Header_filename
#define Header_filename
// Header declarations...
#endif
SINCE
v7.1
BENEFITS
Conditional code compilation should be kept to a minimum as it can
significantly obscure testing and maintenance efforts.
EXAMPLE
#ifndef MAX
// Violation
// Violation
int a;
REPAIR
#ifndef FOO_H
#define FOO_H
int max = 10;
int a;
// OK
#endif
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 28
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
The following pre-processor directives shall not be used: #if, #elif, #else, #ifdef, #undef,
#pragma [MISRA2008-16_2_1_c-3]
DESCRIPTION
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include
SINCE
v7.1
BENEFITS
Limit the use of the pre-processor to those cases where it is necessary.
EXAMPLE
#pragma once // Violation
REPAIR
#ifndef FOO_H
#define FOO_H
/* ... */
#endif
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 26
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
C++ macros shall only be used for: include guards, type qualifiers, or storage class specifiers
[MISRA2008-16_2_2-3]
DESCRIPTION
"C++ macros shall only be used for include guards, type qualifiers, or
storage
class specifiers. These are the only permitted uses of macros. C++ offers
const variable and function templates, which provide a type-safe
alternative
to the preprocessor."
SINCE
v7.2
NOTES
List of type qualifiers and storage class specifiers:
// type qualifiers:
const
volatile
// storage class specifiers:
auto
register
static
extern
mutable
BENEFITS
Improves code reliability and maintainability.
EXAMPLE
#define PI 3.14
REPAIR
// Violation
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-2
BENEFITS
Rule improves maintainability and optimization of code.
EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present
REPAIR
// file foo.hh
// OK
#ifndef FOO_HH
#define FOO_HH
int i;
#endif
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 27
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-3
The ', ", /* or // characters shall not occur in a header file name [MISRA2008-16_2_4-3]
DESCRIPTION
"It is undefined behaviour if the ', ", /* or // characters are used
between < and > delimiters or the ', /* or // characters are used
between the " delimiters in a header name preprocessing token."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include "fi'le.h" // Violation
REPAIR
#include "file.h"
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-4
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include "fi\\le.h" // Violation
REPAIR
#include "file.h"
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-5
There shall be at most one occurrence of the # or ## operators in a single macro definition
[MISRA2008-16_3_1-3]
DESCRIPTION
"There is an issue of unspecified order of evaluation associated
with the # and ## preprocessor operators.
To avoid this problem only one occurrence of either operator
shall be used in any single macro definition
(i.e. one #, or one ## or neither)."
BENEFITS
Rule improves readability and clarity of code.
EXAMPLE
#define TEST1(A,B,C) A # B # C
#define TEST2(A,B,C) A ## B # C
#define TEST3(A,B,C) A ## B ## C
/* Violation */
/* Violation */
/* Violation */
REPAIR
#define TESTa(A,B) A # B
#define TESTb(A,B) A ## B
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. Origin: Misra Guidelines - Rule 98
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-1
BENEFITS
Rule prevents inconsistent implementation of # and ## operators.
EXAMPLE
#define stringer( x ) printf( #x "\n" ) /* Violation */
REPAIR
Do not use # and ## preprocessor operators.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 19
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-3-2
BENEFITS
Provides readability and maintainability.
EXAMPLE
#pragma TEST
/* Violation */
/* Violation */
*/
#pragma TEST
/* Violation */
REPAIR
// OK
#pragma TEST
/* OK */
#pragma TEST
/* OK - multiline comment
*/
#pragma TEST
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 3
2. Origin: Misra Guidelines - Rule 99
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-6-1
Reserved identifiers, macros and functions in the standard library shall not be defined,
redefined or undefined [MISRA2008-17_0_1_a-3]
DESCRIPTION
"It is generally bad practice to #undef a macro which is defined in the
standard library. It is also bad practice to #define a macro name which
is a C reserved identifier or C keyword which is the name of any macro,
object or function in the standard library.
For example, there are some specific reserved words and function names
which are known to give rise to undefined behaviour if they are redefined
or
undefined, including defined, _ _LINE_ _, _ _FILE_ _, _ _DATE_ _, _ _TIME_
_,
_ _STDC_ _, errno and assert. Generally, all identifiers that begin with
the underscore character are reserved."
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#define __A 1
// Violation
#define assert 1
// Violation
#undef __AA
// Violation
#undef assert
// Violation
REPAIR
Do not #define or #undef reserved identifiers
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1
Reserved identifiers, macros and functions in the standard library shall not be defined,
redefined or undefined [MISRA2008-17_0_1_b-3]
DESCRIPTION
"It is generally bad practice to #undef or #define names which are C
reserved words"
BENEFITS
Redefinition of reserved words can lead to errors and confusion.
EXAMPLE
#define break 1
#define continue 1
#undef while
#undef return
//
//
//
//
Violation
Violation
Violation
Violation
REPAIR
Do not #define or #undef reserved words
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-1
The names of standard library macros and objects shall not be reused [MISRA2008-17_0_2-3]
DESCRIPTION
"Where the developer uses new versions of standard library macros or
objects
(e.g. to enhance functionality or add checks of input values), the
modified
macro or object shall have a new name.
This is to avoid any confusion as to whether a standard macro or object,
or a modified version of them, is being used."
Rule checks if the following reserved names are used:
- macro and typedef names from C standard library headers: assert.h,
complex.h, ctype.h, errno.h, float.h, iso646.h, limits.h, locale.h,
math.h,
setjmp.h, signal.h, stdarg.h, stddef.h, stdio.h, stdlib.h, string.h,
time.h,
wchar.h, wctype.h, stdint.h, inttypes.h, fenv.h, stdbool.h, tgmath.h
- identifiers that begin with the underscore character
See also: NAMING-33, MISRA2004-20_2, CODSTA-93
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#define NULL ( a > b )
#define _NULL ( a > b )
// Violation
// Violation
REPAIR
#define MY_NULL ( a > b ) // OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-2
BENEFITS
Rule prevents undefined behaviour.
DRAWBACKS
It is not possible in static analysis to check if the functionality is
consistent
with those of the original. So, rule reports violations on all declared
functions
which names are reserved. The user should himself check if the modified
function
has the same functionality and could overload a function from standard
library.
Rule also does not have exception that permits overloading functions with
// Violation
REPAIR
int my_printf ( int a, int b )
{
return ( ( a > b ) ? a : b );
}
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 17, Rule 17-0-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The setjmp macro and the longjmp function shall not be used [MISRA2008-17_0_5-3]
DESCRIPTION
"setjmp and longjmp allow the normal function call mechanisms to be
bypassed,
and shall not be used."
Rule reports a violation message if setjmp or longjmp is used and the file
includes any of the following headers: setjmp.h, setjmp, or csetjmp.
BENEFITS
Rule prevents normal function call mechanisms from being bypassed.
EXAMPLE
#include <setjmp.h>
jmp_buf mark;
int
fperr;
void foo( void ) {
int jmpret;
jmpret = setjmp( mark );
}
/* Violation */
REPAIR
Do not use the setjmp macro and the longjmp function.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 122
SINCE
v7.2
BENEFITS
Rule prevents undefined and implementation-defined behaviour.
EXAMPLE
#include <stdio.h> // Violation
REPAIR
#include <cstdio>
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The library functions atof, atoi and atol from library <cstdlib> shall not be used [MISRA200818_0_2-3]
DESCRIPTION
'atof', 'atoi' and 'atol' functions from library <stdlib.h> have undefined
behaviour associated with them when the string cannot be converted.
BENEFITS
Prevents using functions which have sometimes undefined behaviour.
EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *s; double x; int i; long l;
s = " -2309.12E-15";
x = atof( s );
/* Violation */
s = " -9885 pigs";
i = atoi( s );
/* Violation */
s = "98854 dollars";
l = atol( s );
/* Violation */
}
REPAIR
Do not use atof, atoi and atol functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 125
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 23
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-2
The library functions abort, exit, getenv and system from library <cstdlib> shall not be used
[MISRA2008-18_0_3-3]
DESCRIPTION
'abort', 'exit', 'getenv' and 'system' functions from stdlib.h, cstdlib,
or stdlib_iso.h libraries shall not be used.
BENEFITS
Prevents using functions which are not required in an embedded system.
EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *libvar;
libvar = getenv( "LIB" );
system( "dir" );
abort( );
exit( 0 );
}
/*
/*
/*
/*
Violation
Violation
Violation
Violation
*/
*/
*/
*/
REPAIR
Do not use abort, exit, getenv and system functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 126
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 24
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-0-3
The time handling functions of library <ctime> shall not be used [MISRA2008-18_0_4-3]
DESCRIPTION
"This library is associated with clock times.
Various aspects are implementation dependent
or unspecified, such as the formats of times."
Rule prevents inclusion of <time.h> and <ctime> headers.
See also: SECURITY-01
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include <time.h>
/* Violation */
REPAIR
Do not include time.h header.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 127
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 25
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 18, Section 7, Rule 18-0-4
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strcpy ( array, pChar ); // Violation
}
REPAIR
/* Ideally, a safe string handling library should be used.
Use of bounded functions (e.g. strncpy) is also possible. */
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strncpy ( array, pChar, 10 ); // OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
// Violation - The macro offsetof shall not be used. Macro is in line:
[10]
#include <stddef.h>
struct S {
int x, y, z;
char buffer[ 128 ];
};
int main( ) {
int i = offsetof( struct S, buffer );
return 0;
}
REPAIR
Do not use offsetof.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
EXCEPTIONS
The rule allows to use a placement new.
BENEFITS
"There is a range of unspecified,
behaviour associated with dynamic
of
other potential pitfalls. Dynamic
memory
leaks, data inconsistency, memory
behaviour."
EXAMPLE
void foo()
{
int * p = new int[10]; // Violation
/* ... */
delete[] p;
// Violation
REPAIR
Do not use neither 'new' and 'delete' operators nor 'calloc', 'malloc',
'realloc' and 'free' functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Misra Guidelines - Rule 118
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-4-1
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.26 Memory Allocation, AV Rule 206
5. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 3
BENEFITS
Prevents from problems associated with implementation-defined
and undefined behaviour in signal handling.
EXAMPLE
#include <signal.h>
/* Violation */
REPAIR
Do not use <signal.h> header.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 123
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 21
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 18, Rule 18-7-1
BENEFITS
The rule prevents undefined behaviours.
EXAMPLE
#include <errno.h>
int err_check( ) {
errno = 1;
return (errno);
}
/* Violation */
/* Violation */
REPAIR
Do not use errno.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 119
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 17
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 19, Rule 19-3-1
BENEFITS
Prevents form problems associated with a large number of unspecified,
undefined and implementation-defined behaviour associated
with streams and file I/O.
EXAMPLE
#include <stdio.h>
/* Violation */
REPAIR
Do not use <stdio.h> library.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 20
2. Origin: Misra Guidelines - Rule 124
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.5 Libraries, AV Rule 22
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 27, Rule 27-0-1
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
typedef int id1_uint32; // Violation - interchange Z and 2
short id1_uint3Z;
// Violation - interchange Z and 2
void id2_foo(
void id2_foo_(){
// Violation - presence underscore
int id5_BO;
// Violation - interchange B and 8, O and 0
int id5_80;
// Violation - interchange B and 8, O and 0
int id6_modem; // Violation - interchange rn and m
}
REPAIR
typedef int id1_uint32_t; // OK
int id1_uint32_v;
// OK
void id2_foo_1(
// OK
int id4_param1, // OK
int id4_param2
// OK
){
int id3_abc_1; // OK
int id3_ABC_2; // OK
}
int id6_modern;
// OK
void id2_foo_2(){ // OK
int id5_BO_1; // OK
int id5_80_2; // OK
int foo_2_id6_modem; // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-10-1
Identifiers declared in an inner scope shall not hide an identifier declared in an outer scope
[MISRA2008-2_10_2_a-3]
DESCRIPTION
Do not hide names of global variables and parameters.
BENEFITS
Hiding names of global variables or parameters
can lead to errors and confusion.
EXAMPLE
int x;
void foo( ) {
int x;
/* Violation */
x = 3;
}
REPAIR
Avoid hiding names of global variables and parameters.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4
Identifiers declared in an inner scope shall not hide an identifier declared in an outer scope
[MISRA2008-2_10_2_b-3]
DESCRIPTION
Do not hide names of local variables.
BENEFITS
Hiding names of local variables can lead to errors and confusion.
EXAMPLE
int foo( ) {
int a;
{
int a;
}
}
/* Violation */
REPAIR
Avoid hiding names of local variables.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 21
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.15 Declarations and Definitions, AV Rule 135
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-2
5. ISO/DIS 26262
point 8.4.4
A class, union or enum name (including qualification, if any) shall be a unique identifier
[MISRA2008-2_10_4_a-3]
DESCRIPTION
"No tag name shall be reused for any other purpose within the program.
ISO 9899:1990 does not define the behaviour when an aggregate declaration
uses a tag in different forms of type specifier."
BENEFITS
Reuse of tag names can lead to errors and confusion.
EXAMPLE
struct stag { int a; };
void stag(void){}
// Violation
REPAIR
struct stag { int a; };
void foo(void){}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4
A class, union or enum name (including qualification, if any) shall be a unique identifier
[MISRA2008-2_10_4_b-3]
DESCRIPTION
"No tag name shall be reused to define a different tag.
ISO 9899:1990 does not define the behaviour when an aggregate declaration
uses
a tag in different forms of type specifier. Either all uses of the tag
should
be in structure type specifiers, or all uses should be in union type
specifiers"
BENEFITS
Reuse of tag names can lead to errors and confusion.
EXAMPLE
struct stag { int a; int b; };
void foo1()
{
union stag
}
void foo2(void)
{
struct stag { int a; };
}
// Violation
REPAIR
struct stag { int a; int b; };
void foo1()
{
union union_tag
}
void foo2(void)
{ int a; float b; }; // OK
{
struct new_stag { int a; };
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-4
The identifier name of a non-member object or function with static storage duration should
not be reused [MISRA2008-2_10_5_a-4]
DESCRIPTION
Static object or function identifier shall not be reused for any other
purpose within the program.
BENEFITS
Reuse of static identifiers can lead to errors and confusion.
EXAMPLE
static float a;
static void foo()
{
int a;
/* Violation */
int foo; /* Violation */
}
REPAIR
Do not use static identifiers for any other purpose within the program.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4
The identifier name of a non-member object or function with static storage duration should
not be reused [MISRA2008-2_10_5_b-4]
DESCRIPTION
Object or function identifier with static storage duration should be
unique.
BENEFITS
Reuse of identifier names can lead to errors and confusion.
EXAMPLE
static
static
{
static
static
}
float a;
void foo()
int a ; /* Violation */
int foo; /* Violation */
REPAIR
Do not use the same names for different static object or functions.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-5
3. ISO/DIS 26262
point 8.4.4
If an identifier refers to a type, it shall not also refer to an object or a function in the same
scope [MISRA2008-2_10_6-3]
DESCRIPTION
"ISO C defines a number of different name spaces. It is technically
possible to use the same name in separate name spaces to represent
completely different items. However this practice is deprecated because
of the confusion it can cause, and so names should not be reused, even
in separate name spaces."
There are four namespaces in the C Language
1. Label names
2. Tags of structure, unions and enumerations
3. Members of structs and unions; each struct/union as a separate
namespace
4. All other identifiers; e.g. enum constants, variables, functions,
typedefs
NOTES
The output message shows only the first place (line) where the same
name is used in the other name space.
EXCEPTIONS
"An exception to this rule is the naming of members of structures,
where members names may be reused within separate structures."
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
typedef struct MyStruct // tags name space
{
int Member;
// members name space
} MyStruct;
// Violation - identifiers name space
REPAIR
typedef struct MyStruct
{
int Member;
} MyStructObj;
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 5
2. Origin: Misra Guidelines - Rule 12
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-10-6
Only those escape sequences that are defined in ISO/IEC 14882:2003 shall be used
[MISRA2008-2_13_1-3]
DESCRIPTION
"Only those escape sequences that are defined in ISO/IEC 14882:2003
shall be used. The defined escape sequences (ISO/IEC 14882:2003) are:
\n, \t, \v, \b, \r, \f, \a, \\, \?, \', \", \<Octal Number>,
\x<Hexadecimal Number>"
SINCE
v7.2
BENEFITS
The use of an undefined escape sequence leads to undefined behaviour.
EXAMPLE
#include <stdio.h>
void foo( ) {
printf("ABCD\u1111");
printf("abcd\hgf");
printf("\k");
}
// Violation
// Violation
// Violation
REPAIR
Do not use escape sequences not defined in the ISO/IEC 14882:2003
standard.
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-1
2. General Principles of Software Validation;
Octal constants (other than zero) and octal escape sequences (other than "\0") shall not be
used [MISRA2008-2_13_2-3]
DESCRIPTION
"Any integer constant beginning with a '0' (zero) is treated as octal.
So there is a danger, for example, with writing fixed length constants.
Octal escape sequences can be problematic because the inadvertent
introduction of a decimal digit ends the octal escape and introduces
another character. It is better not to use octal constants or escape
sequences at all and to statically check for any occurrences.
The integer constant zero (written as a single numeric digit) is, strictly
speaking, an octal constant, but is a permitted exception to this rule.
Additionally \0 is the only permitted octal escape sequence."
EXCEPTIONS
Rule ignores any #pragma parasoft / codewizard directives.
Rule ignores any values inside asm blocks.
BENEFITS
Rule increases readability and maintainability.
Rule prevents using implementation-defined values.
EXAMPLE
void foo()
{
int code1;
int code2;
int code3;
code1 = 052;
/* Violation */
code2 = 071;
/* Violation */
code3 = '\100'; /* Violation */
}
REPAIR
void foo1()
{
int code1;
int code2;
int code3;
code1 = 42;
code2 = 57;
code3 = 64;
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 7
2. Origin: Misra Guidelines - Rule 19
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 149
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-2
A "U" suffix shall be applied to all octal or hexadecimal integer literals of unsigned type
[MISRA2008-2_13_3-3]
DESCRIPTION
"The type of an integer is dependent on a complex combination of factors
including:
- The magnitude of the constant;
- The implemented sizes of the integer types;
- The presence of any suffixes;
- The number base in which the value is expressed.
For example, the value 0x8000 is of type unsigned int in a 16-bit
environment,
but of type (signed) int in a 32-bit environment. If an overload set
includes
candidates for an unsigned int and an int, then the overload that would be
matched by 0x8000 is therefore dependent on the implemented integer size.
Adding a "U" suffix to the value specifies that it is unsigned."
SINCE
v7.2
BENEFITS
Rule improves portability and prevents undefined behaviour.
EXAMPLE
unsigned long var = 02;
// Violation
REPAIR
unsigned long var = 02U; // OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo(long param = 64l) // Violation
{
const long a = 64l; // Violation
}
REPAIR
void foo(long param = 64L) // OK
{
const long a = 64L;
// OK
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-13-4
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
wchar_t array[] = "Hello" L"World";
// Violation
REPAIR
wchar_t array[] = L"Hello" L"World";
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-5
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
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
int a <: 2 :> <: 2 :> = <%<%0,1%>,<%2,3%>%>; // Violation
REPAIR
int a[2][2] = { {0,1}, {2,3} };
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.4 Environment, AV Rule 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-5-1
The character sequence /* shall not be used within a C-style comment [MISRA2008-2_7_1-3]
DESCRIPTION
C does not support the nesting of comments even though
some compilers support this as a language extension.
A comment begins with /* and continues until the first */ is encountered.
Any /* occurring inside a comment is a violation of this rule.
BENEFITS
Nested comments are not supported by C and can lead to confusion.
EXAMPLE
/* some comment, end comment marker accidentally omitted
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is not compliant - Violation */
REPAIR
/* some comment, end comment marker accidentally omitted */
<<New Page>>
Perform_Critical_Safety_Function(X);
/* this comment is compliant - OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 9
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-1
Sections of code shall not be "commented out" using C-style comments [MISRA2008-2_7_2-3]
DESCRIPTION
"Where it is required for sections of source code not to be compiled then
this should be achieved by use of conditional compilation (e.g. #if or
#ifdef constructs with a comment)."
NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.
BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."
EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}
// Violation
REPAIR
void foo()
{
int x = 5;
/* Comment without
// OK
code within */
#if 0
if (x==0){
x++;
}
#endif
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3
Sections of code should not be "commented out" using C++ comments [MISRA2008-2_7_3-4]
DESCRIPTION
"Where it is required for sections of source code not to be compiled then
this should be achieved by use of conditional compilation (e.g. #if or
#ifdef constructs with a comment)."
NOTES
There are situations where rule may report false positive or false
negative.
Such situations are caused by similarity between source code and comment
text.
BENEFITS
"Using start and end comment markers for this purpose is dangerous
because C does not support nested comments, and any comments already
existing in the section of code would change the effect."
EXAMPLE
void foo()
{
int x = 5;
/* Section of code
commented out
if (x==0){
x++;
}
*/
}
// Violation
REPAIR
void foo()
{
int x = 5;
/* Comment without
// OK
code within */
#if 0
if (x==0){
x++;
}
#endif
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Origin: Misra Guidelines - Rule 10
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.14 Comments, AV Rule 127
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-2
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 2, Rule 2-7-3
It shall be possible to include any header file in multiple translation units without violating the
One Definition Rule [MISRA2008-3_1_1-3]
DESCRIPTION
"Header files should be used to declare objects, functions, inline
functions,
function templates, typedefs, macros, classes, and class templates and
shall
not contain or produce definitions of objects or functions (or fragment of
functions or objects) that occupy storage."
See also: MISRA2004-8_5
NOTES
As a headers rule detects files with extensions ".h", ".hh", ".hxx", ".i"
(e.g. "file.h", "file.hh", "file.hxx", "file.i").
EXCEPTIONS
The following definitions are allowed in a header file:
- inline functions
- function templates
- static data members of class templates
- const variables if they have internal or no linkage (C++ mode)
- static const variables
BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.
EXAMPLE
/* file.h */
void f1(){}
int var;
class C {
void f2();
// Violation
// Violation
};
void C::f2() {}
// Violation
/* file.cpp */
#include "file.h"
REPAIR
/* file.h */
void f1();
extern int var;
class C {
void f2();
};
template <typename T>
void f3 ( T ) { }
// OK
// OK
// OK
/* file.cpp */
#include "file.h"
void f1(){}
int var;
void C::f2() {}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-1
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 61
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 39
BENEFITS
Rule prevents undefined behaviour and improves readability.
EXAMPLE
void foo1( ) {
void foo2( );
}
/* Violation */
REPAIR
void foo2( );
void foo1( ) {
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. Origin: Misra Guidelines - Rule 68
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 107
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-2
When an array is declared, its size shall either be stated explicitly or defined implicitly by
initialization [MISRA2008-3_1_3-3]
DESCRIPTION
"When an array is declared with external linkage, its size shall be stated
explicitly or defined implicitly by initialisation.
Although it is possible to declare an array of incomplete type and access
its elements, it is safer to do so when the size of the array may be
explicitly determined."
BENEFITS
Rule prevents undefined behaviour and improves safety of code.
EXAMPLE
extern int array2[ ]; /* Violation */
extern int array1[ ]; /* Violation */
REPAIR
int array2[ ] = { 0, 10, 15 };
extern int array1[ 10 ];
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 8
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-3
Objects or functions with external linkage shall be declared in a header file [MISRA20083_3_1-3]
DESCRIPTION
"Placing the declarations of objects and functions with external linkage
in a header file documents that they are intended to be accessible from
other
translation units. If external linkage is not required, then the object or
function shall either be declared in an unnamed namespace or declared
static."
SINCE
v7.2
EXCEPTIONS
This rule does not apply to main, or to members of unnamed namespaces.
BENEFITS
Rule reduce the visibility of objects and functions.
EXAMPLE
// file.cpp
int a1 = 0;
void fun(){}
// Violation
// Violation
REPAIR
// file.h
extern int a1;
extern void fun();
// file.cpp
#include "file.h"
int a1 = 0;
// OK
// OK
// OK
void fun(){}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-3-1
If a function has internal linkage then all re-declarations shall include the static storage class
specifier [MISRA2008-3_3_2-3]
DESCRIPTION
"If the declaration of a function includes the static storage class
specifier,
then it has internal linkage. A re-declaration of such a function is not
required to have the static keyword, but it will still have internal
linkage.
However, this is implicit and may not be obvious to a developer. It is
therefore
good practice to apply the static keyword consistently so that the linkage
is explicitly stated."
See also: MISRA2004-8_11
SINCE
v7.2
BENEFITS
Rule improves good programming style and readability.
EXAMPLE
static void f1 ( );
void f1 ( ) { }
// Violation
REPAIR
static void f1 ( );
static void f1 ( ) { }
// OK
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-3-2
An identifier declared to be an object or type shall be defined in a block that minimizes its
visibility [MISRA2008-3_4_1-3]
DESCRIPTION
"A variable ought to be declared with the smallest possible scope to
improve
the readability of the code and so that variables are not unnecessarily
allocated. When a variable that is declared at the beginning of a function
is
used somewhere in the code, it is not easy to directly see the type of
the variable.
In addition, there is a risk that such a variable is inadvertently hidden
if a local variable, having the same name, is declared in an internal
block.
Many local variables are only used in special cases which seldom occur.
If a variable is declared at the outer level,
memory will be allocated even if it is not used. In addition, when
variables
are initialized upon declaration, more efficient code is obtained than if
values are assigned when the variable is used."
BENEFITS
Rule prevents from making the program harder to understand and maintain.
EXAMPLE
void foo( ) {
int a;
{
a = 0;
}
}
// Violation
REPAIR
void foo( ) {
{
int a;
// OK
a = 0;
}
}
void fooOK1(){
int b;
if (b > 0) {
b = 10;
}
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 18
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-4-1
4. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 6
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The types used for an object, a function return type, or a function parameter shall be tokenfor-token identical in all declarations and re-declarations [MISRA2008-3_9_1-3]
DESCRIPTION
"If a re-declaration has compatible types but not types which are
token-for-token identical, it may not be clear to which declaration
that re-declaration refers."
SINCE
v7.2
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
typedef int INT;
INT i;
extern int i;
// Violation
REPAIR
typedef int INT;
INT i;
extern INT i;
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 3, Rule 3-9-1
typedefs that indicate size and signedness should be used in place of the basic numerical
types [MISRA2008-3_9_2-4]
DESCRIPTION
"The storage length of types can vary from compiler to compiler. It is
safer
if programmers work with types which they know to be of a given length."
Rule reports a violation message if basic numerical type is used
(e.g. signed char) or typedef name does not contain any digits
indicating the size (e.g. my_int).
See also: MISRA2004-6_3
EXCEPTIONS
Rule does not report a violation for:
- "main" function return type
- extern variable declaration
- boolean and enum types
- bit-field types.
- typedef name which starts with 'bool' prefix, or is a typedef for plain
char
(even if it does not contain any digits)
BENEFITS
"Rule helps to clarify the size of the storage, but does not guarantee
portability because of the asymmetric behaviour of integral promotion."
EXAMPLE
typedef signed int my_int; /* Violation - no digits */
static signed char a;
/* Violation - not typedef */
short int foo(
char* p_char,
float& r_float)
{
double h;
const int z = 1;
return 1;
REPAIR
/* Exceptions: */
typedef char char_t;
typedef unsigned char BOOL;
prefix */
struct STRUCT {
unsigned int i:2;
};
bool b;
enum ENUM { EV };
extern signed char a;
int main() { return 0; }
/* Correct use of typedef: */
typedef signed int my_int32;
typedef signed char int8_t;
typedef short int s16_t;
typedef float& float32ref;
typedef double float64;
typedef const int cs32_t;
s16_t foo(
char_t* p_char,
float32ref r_float)
{
float64 h;
cs32_t z = 1;
return 1;
}
/* OK (plain char) */
/* OK (typedef name starts with 'bool'
/* OK (bit-bield type) */
/*
/*
/*
/*
OK
OK
OK
OK
(boolean type) */
(enum type) */
(extern variable) */
("main" return type) */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
/* OK */
REFERENCES
1. Misra Guidelines - Rule 13
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-9-2
The underlying bit representations of floating-point values shall not be used [MISRA20083_9_3-3]
DESCRIPTION
"The storage layout used for floating-point values may vary from one
compiler to
another, and therefore no floating-point manipulations shall be made which
rely
directly on the way the values are stored. The in-built operators and
functions,
which hide the storage details from the programmer, should be used."
NOTES
In many cases floating point bit fields will be flagged as syntax errors.
BENEFITS
Prevents implementation-defined behaviour.
EXAMPLE
struct S {
float f:6; // Violation
};
union U {
float f:6; // Violation
};
REPAIR
struct S {
int f:6; // OK
};
union U {
int f:6; // OK
};
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 3-9-3
SINCE
v7.2
BENEFITS
"As a result of this rule, NULL is considered to have pointer type."
EXAMPLE
#include <cstddef>
void f1( int );
void foo( )
{
f1( NULL ); // Violation
}
REPAIR
void f1( int );
void foo( )
{
f1( 0 ); // OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
"As a result of this rule, NULL is considered to have pointer type."
EXAMPLE
#include <cstddef>
void f1( int* );
void foo( )
{
f1( 0 ); // Violation
}
REPAIR
#include <cstddef>
void f1( int* );
void foo( )
{
f1( NULL ); // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-10-2
Expressions with type bool shall not be used as operands to built-in operators other than the
assignment operator =, the logical operators &&, ||, !, the equality operators == and !=, the
unary & operator, and the conditional operator [MISRA2008-4_5_1-3]
DESCRIPTION
"Expressions that are effectively Boolean should not be used as operands
to operators other than (&&, ||, !, =, ==, !=, ?:).
An 'effectively Boolean' expression which is either 'Boolean-by-construct'
or 'Boolean-by-enforcement' as defined below.
Boolean-by-construct values are produced by the following operators:
- equality operators (== and !=)
- logical operators (!, && and ||)
- relational operators (<, >, <= and >=)
Boolean-by-enforcement values can be introduced by implementing a specific
type
enforcement mechanism using a tool. A Boolean type could be associated
with
a specific typedef, and would then be used for any objects that are
Boolean."
Rule reports violation if as an operand of operator
other than (&&, ||, !, =, ==, !=, ?:) is used:
- Boolean-by-construct values
- boolean constant
- variable, parameter or expression of type:
- bool,
- typedef to bool,
- enum that name begins with 'bool' (ignoring case)
and that contains exactly 2 enum constant in body
- typedef to char/short/int/enum which name begins with 'bool' (ignoring
case)
- reference to above types
BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.
EXAMPLE
int goo();
void foo()
{
int x, y, z;
z = (x > y) & (goo()); // Violation
z = x | (goo() != 0); // Violation
z = ~(x == y);
// Violation
}
REPAIR
int goo();
void foo()
{
int x, y, z;
int tmp;
tmp = x > y;
z = tmp & goo();
// OK
tmp = goo() != 0;
z = x | tmp;
// OK
tmp = x == y;
z = ~tmp;
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 36
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 4, Rule 4-5-1
Expressions with type enum shall not be used as operands to built-in operators other than [ ],
=, ==, !=, <, <=, >, >=, and the unary & operator [MISRA2008-4_5_2-3]
DESCRIPTION
"Expressions with type enum shall not be used as operands to built-in
operators other than the subscript operator [ ], the assignment operator
=,
the equality operators == and !=, the unary & operator, and the relational
operators <, <=, >, >=."
SINCE
v7.2
BENEFITS
"Enumerations have implementation-defined representation
and so should not be used in arithmetic contexts."
EXAMPLE
/* Examples of incorrect code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 + COLOUR_1 ) == colour ){} // Violation
}
REPAIR
/* Examples of correct code */
enum { COLOUR_0, COLOUR_1, COLOUR_2, COLOUR_3, COLOUR_COUNT } colour;
void foo()
{
if ( ( COLOUR_0 < colour) && (COLOUR_3 > colour ) ){} // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-2
Expressions with type (plain) char and wchar_t shall not be used as operands to built-in
operators other than the assignment operator =, the equality operators == and !=, and the
unary & operator [MISRA2008-4_5_3-3]
DESCRIPTION
"Expressions with type (plain) char and wchar_t shall not be used as
operands
to built-in operators other than the assignment operator =, the equality
operators == and !=, and the unary & operator."
SINCE
v7.2
EXCEPTIONS
Exceptionally, the following operators may be used if the associated
restriction is observed:
- The binary + operator may be used to add an integral
value in the range 0 to 9 to 0;
- The binary operator may be used to subtract character 0;
- The relational operators <, <=, >, >= may be used to determine
if a character (or wide character) represents a digit.
(Rule does not report a violation if a character constant is compared
with a variable of type plain char)
BENEFITS
"Manipulation of character data may generate results that are contrary
to developer expectations."
EXAMPLE
void foo()
{
char ch = 't';
// OK
if ( ( ch >= 'a' ) && ( ch <= 'z' ) ) // Violation
{
//...
}
}
REPAIR
void foo()
{
char ch = 't';
// OK
if ( ch == 't' ) // OK
{
//...
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 4, Rule 4-5-3
If the bitwise operators ~ and << are applied to an operand with an underlying type of
unsigned char or unsigned short, the result shall be immediately cast to the underlying type of
the operand [MISRA2008-5_0_10-3]
DESCRIPTION
"When these operators (~ and <<) are applied to small integer types
(unsigned char or unsigned short),
the operations are preceded by integral promotion,
and the result may contain high order bits which have not been
anticipated.
A similar problem exists when the << operator is used on small integer
types
and high order bits are retained."
BENEFITS
Rule prevents high order bits retaining.
EXAMPLE
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = (~port) >> 4;
*/
result_16 = ((port << 4) & mode) >> 6;
*/
}
REPAIR
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
/* Violation
/* Violation
void foo()
{
uint8_t port = 0x5aU;
uint8_t result_8;
uint16_t result_16;
uint16_t mode;
result_8 = ((uint8_t)(~port)) >> 4 ;
result_16 = (
(uint16_t) (~(uint16_t)port)
) >> 4 ;
result_16 = ((uint16_t)((uint16_t)port << 4) & mode) >> 6;
}
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-10
The plain char type shall only be used for the storage and use of character values
[MISRA2008-5_0_11-3]
DESCRIPTION
"The plain char type shall be used only for the storage and use of
character values.
The only permissible operators on plain char types are assignment
and equality operators (=, ==, != )"
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
char a = 65;
/* Violation */
void foo( ) {
a = 66;
/* Violation */
a++;
/* Violation */
if (a < 67) /* Violation */
{
}
}
REPAIR
char a = 'A';
/* OK */
void foo( ) {
a = 'B';
/* OK */
if (a == 'C') /* OK */
{
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-11
signed char and unsigned char type shall only be used for the storage and use of numeric
values [MISRA2008-5_0_12-3]
DESCRIPTION
signed and unsigned char type shall be used only for the storage
and use of numeric values. The signedness of the plain char type is
implementation-defined and should not be relied upon.
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
signed char a = 'A';
void foo( ) {
unsigned char a = 'B';
if (a == 'C')
{
}
if (a < 'D')
{
}
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
signed char a = 65;
void foo( ) {
unsigned char a = 66;
if (a == 67)
{
}
if (a < 68)
{
}
}
/* OK */
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 6
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-12
The condition of an if-statement and the condition of an iteration-statement shall have type
bool [MISRA2008-5_0_13-3]
DESCRIPTION
"If an expression with type other than bool is used in the condition
of an if-statement or iteration statement, then its result will be
implicitly converted to bool."
SINCE
v7.2
NOTES
Rule does not report violations if the condition expression is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.
EXCEPTIONS
"A condition of the form type-specifier-seq declarator is not required
to have type bool."
BENEFITS
"The condition expression shall contain an explicit test (yielding a
result
of type bool) in order to clarify the intentions of the developer."
EXAMPLE
void foo()
{
int i;
if (i){} // Violation
}
REPAIR
void foo()
{
int i;
if (i != 0){} // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-13
SINCE
v7.2
BENEFITS
"The first operand shall contain an explicit test (yielding a result of
type
bool) in order to clarify the intentions of the developer."
EXAMPLE
void foo(int i, int j, int k, int l)
{
i = j ? k : l;
// Violation
}
REPAIR
void foo(int i, int j, int k, int l)
{
i = (j != 0) ? k : l;
// OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-14
DRAWBACKS
For more complex code rule may not be able to check if there is indexed
pointer
which points to array. For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10];
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
=
=
=
=
=
a;
p1;
p2;
p3;
p4;
p1[0]
p2[0]
p3[0]
p4[0]
p5[0]
=
=
=
=
=
0;
0;
0;
0;
0;
//
//
//
//
//
OK
OK
OK
Violation - false positive
Violation - false positive
EXAMPLE
void my_fn(int * p1, int p2[]) {
int index = 0;
int * p3;
int * p4;
*p1 = 0;
p1 ++;
/* Violation
p1 = p1 + 5; /* Violation
p1[5] = 0;
/* Violation
p3 = &p1[5]; /* Violation
p2[0] = 0;
index ++;
index = index + 5;
p2[index] = 0; /* OK */
p4 = &p2[5];
/* OK */
pointer increment */
pointer increment */
p1 was not declared as an array */
p1 was not declared as an array */
}
void foo() {
int a1[16];
int a2[16];
int a[10];
int * p;
my_fn(a1, a2);
my_fn(&a1[4], &a2[4]);
p = a;
*(p+5) = 0; /* Violation */
p[5] = 0;
/* OK */
}
REPAIR
Do not increment/decrement pointers that does not point to an array
Do not apply array indexing to pointers that does not point to array
elements.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-15
Subtraction between pointers shall only be applied to pointers that address elements of the
same array [MISRA2008-5_0_17-3]
DESCRIPTION
"Subtraction of pointers only gives well-defined results if the two
pointers
point (or at least behave as if they point) into the same array object."
Drawbacks: For more complex code rule may not be able to check if there is
applied pointer arithmetic to pointers that address an array or array
element.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
=
=
=
=
=
a; i
p1;i
p2;i
p3;i
p4;i
=
=
=
=
=
p1
p2
p3
p4
p5
a;
a;
a;
a;
a;
//
//
//
//
//
OK
OK
OK
Violation - false positive
Violation - false positive
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 - p2;
i = p2 - a;
i = p3 - a;
}
// Violation
// Violation
// OK
REPAIR
Do not apply pointer subtraction to pointers that address elements
of different arrays.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-17
>, >=, <, <= shall not be applied to objects of pointer type, except where they point to the same
array [MISRA2008-5_0_18-3]
DESCRIPTION
"Attempting to make comparisons between pointers will produce undefined
behaviour."
NOTES
"It is permissible to address the next element beyond the end of an array,
but accessing this element is not allowed."
EXCEPTIONS
"Both operands are of the same type and point to the same array"
BENEFITS
Rule makes the code more readable and less confusing.
DRAWBACKS
For more complex code rule may not be able to check if there is
applied pointer comparison to pointers which point the same array.
For such cases the rule may report false positives.
For example:
void foo( ) {
int a[10], i;
int* p1,* p2,* p3,* p4,* p5;
p1
p2
p3
p4
p5
}
=
=
=
=
=
a; i
p1;i
p2;i
p3;i
p4;i
=
=
=
=
=
p1
p2
p3
p4
p5
<
<
<
<
<
a;
a;
a;
a;
a;
//
//
//
//
//
OK
OK
OK
Violation - false positive
Violation - false positive
EXAMPLE
void foo( int a[] ) {
int* p1 = 0;
int* p2;
int* p3 = a;
int i;
i = p1 < p2;
i = p2 < a;
i = p3 < a;
// Violation
// Violation
// OK
REPAIR
Do not apply pointer comparison to pointers that address elements
of different arrays
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 103
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 171
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-18
The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_a-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int * INTPTR;
struct s {
int *** s3;
};
struct s *** ps3;
int ** (***pfunc3)();
int *** ( **pfunc4)();
void function( int * par1,
int *** par3,
INTPTR * const * const par5
)
{
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4
The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_b-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int* apInt[] ;
apInt* rule12;
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 170
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
4. Origin: Misra Guidelines - Rule 102
5. ISO/DIS 26262
point 8.4.4
The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_c-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
int*** (*rule13)();
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4
The declaration of objects shall contain no more than two levels of pointer indirection
[MISRA2008-5_0_19_d-3]
DESCRIPTION
"Array indexing is the only acceptable form of pointer arithmetic, because
it is
clearer and hence less error prone than pointer manipulation. This rule
bans the
explicit calculation of pointer values. Array indexing shall only be
applied to
objects defined as an array type. Any explicitly calculated pointer value
has
the potential to access unintended or invalid memory addresses. Pointers
may go
out of bounds of arrays or structures, or may even point to effectively
arbitrary locations."
NOTES
Array type with unspecified length is treat as a pointer.
BENEFITS
Rule improves safety of the code.
EXAMPLE
typedef int* INTPTR;
void function(int ** par7[])
{
}
int*** (*xx5[])() = {0};
typedef int INTARR[];
INTARR* (**xx9[])() = {0};
int** rule21[] = {0};
/* Violation */
/* Violation */
/* Violation */
/* Violation */
REPAIR
Do not declare more than two levels of pointer indirection.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-19
3. Origin: Misra Guidelines - Rule 102
4. ISO/DIS 26262
point 8.4.4
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_a-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
As an example of what can go wrong, consider x = b[i] + i++; This will
give
different results depending on whether b[i] is evaluated before i++ or
vice
versa. The problem could be avoided by putting the increment operation
in a separate statement."
The rule reports a violation if a variable is used and
incremented/decremented
in the same statement.
See also: MISRA2004-12_4_a, MISRA2004-12_4_b
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
void foo( )
{
int a, b[10];
a = b[a] + a++; // Violation
}
REPAIR
void foo( )
{
int a, b[10];
a = b[a] + a;
a++;
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_b-3]
DESCRIPTION
The order of evaluation of function arguments is unspecified. This means
that
if arguments contain side effects then the order in which side effects
take
place is unspecified. A function call can give different results depending
on which of the function's arguments is evaluated first.
By side effect we understand accessing a volatile object, modifying an
object
or calling a function that does any of those operations.
Rule checks calls of functions that have at least two arguments.
A violation is reported if
* a volatile object is read or modified, or
* a non-volatile object is modified
during evaluation of a function argument and the same object is read or
modified during evaluation of function's other argument.
EXCEPTIONS
Only one level of function calls is checked.
BENEFITS
Rule prevents writing source code which might produce different results
between compilers.
EXAMPLE
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
Transmogrify(Bump(count),Bump(count)); // Violation
Transmogrify(count++,count);
// Violation
REPAIR
void Transmogrify(int,int);
int Bump(int& x) {return ++x;}
void foo()
{
int count = 5;
int temp1 = Bump(count);
Transmogrify(temp1,Bump(count)); // OK
Transmogrify(count,count);
// OK
count++;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 31
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
5. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_c-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur. Those points in the evaluation of
an
expression at which all previous side effects can be guaranteed to have
taken
place are called sequence points. Sequence points and side effects are
described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].
Note that the order of evaluation problem is not solved by the use of
parentheses, as this is not a precedence issue."
"If a function is called via a function pointer there shall be no
dependence on
the order in which function designator and function arguments are
evaluated.
p->task_start_fn(p++);"
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p++ );
}
// Violation
REPAIR
struct S {
void (*task_start_fn)( struct S* );
};
void foo() {
struct S* p;
p->task_start_fn( p );
p++;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_d-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
Rule reports a violation if in an expression a function is called that
takes as
an argument a pointer or a reference to a non-const variable and modifies
this
variable, and in the same expression the variable is used in some other
way.
NOTES
Rule assumes that a variable is modified in function if it is directly
modified
by assignment or body of function is not defined in current translation
unit.
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
int foo(int* ptr)
{
(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
i = foo(&j) + bar(j);
}
// Violation
REPAIR
int foo(int* ptr)
{
(*ptr)++;
return 0;
}
int bar(int local_param)
{
return local_param;
}
void foo_t(int i, int j)
{
int temp = foo(&j);
i = temp + bar(j);
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_e-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Assignments nested within expressions cause additional side effects. The
best
way to avoid any chance of this leading to a dependence on order of
evaluation
is to not embed assignments within expressions."
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
void foo( int x, int y, int z ) {
x = y = z / 3; // Violation
}
REPAIR
void foo( int x, int y, int z ) {
y = z / 3; // OK
x = y;
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_f-3]
DESCRIPTION
"The volatile type qualifier is provided in C to denote objects whose
value can
change independently of the execution of the program (for example an input
register). If an object of volatile qualified type is accessed this may
change
its value. C compilers will not optimise out reads of a volatile. In
addition,
as far as a C program is concerned, a read of a volatile has a side effect
(changing the value of the volatile). It will usually be necessary to
access
volatile data as part of an expression, which then means there may be
dependence
on order of evaluation. Where possible though it is recommended that
volatiles
only be accessed in simple assignment statements."
The rule reports a violation if in one expression is used more than one
volatile.
See also: MISRA2004-12_2_b
SINCE
v7.0
NOTES
Rule does not report violation if in a function call are used as arguments
more than one volatile. In this case should be used rule MISRA2004-12_2_b.
void goo(int, int);
void foo()
{
volatile int v;
goo(v, v); // Violation - MISRA2004-12_2_b
}
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
void foo( )
{
volatile int x;
int y;
y = x * x; // Violation
}
REPAIR
void foo( )
{
volatile int x;
int y;
y = x;
// OK
y = y * y;
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
The value of an expression shall be the same under any order of evaluation that the standard
permits [MISRA2008-5_0_1_g-3]
DESCRIPTION
"Apart from a few operators (notably the function call operator (), &&,
||, ?:
and , (comma)) the order in which sub-expressions are evaluated is
unspecified
and can vary. This means that no reliance can be placed on the order of
evaluation of sub-expressions, and in particular no reliance can be placed
on
the order in which side effects occur.
Functions may have additional effects when they are called (e.g. modifying
some
global data). Dependence on order of evaluation could be avoided by
invoking the
function prior to the expression that uses it, making use of a temporary
variable for the value."
The rule reports a violation if in one expression are called two functions
that
use the same global or static variable and at least one function modifies
this
variable.
EXCEPTIONS
Only one level of function calls is checked.
BENEFITS
Rule prevents evaluation of expression dependent on compiler version.
EXAMPLE
int global;
int modify_global()
{
global++;
return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global() + use_global();
}
// Violation
REPAIR
int global;
int modify_global()
{
global++;
return global;
}
int use_global()
{
return global;
}
void expr1()
{
int a = modify_global();
a += use_global();
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 46
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-1
Non-constant operands to a binary bitwise operator shall have the same underlying type
[MISRA2008-5_0_20-3]
DESCRIPTION
"Non-constant operands to a binary bitwise operator shall have the same
underlying type. The term 'underlying type' is defined as describing
the type that would be obtained from evaluating an expression if it were
not for the effects of integral promotion."
SINCE
v7.2
BENEFITS
"Using operands of the same underlying type documents that it is the
number
of bits in the final (promoted and balanced) type that are used, and not
the number of bits in the original types of the expression."
EXAMPLE
void foo()
{
unsigned char mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// Violation
}
REPAIR
void foo()
{
unsigned short mask = ~(0x10);
unsigned short ushort;
ushort ^= mask;
// OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-20
Bitwise operators shall only be applied to operands of unsigned underlying type [MISRA20085_0_21-3]
DESCRIPTION
"Bitwise operations (~, <<, <<=, >>, >>=, &, &=, ^, ^=, | and |=) are not
normally meaningful on signed integers or enumeration constants.
Additionally, an implementation-defined result is obtained if a right
shift
is applied to a negative value."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & s1;
// Violation
REPAIR
int foo1( )
{
signed short
s1;
unsigned short us1, us2;
us1 = us2 & (unsigned short)s1;
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-0-21
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int a, b;
b = a = 0;// Violation
}
REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
NOTES
Macro's body is excluded from checking.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int a, b;
b = (a = 0);// OK
b = (a + 0);// Violation
}
REPAIR
void foo() {
int a, b;
b = (a = 0);// OK
b = a + 0;// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( )
{
int a, b;
b = a * (-1);
}
// Violation
REPAIR
void foo( )
{
int a, b;
b = a * -1;
}
REFERENCES
// OK
SINCE
v7.0
BENEFITS
Rule increases safety in arithmetic operations.
EXAMPLE
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
REPAIR
#ifdef _MSC_VER
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
#elif __GNUC__
#include <sys/types.h>
typedef u_int16_t uint16;
typedef u_int32_t uint32;
#endif
void fooPlus(
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a + (b
}
) {
10;
65535;
0;
+ c); /* OK d is 65545 */
void fooMultiply( ) {
uint16 a =
uint16 b =
uint32 c =
uint32 d;
d = a * (b
10;
65535;
0;
* c); /* OK d is 655350 */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
NOTES
The operands of a logical && and || are checked by the rule MISRA2004-12_5
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( ) {
int a, b;
b = a * a + a;
}
// Violation
REPAIR
void foo( ) {
int a, b;
b = (a * a) + a;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
Note:
Nested parentheses level is set on 10 but can be changed. To change the
default level of the nested parentheses modify the main "Count" expression
of the rule (Collector A) from "$$ > 9" to "$$ > N" using desired
threshold
value for N. Rule's header should be also changed accordingly.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( )
{
int a, b,c,d;
a=(((((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8)/(b+d))+3; // Violation
REPAIR
void foo( )
{
int a, b,c,d;
int h;
h = (((((((((b+1)+1)+c)*d)/2)+1)*b)+c)*d)+8;
a =(h*(b+d))+3;
}
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 213
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-2
4. Origin: Misra Guidelines - Rule 47
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned short u16a,u16b;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned short u16a,u16b;
unsigned int u32a, u32b;
u32a = u32b + u16b + u16a;
u32a = u16b + (u16a + u32b);
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.
EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;
/* Violation */
REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a;
u32a = (unsigned int)(u16b + u16a);
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
DRAWBACKS
Rule checks only the simple expressions. Rule does not report any
violations
if an expression is more complex.
EXAMPLE
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = u16b + u16a;
/* Violation */
REPAIR
void Conv1_int( )
{
unsigned short u16a,u16b;
unsigned int u32a = (unsigned int)(u16b + u16a);
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-3
3. ISO/DIS 26262
point 8.4.4
An implicit integral conversion shall not change the signedness of the underlying type
[MISRA2008-5_0_4_a-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used.
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
s32a = u32a;
s32b = s32a + u32a;
}
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned int u32a, u32b;
signed int s32a, s32b;
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4
An implicit integral conversion shall not change the signedness of the underlying type
[MISRA2008-5_0_4_b-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
Rule checks if implicit conversions between signed and unsigned types are
used
when variables are initialized.
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = u32a;
}
/* Violation */
REPAIR
void Conv1_int( )
{
unsigned int u32a;
signed int s32a = (signed int)u32a;
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-4
3. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a
=
=
=
=
f32a;
f32a;
f64a;
f32b + f32a + f64b;
REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
//
//
//
//
Violation
Violation
Violation
Violation
u32b
s32b
f32a
f64a
=
=
=
=
(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}
REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
// Violation
// Violation
// Violation
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
float f32a;
unsigned int u32a;
f32a = u32a;
f32a = f32a + u32a;
f32a = u32a + 2.5f;
}
REPAIR
void Conv1_int( ) {
float f32a;
unsigned int u32a;
/* Violation */
/* Violation */
/* Violation */
f32a = (float)u32a;
f32a = f32a + (float)u32a;
f32a = (float)u32a + 2.5f;
/* OK */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
3. ISO/DIS 26262
point 8.4.4
An implicit integral or floating-point conversion shall not reduce the size of the underlying
type [MISRA2008-5_0_6_a-3]
DESCRIPTION
"The value of an expression of integer type shall not be implicitly
converted
to a different underlying type.
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion.
Integral promotion describes a process whereby arithmetic operations are
always
conducted on integer operands of type int or long (signed or unsigned).
Operands of any other integer type, (char, short, bit-field and enum) are
always converted to type int or unsigned int before an arithmetic
operation.
The underlying type of an integer constant expression will be determined
according to its magnitude and signedness"
The rule reports a violation if parameter/variable/expression of integral
type is implicitly converted to a narrower integral type.
SINCE
v7.0
NOTES
The rule assumes the following order of sizes:
char < short < int < long < long long
The underlying type of an integer constant is determined according
to its magnitude and signedness.
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = u32a;
u8a = u32a;
/* Violation */
/* Violation */
REPAIR
void Conv1_int( ) {
unsigned char u8a;
unsigned short u16a;
unsigned int u32a;
u16a = (unsigned short)u32a;
u8a = (unsigned char)u32a;
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
An implicit integral or floating-point conversion shall not reduce the size of the underlying
type [MISRA2008-5_0_6_b-3]
DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
signed int s32a,s32b;
u32b
s32b
f32a
f64a
=
=
=
=
f32a;
f32a;
f64a;
f32b + f32a + f64b;
REPAIR
unsigned short goo_float( ) {
double f64a, f64b;
float f32a, f32b;
unsigned int u32a, u32b;
//
//
//
//
Violation
Violation
Violation
Violation
=
=
=
=
(unsigned int)f32a;
(signed int)f32a;
(float)f64b;
f64b + f32b + f32a;
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
An implicit integral or floating-point conversion shall not reduce the size of the underlying
type [MISRA2008-5_0_6_c-3]
DESCRIPTION
"The value of an expression of float type shall not be implicitly
converted
to a different type."
SINCE
v7.0
BENEFITS
"By observing the principle whereby all operations are performed in
a consistent (underlying) type, it is possible to avoid programmer
confusion
and some of the dangers associated with integral promotion."
EXAMPLE
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
float32_t f32bt = f64a;
unsigned int u32a = f32a;
unsigned short u16a = 1.0;
}
REPAIR
typedef float float32_t;
void goo_float( ) {
double f64a;
float f32a;
// Violation
// Violation
// Violation
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 184
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-5
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-6
5. ISO/DIS 26262
point 8.4.4
BENEFITS
The rule prevents behaviours inconsistent with developer expectations.
EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}
REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =
/*
/*
/*
/*
OK
OK
OK
OK
*/
*/
*/
*/
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9
BENEFITS
Prevents loss of data.
EXAMPLE
typedef float
typedef double
typedef long double
float32_t;
float64_t;
float128_t;
void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float64_t)(f32a + f32b);
/* Violation */
REPAIR
typedef float
typedef double
typedef long double
float32_t;
float64_t;
float128_t;
void goo( ) {
float128_t f128a, f128b;
float64_t f64a, f64b;
float32_t f32a, f32b;
(float32_t)(f64a + f64b);
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
An explicit integral or floating-point conversion shall not increase the size of the underlying
type of a cvalue expression [MISRA2008-5_0_8-3]
DESCRIPTION
Rule reports violation if the value of a complex expression of integer
type
is cast to a type that has different signedness or is wider than
the underlying type of the expression.
"The term 'complex expression' is defined to mean any expression that is
not:
- a constant expression
- an lvalue (i.e. an object)
- the return value of a function
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
BENEFITS
The rule prevents behaviours inconsistent with developer expectations.
EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}
REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =
/*
/*
/*
/*
OK
OK
OK
OK
*/
*/
*/
*/
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9
An explicit integral conversion shall not change the signedness of the underlying type of a
cvalue expression [MISRA2008-5_0_9-3]
DESCRIPTION
Rule reports violation if the value of a complex expression of integer
type
is cast to a type that has different signedness or is wider than
the underlying type of the expression.
"The term 'complex expression' is defined to mean any expression that is
not:
- a constant expression
- an lvalue (i.e. an object)
- the return value of a function
The term 'underlying type' is defined as describing the type that would
be obtained from evaluating an expression if it were not for the effects
of integral promotion."
BENEFITS
The rule prevents behaviours inconsistent with developer expectations.
EXAMPLE
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1 = (unsigned int)(si1 + si2); /*
unsigned type */
si1 = (signed int)(ui1 / ui2);
/*
signed type */
ui1 = (unsigned int)(us1 - us2); /*
wider type */
d = (double)(ui1 * ui2);
/*
floating type */
}
REPAIR
void myFunction()
{
unsigned int ui1, ui2;
signed int si1, si2;
unsigned short us1, us2;
double d;
ui1
si1
ui1
d =
/*
/*
/*
/*
OK
OK
OK
OK
*/
*/
*/
*/
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 10
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-7
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-8
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-0-9
The right hand operand of a logical && or || operator shall not contain side effects
[MISRA2008-5_14_1-3]
DESCRIPTION
"There are some situations in C or C++ where certain parts of expressions
may
not be evaluated. If these sub-expressions contain side effects then those
side
effects may or may not occur, depending on the values of other sub
expressions.
The operators which can lead to this problem are && and || where the
evaluation
of the right-hand operand is conditional on the value of the left-hand
operand.
The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
See also: MISRA2004-12_2_a, MISRA2004-12_4_b
NOTES
Rule checks only three nested level of function calls.
BENEFITS
Rule prevents conditional evaluation of the right-hand operand that can
easily
cause problems if the developer relies on a side effect occurring.
EXAMPLE
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i++)) ; // Violation
}
REPAIR
void foo( ) {
int i;
int j;
if ((j == i) || (0 == i)) i++; // OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 33
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 157
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-14-1
5. ISO/DIS 26262
point 8.4.4
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo() {
int x, y;
x = 0, y = 0;
}
// Violation
REPAIR
void foo() {
int x, y;
x = 0;
y = 0;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-18-1
SINCE
v7.3
EXCEPTIONS
"Where an expression consists of either a sequence of only logical '&&'
or a sequence of only logical '||', extra parentheses are not required.
BENEFITS
"The effect of this rule is to require that operands are appropriately
parenthesized."
EXAMPLE
int foo( int x, int y, int z )
{
if ( x || y && z );
// Violation
if ( x && !y );
// Violation
return 0;
}
REPAIR
int foo( int x, int y, int z )
{
if ( x || ( y && z ) );
if ( x && ( !y ) );
// OK
// OK
return 0;
}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-1
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 158
The increment (++) and decrement (--) operators should not be mixed with other operators in
an expression [MISRA2008-5_2_10-4]
DESCRIPTION
"It is the intention of the rule that when the increment or decrement
operator
is used, it should be the only side-effect in the statement.
The use of increment and decrement operators in combination with other
arithmetic operators is not recommended because:
- It can significantly impair the readability of the code
- It introduces additional side effects into a statement with the
potential for
undefined behaviour
It is safer to use these operations in isolation from any other arithmetic
operators."
BENEFITS
Improves readability and maintainability.
Reduces risk of potential undefined behaviour
caused by additional side effects
EXAMPLE
void foo() {
int x, y;
x = --y + x++;
}
/* Violation */
REPAIR
void foo() {
int x, y;
--y;
x = y + x;
x++;
}
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 204
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-10
The comma operator, && operator and the || operator shall not be overloaded [MISRA20085_2_11-3]
DESCRIPTION
"The built-in &&, || or, (comma) enjoy special treatment from the
compiler.
If you overload them, they become ordinary functions with very different
semantics, and this is a sure way to introduce subtle bugs and
fragilities."
This rule detects when you overload operator &&, || or ,(comma).
BENEFITS
Overloading these operators changes the way the compiler reads the
semantics of an expression, resulting in unpredictable program behavior.
EXAMPLE
class A {
public:
A( int i ) : _i( i ) {}
~A( );
int value( ) { return _i; }
private:
int _i;
};
int operator&&( A& lhs, A& rhs ) {
return lhs.value( ) && rhs.value( );
}
// Violation
REPAIR
Do not overload operator &&, || or ,(comma).
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-
Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 30
2. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 7
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 159
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-11
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
An identifier with array type passed as a function argument shall not decay to a pointer
[MISRA2008-5_2_12-3]
DESCRIPTION
"When a variable with array type decays to a pointer, its bounds are
lost."
SINCE
v7.2
BENEFITS
"If a design requires arrays of different lengths, then a class should
be used to encapsulate the array objects and so ensure that the
dimensionality
is maintained."
EXAMPLE
typedef int int32_t;
void f1( int32_t p[ 10 ] );
void f2( int32_t *p );
void b ()
{
int32_t a[ 10 ];
f1( a ); // Violation
f2( a ); // Violation
}
REPAIR
typedef int int32_t;
void f1( int32_t ( &p )[ 10 ] );
void b ()
{
int32_t a[ 10 ];
f1( a );
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-12
A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of
dynamic_cast [MISRA2008-5_2_2-3]
DESCRIPTION
"Since the virtualness of inheritance is not a property of a base class,
the layout of a derived class object, referenced through a virtual base
pointer, is unknown at compile time."
"Casting from a virtual base to a derived class, using any means
other than dynamic_cast has undefined behaviour.
The behaviour for dynamic_cast is defined."
See also: OOP-29, OOP-49
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviours.
EXAMPLE
// The code is not compilable with all compilers
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = static_cast<D*>(pB); // Violation
}
REPAIR
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = dynamic_cast<D*>(pB);
}
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 179
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-2
Casts from a base class to a derived class should not be performed on polymorphic types
[MISRA2008-5_2_3-4]
DESCRIPTION
"A downcast occurs when a class type is converted to another class type
that is derived from that first class.
Polymorphism enables strong abstraction between the interface and
implementation
of a hierarchy. Explicit casts bypass this layer of abstraction resulting
in higher levels of coupling and dependency."
"Casting from a base class to a derived class is unsafe unless some
mechanism
is provided to ensure that the cast is legitimate."
See also: OOP-29, OOP-50
SINCE
v7.2
BENEFITS
Prevents illegal casts and ensures that abstraction layer is not bypassed.
EXAMPLE
class B
{
public:
virtual int foo( );
};
class D : public B
{
public:
int foo( );
};
void main( )
{
B *b;
D *d;
d = (D*) b; // Violation
}
REPAIR
Do not cast a pointer to a base class to a pointer to a class
that inherits from it.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-3
C-style casts (other than void casts) and functional notation casts (other than explicit
constructor calls) shall not be used [MISRA2008-5_2_4-3]
DESCRIPTION
"C-style (cast notation), and functional notation casts that do not invoke
a converting constructor are capable of performing casts between unrelated
types."
SINCE
v7.2
EXCEPTIONS
"A C-style cast to void may be used to signify that the return value
for a non-void function call is being ignored"
BENEFITS
C++ casts are more specific than C casts and are much easier to locate
and read.
EXAMPLE
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD2 = (Derived *) pB;
// Violation
REPAIR
class Base {
public:
Base( );
virtual ~Base( );
};
class Derived : public Base {
public:
Derived( );
~Derived( );
};
void foo( ) {
Base *pB;
Derived *pD1 = dynamic_cast<Derived*>( pB );
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-4
A cast shall not remove any const or volatile qualification from the type of a pointer or
reference [MISRA2008-5_2_5-3]
DESCRIPTION
"Any attempt to remove the qualification associated with the addressed
type by
using casting is a violation of the principle of type qualification.
Notice that the qualification referred to here is not the same as any
qualification that may be applied to the pointer itself."
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
typedef unsigned short uint16_t;
void foo( )
{
uint16_t *pi, **ppi;
uint16_t * const * pcpi; /* pointer
const uint16_t * * ppci; /* pointer
const uint16_t * pci;
/* pointer
volatile uint16_t * pvi; /* pointer
pi = (uint16_t *)pci;
pi = (uint16_t *)pvi;
ppi = (uint16_t * *)pcpi;
ppi = (uint16_t * *)ppci;
/*
/*
/*
/*
to
to
to
to
Violation
Violation
Violation
Violation
const pointer */
pointer to const */
const */
volatile */
*/
*/
*/
*/
REPAIR
Do not cast from 'const' or 'volatile' type addressed by a pointer to
'non-const'
or 'non-volatile' type.
REFERENCES
A cast shall not convert a pointer to a function to any other pointer type, including a pointer to
function type [MISRA2008-5_2_6-3]
DESCRIPTION
"Conversion of a function pointer to a non-function pointer type causes
undefined behaviour. Undefined behaviour may arise if a function call is
made using a pointer that is the result of a function pointer conversion."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
void f ( int )
{
reinterpret_cast< void (*)( ) >( &f ); // Violation
reinterpret_cast< void * >( &f );
// Violation
}
REPAIR
Do not cast a pointer to a function to any other pointer type.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-6
An object with pointer type shall not be converted to an unrelated pointer type, either directly
or indirectly [MISRA2008-5_2_7-3]
DESCRIPTION
"A cast should not be performed between a pointer to object type and a
different
pointer to object type. Conversions of this type may be invalid if the new
pointer type requires a stricter alignment.
Pointer types can be classified as follows:
- Pointer to object
- Pointer to function
- Pointer to void
- The null pointer constant (the value 0 cast to type void *)"
NOTES
Pointers which are different only const or volatile qualifier are not
checked
by this rule.
BENEFITS
Prevents incorrect pointer alignment.
EXAMPLE
void foo( )
{
unsigned int* ui;
signed char* sc;
/* Examples of incorrect code */
ui = (unsigned int*) sc;
ui = (unsigned int*) ≻
}
REPAIR
/* Violation */
/* Violation */
/* OK */
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
2. Origin: Misra Guidelines rule 45
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-7
4. ISO/DIS 26262
point 8.4.4
An object with integer type or pointer to void type shall not be converted to an object with
pointer type [MISRA2008-5_2_8-3]
DESCRIPTION
"An object with integer type or pointer to void type shall
not be converted to an object with pointer type"
SINCE
v7.2
BENEFITS
In general, converting from an integral type or a pointer to void type
to a pointer to an object leads to unspecified behaviour.
EXAMPLE
struct S
{
int i;
int j;
};
void f ( void * v, int i )
{
S * s1 = reinterpret_cast< S * >( v ); // Violation
S * s2 = reinterpret_cast< S * >( i ); // Violation
}
REPAIR
Do not cast an object with integer type or pointer to void type
to an object with pointer type
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-8
EXCEPTIONS
The rule allows to cast to UINT_PTR or INT_PTR type. These types are
integral
types that scale to the size of a pointer for both 32-bit and 64-bit
Windows.
BENEFITS
Prevents undefined or implementation-defined behaviour.
EXAMPLE
void foo( ) {
int* pi;
int i;
i = (int) pi;
}
// Violation
REPAIR
Do not cast pointers to non-pointers.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 11
2. Misra Guidelines rule 45
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 7
4. http://msdn2.microsoft.com/en-gb/library/aa489560.aspx
5. http://www.codeproject.com/system/64BitOSAndPortingIssues.asp
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 182
7. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-2-9
8. ISO/DIS 26262
point 8.4.4
Each operand of the ! operator, the logical && or the logical || operators shall have type bool
[MISRA2008-5_3_1-3]
DESCRIPTION
"The use of operands with types other than bool with these operators is
unlikely to be meaningful (or intended). This rule allows the detection of
such uses, which often occur because the logical operators (&&, || and !)
can be easily confused with the bitwise operators (&, | and ~)."
SINCE
v7.2
NOTES
Rule does not report violations if the operand is a call
to a conversion function that converts to a typedef with a name
containing 'bool' that names a pointer to member.
BENEFITS
Rule improves readability and maintainability.
Rule prevents confusion between logical and bitwise operators.
EXAMPLE
/* examples of incorrect code */
void foo(int a, int b, int c, int d, int* ptr)
{
if ( 1 && ( c < d ) ) {}
// Violation
if ( ( a < b ) && ( c + d ) ){} // Violation
if ( a || ( c + d ) ) {}
// Violation
if ( !ptr ) {}
// Violation
}
REPAIR
/* examples of correct code */
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-1
The unary minus operator shall not be applied to an expression whose underlying type is
unsigned [MISRA2008-5_3_2-3]
DESCRIPTION
"Applying the unary minus operator to an expression of type unsigned int
or
unsigned long generates a result of type unsigned int or unsigned long
respectively and is not a meaningful operation. Applying unary minus to an
operand of smaller unsigned integer type may generate a meaningful signed
result
due to integral promotion, but this is not good practice."
BENEFITS
Prevents unexpected result due to integral promotion.
EXAMPLE
void foo() {
unsigned char ui1;
signed short si2;
si2 = -ui1;
}
// Violation
REPAIR
void foo() {
unsigned char ui1;
signed short si2;
si2 = -(signed short) ui1;
}
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
class A
{
public:
A * operator & ( );
};
// Violation
REPAIR
Do not overload the unary '&' operator
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-3-3
Evaluation of the operand to the sizeof operator shall not contain side effects [MISRA20085_3_4-3]
DESCRIPTION
"A possible programming error in C is to apply the sizeof operator to an
expression and expect the expression to be evaluated. However the
expression
is not evaluated: sizeof only acts on the type of the expression. To avoid
this
error, sizeof shall not be used on expressions that contain side effects,
as the side effects will not occur."
"The operations that cause side effects are accessing a volatile object,
modifying an object, modifying a file, or calling a function that does
any of those operations, which cause changes in the state of the execution
environment of the calling function."
NOTES
Rule checks only three nested level of function calls.
EXCEPTIONS
An operand of the form sizeof(i) where i is volatile is permitted.
BENEFITS
Prevents error that are caused by believing that operand of sizeof is
evaluated.
EXAMPLE
int glob;
int fun_with_se(){
glob++; // side-effect
return glob;
}
void foo1(int i){
int
j =
l =
m =
j, k, l, m;
sizeof(k = 2);
// Violation - k is not set to 2
sizeof(i++);
// Violation - i is not incremented
sizeof(fun_with_se()); // Violation - glob is not incremented
REPAIR
int fun_without_se(){
// no side-effect
return 1;
}
void foo1(int i){
int j, k, l, m, n, o;
volatile int vol;
k = 2;
j = sizeof(k);
i++;
l = sizeof(i);
// examples of correct code
m = sizeof(fun_without_se());
n = sizeof(int);
o = sizeof(vol);
}
// OK
// OK
// OK
// OK
// OK - volatile objects are permitted
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. Origin: Misra Guidelines - Rule 40
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 166
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-3-4
The right hand operand of a shift operator shall lie between zero and one less than the width
in bits of the underlying type of the left hand operand [MISRA2008-5_8_1-3]
DESCRIPTION
"If, for example, the left-hand operand of a left-shift or right-shift is
a
16-bit integer, then it is important to ensure that this is shifted only
by a
number between 0 and 15 inclusive.
There are various ways of ensuring this rule is followed. The simplest is
for
the right-hand operand to be a constant (whose value can then be
statically
checked). Use of an unsigned integer type will ensure that the operand is
non-negative, so then only the upper limit needs to be checked
(dynamically at
run-time or by review). Otherwise both limits will need to be checked."
The rule checks right-hand operand of shift operator and reports a
violation
in following cases:
- the operand is a constant with negative value or with value that exceeds
the length (in bits) of the left-hand operand
- the operand is a non-const variable and it's value is not checked by
specific
pattern.
The specific pattern recognized by the rule requires the shift operator
to be wrapped by an 'if' statement which checks the variable's value
using
comparison operators (both "greater then" and "less then" operators must
be used).
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
uint8_t;
uint16_t;
{
uint8_t u8a;
u8a = (uint8_t) (u8a << 9); /* Violation */
u8a = (uint8_t) (u8a << p); /* Violation */
}
REPAIR
typedef unsigned char
typedef unsigned short
void foo( uint16_t p )
{
uint8_t u8a;
uint16_t u16a;
uint8_t;
uint16_t;
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 12
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 5, Rule 5-8-1
NOTES
An expression is considered to represent a Boolean value either because
it appears in a position where a Boolean value is expected or because it
uses an operator that gives rise to a Boolean value. Boolean values are
expected in the following contexts:
- the controlling expression of an if statement
- the controlling expression of an iteration statement
- the first operand of the conditional operator ?
BENEFITS
Rule prevents getting "=" and "==" confused.
EXAMPLE
void foo()
{
int x;
int y;
int z;
z = !(x = y);
if ((x > y) && (x = 4));
// Violation
// Violation
if (!(x = y));
// Violation
REPAIR
void foo()
{
int x;
int y;
int z;
z = !(x == y);
// OK
if ((x > y) && (x == 4)); // OK
if (!(x == y));
// OK
}
REFERENCES
1. Misra Guidelines - Rule 35
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 160
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-1
Floating-point expressions shall not be directly or indirectly tested for equality or inequality
[MISRA2008-6_2_2-3]
DESCRIPTION
"Floating-point expressions shall not be tested for equality or
inequality.
The recommended method for achieving deterministic floating-point
comparisons is
to write a library that implements the comparison operations. The library
should
take into account the floating-point granularity (FLT_EPSILON) and the
magnitude
of the numbers being compared."
NOTES
Rule does not detect indirect tests of equality and inequality which are
equally
problematic and are also forbidden by Misra standard:
if ( ( x <= y ) && ( x >= y ) )
{
/* ... */
}
BENEFITS
"The inherent nature of floating-point types is such that comparisons of
equality will often not evaluate to true even when they are expected to.
In
addition the behaviour of such a comparison cannot be predicted before
execution, and may well vary from one implementation to another. "
EXAMPLE
void foo() {
float x, y;
if (x == y);
if (x == 0.0f);
// Violation
// Violation
REPAIR
void foo( float epsilon ) {
float x, y;
if (x - epsilon <= y && y <= x + epsilon);
if (-epsilon <= x && x <= epsilon);
// OK
// OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Misra Guidelines - Rule 50
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.25 Expressions, AV Rule 202
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-2
Before preprocessing, a null statement shall only occur on a line by itself; it may be followed
by a comment, provided that the first character following the null statement is a white-space
character [MISRA2008-6_2_3-3]
DESCRIPTION
"Null statements should not normally be deliberately included, but where
they
are used they shall appear on a line by themselves.
White-space characters may precede the null statement to preserve
indentation.
If a comment follows the null statement then at least one white-space
character
shall separate the null statement from the comment.
The use of a white-space character to separate the null statement from any
following comment is required on the grounds that it provides an important
visual cue to reviewers."
See also: MISRA-054.
BENEFITS
"Following this rule enables a static checking tool to
warn of null statements appearing on a line with other text,
which would normally indicate a programming error."
EXAMPLE
void foo()
{
/* Violation */ ;
;/* Violation */
}
REPAIR
void goo()
{
/* OK */
;
; /* OK */
;
/* OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-2-3
The statement forming the body of a switch, while, do while or for statement shall be a
compound statement [MISRA2008-6_3_1-3]
DESCRIPTION
" The statement that forms the body of a switch statement or a while,
do ... while or for loop, shall be a compound statement (enclosed within
braces), even if that compound statement contains a single statement."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x ) {
int i;
switch(i)
;
// Violation
// Violation
REPAIR
void foo( int x ) {
int i;
switch(i)
{
}
// OK
{foo( x );}
while (1)
{foo( x );}
// OK
do
// OK
{foo( x );}
while(1);
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 59
3. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-3-1
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int x, int
{
int i, j;
if(x > 0)
//
x = i;
else if(y > 0) //
y = i;
else
y = j;
//
x = j;
}
y )
Violation
Violation
Violation
REPAIR
void foo( int x, int y )
{
int i, j;
if(x > 0)
// OK
{
x = i;
}
else if(y > 0) // OK
{
y = i;
}
else
{
y = j;
x = j;
// OK
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Misra Guidelines - Rule 59
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 6 Style - 6.4 Flow Control Statements - Rec. 25
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 59
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-1
All if ... else if constructs shall be terminated with an else clause [MISRA2008-6_4_2-3]
DESCRIPTION
"This rule applies whenever an 'if' statement is followed by one or more
'else-if' statements; the final 'else-if' shall be followed by an 'else'
statement. In the case of a simple 'if' statement then the 'else'
statement
need not be included.
The requirement for a final 'else' statement is defensive programming.
The 'else' statement should either take appropriate action or contain
a suitable comment as to why no action is taken."
See also: CODSTA-23
BENEFITS
Rule ensures proper data flow and improves readability and
maintainability.
EXAMPLE
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
}
// Violation
REPAIR
void foo(int a)
{
if(a > 0)
{
}
else if (a > 10)
{
}
// OK
else
{
// comment or action
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 60
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 192
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-2
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int a, int b ) {
switch(a) {
case 1:
{
case 6:
/* Violation */
;
default:
/* Violation */
break;
}
break;
case 2:
if (b == 1) {
case 3:
/* Violation */
break;
}
break;
}
}
REPAIR
Do not use nested 'case'/'default' statements.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-4
SINCE
v7.2
BENEFITS
Prevents unpredictable program behaviour.
EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
{
// Violation
// Violation
i = 5;
break;
}
case 2 :
{
// Violation
i = 3;
}
default:
i = 8;
// Violation
}
}
REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
throw;
}
}
// OK
// OK
// OK
// OK - empty case
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
SINCE
v7.2
EXCEPTIONS
"If the condition of a switch statement is of type enum, and all the
enumerators are listed in case labels, then the default-clause is not
required
as the rules associated with enums are intended to ensure that the enum
cannot
be assigned values outside of its set of enumerators."
BENEFITS
Rule improves readability and maintainability of 'switch' statement.
EXAMPLE
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
// Violation
}
switch( colour )
{
case RED:
break;
case GREEN:
break;
// Violation
}
}
REPAIR
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
default:
break;
}
switch( colour )
{
case RED:
break;
case BLUE:
break;
case GREEN:
break;
}
}
// OK
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
BENEFITS
Rule prevents using values that are effectively Boolean in switch.
EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}
// Violation
REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}
REFERENCES
// OK
BENEFITS
Provides maintainability of 'switch' statement.
EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}
/* Violation */
REPAIR
void foo(int i)
{
switch(i)
{
case 1:
{
}
default:
;
}
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 64
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-8
A switch-label shall only be used when the most closely-enclosing compound statement is the
body of a switch statement [MISRA2008-6_4_4-3]
DESCRIPTION
"The scope of a case or default label shall be the compound statement,
which is the body of a switch statement.
All case clauses and the default clause shall be at the same scope."
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo( int a, int b ) {
switch(a) {
case 1:
{
case 6:
/* Violation */
;
default:
/* Violation */
break;
}
break;
case 2:
if (b == 1) {
case 3:
/* Violation */
break;
}
break;
}
}
REPAIR
Do not use nested 'case'/'default' statements.
REFERENCES
SINCE
v7.2
BENEFITS
Prevents unpredictable program behaviour.
EXAMPLE
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
break;
i++;
case 1 :
i = 7;
if (i > 0)
// Violation
// Violation
{
i = 5;
break;
}
case 2 :
{
// Violation
i = 3;
}
default:
i = 8;
// Violation
}
}
REPAIR
void foo( int i )
{
switch( i )
{
case 0 :
i = 4;
i++;
break;
case 1 :
i = 7;
if (i > 0)
{
i = 5;
break;
}
break;
case 2 :
{
i = 3;
break;
}
case 3 :
default:
i = 8;
throw;
}
}
// OK
// OK
// OK
// OK - empty case
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-5
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
SINCE
v7.2
EXCEPTIONS
"If the condition of a switch statement is of type enum, and all the
enumerators are listed in case labels, then the default-clause is not
required
as the rules associated with enums are intended to ensure that the enum
cannot
be assigned values outside of its set of enumerators."
BENEFITS
Rule improves readability and maintainability of 'switch' statement.
EXAMPLE
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
// Violation
}
switch( colour )
{
case RED:
break;
case GREEN:
break;
// Violation
}
}
REPAIR
enum Colours { RED, BLUE, GREEN } colour;
void foo(int i)
{
switch( i )
{
case 0:
break;
case 1:
case 2:
break;
default:
break;
}
switch( colour )
{
case RED:
break;
case BLUE:
break;
case GREEN:
break;
}
}
// OK
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-6
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
The condition of a switch statement shall not have bool type [MISRA2008-6_4_7-3]
DESCRIPTION
Values which are effectively Boolean should not be represented in
'switch' condition.
The rule forbids following operators:
a) equality operators (== and !=)
b) logical operators (!, && and ||)
c) relational operators (<, >, <= and >=)
which produce boolean-by-construct values.
BENEFITS
Rule prevents using values that are effectively Boolean in switch.
EXAMPLE
void foo(int i)
{
switch(i == 0)
{
case 0 : break;
default:;
}
}
// Violation
REPAIR
void foo1(int i)
{
switch(i)
{
case 0 : break;
default:;
}
}
REFERENCES
// OK
BENEFITS
Provides maintainability of 'switch' statement.
EXAMPLE
void foo(int i)
{
switch(i)
{
default:
;
}
}
/* Violation */
REPAIR
void foo(int i)
{
switch(i)
{
case 1:
{
}
default:
;
}
}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 15
2. Origin: Misra Guidelines - Rule 64
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-3
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-4-8
A for loop shall contain a single loop-counter which shall not have floating type [MISRA20086_5_1-3]
DESCRIPTION
"A for loop without exactly one loop-counter is simply a while loop.
If this is the desired behaviour, then a while loop is more appropriate."
SINCE
v7.2
NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
BENEFITS
Rule helps to ensure deterministic loop termination.
EXAMPLE
void foo()
{
int x = 0;
int y;
y = 0;
for (x = 0; x < y; x = y++){} // Violation
}
REPAIR
void foo3()
{
int x = 0;
int y;
y = 0;
x = 0;
while(x < y) // OK
{
x = y++;
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-1
If loop-counter is not modified by -- or ++, then, within condition, the loop-counter shall only
be used as an operand to <=, <, > or >= [MISRA2008-6_5_2-3]
DESCRIPTION
"When the loop-counter is modified using an operator other than -- or ++,
then == and != shall not be used, as loop termination may not occur,
which may be inconsistent with developer expectations."
SINCE
v7.2
NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
BENEFITS
Rule helps to ensure deterministic loop termination.
EXAMPLE
void foo()
{
int i;
for ( i = 1; i != 10; i += 2 ){} // Violation
}
REPAIR
void foo()
{
int i;
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-2
NOTES
A
-
BENEFITS
Modification 'for' loop counter within a body of the loop can lead to
errors and confusion.
EXAMPLE
void foo( ) {
int i;
for ( i = 0; i < 5; i++ ) {
i = i + 3;
}
}
/* Violation */
REPAIR
void foo( ) {
int i;
for ( i = 0; i < 5; i = i + 3 ) {} /* OK */
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 13
2. Origin: Misra Guidelines - Rule 67
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.24 Flow Control Structures, AV Rule 201
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 6, Rule 6-5-3
The loop-counter shall be modified by one of: --, ++, -=n, or +=n; where n remains constant for
the duration of the loop [MISRA2008-6_5_4-3]
DESCRIPTION
"The loop-counter shall be modified by one of: --, ++, -=n, or +=n;
where n remains constant for the duration of the loop"
SINCE
v7.2
NOTES
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
BENEFITS
Rule helps to ensure deterministic loop termination.
EXAMPLE
void foo()
{
int x;
for ( x = 0; x < 10; x = x + 1 ){} // Violation
}
REPAIR
void foo()
{
int x;
for ( x = 0; x < 10; ++x ){} // OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-4
A loop-control-variable other than the loop-counter shall not be modified within condition or
expression [MISRA2008-6_5_5-3]
DESCRIPTION
"A loop-control-variable other than the loop-counter shall
not be modified within condition or expression.
A loop-control-variable is any variable occurring in for-init-statement,
condition or expression.
A loop-counter is a loop-control-variable that is:
- Initialized in, or prior to, for-init-statement; and
- an operand to a relational operator in condition; and
- modified in expression.
loop-control-variables are either the loop-counter, or flags used for
early
loop termination. The code is easier to understand if these are not
modified
within condition or expression."
SINCE
v7.2
NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.
BENEFITS
Rule improves readability of code.
EXAMPLE
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; flag = test(++x) ) {}
}
// Violation
REPAIR
bool test(int x);
void foo(int x, bool flag)
{
for ( x = 0; x < 10; ++x ) // OK
{
flag = test(x);
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-5
SINCE
v7.2
NOTES
The rule assumes that variable or parameter might be modified by passing
its non-const pointer or reference to an external function.
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && ( u8a != 3U ); ++x )
{
u8a = 5;
// Violation
}
}
REPAIR
void foo(int x, unsigned int u8a, bool flag)
{
for ( x = 0; ( x < 10 ) && flag; ++x )
{
u8a = 5;
// OK
flag = u8a != 3U;
}
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-5-6
Any label referenced by a goto statement shall be declared in the same block, or in a block
enclosing the goto statement [MISRA2008-6_6_1-3]
DESCRIPTION
"Any label referenced by a goto statement shall be declared in the same
block,
or in a block enclosing the goto statement. Unconstrained use of goto can
lead to programs that are extremely difficult to comprehend, analyse and,
for C++, can also lead to the program exhibiting unspecified behaviour.
However, in many cases a total ban on goto requires the introduction of
flags to ensure correct control flow, and it is possible that these flags
may themselves be less transparent than the goto they replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. Jumping in to nested
blocks is
prohibited as it may lead to complex flow graphs."
SINCE
v7.2
BENEFITS
Prevents unspecified behaviour.
EXAMPLE
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
L1: // Violation
j;
}
}
REPAIR
void f1 ( )
{
int j = 0;
goto L1;
for ( j = 0; j < 10 ; ++j )
{
/* ... */
}
L1: // OK
j;
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-1
The goto statement shall jump to a label declared later in the same function body [MISRA20086_6_2-3]
DESCRIPTION
"Unconstrained use of goto can lead to programs that are extremely
difficult
to comprehend, analyse and, for C++, can also lead to the program
exhibiting
unspecified behaviour. However, in many cases a total ban on goto requires
the introduction of flags to ensure correct control flow, and it is
possible
that these flags may themselves be less transparent than the goto they
replace.
Therefore, the restricted use of goto is allowed where that use will not
lead
to semantics contrary to developer expectations. "Back" jumps are
prohibited
as they can be used to create iterations without using the well-defined
iteration statements supplied by the core language."
SINCE
v7.2
BENEFITS
Prevents unspecified behaviour.
EXAMPLE
void foo(int j)
{
L1:
++j;
goto L1; // Violation - jumps backward
++j;
}
REPAIR
void foo(int j)
{
++j;
goto L1; // OK ++j;
L1:
}
jumps forward
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-2
The continue statement shall only be used within a well-formed for loop [MISRA2008-6_6_3-3]
DESCRIPTION
"Over-use of the continue statement can lead to unnecessary complexity
within
the code. This complexity may impede effective testing as extra logic must
be
tested. The required testing may not be achievable due to control flow
dependencies."
SINCE
v7.2
EXCEPTIONS
Rule does not report a violation if the 'continue' is used within 'for'
loop.
BENEFITS
Rule eliminates unnecessary complexity within the code.
EXAMPLE
void foo()
{
int x = 0;
int y;
y = 10;
while(x < y)
{
x++;
/* ... */
continue;
}
// Violation
REPAIR
Do not use 'continue' statement outside 'for' loop.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-3
For any iteration statement there shall be no more than one break or goto statement used for
loop termination [MISRA2008-6_6_4-3]
DESCRIPTION
"For any iteration statement there shall be no more than one break or goto
statement used for loop termination."
SINCE
v7.2
BENEFITS
"Restricting the number of exits from a loop is done in the interests of
good
structured programming. One break or goto statement is acceptable in a
loop
since this allows, for example, for dual outcome loops or optimal coding."
EXAMPLE
void foo( ) {
int a;
for (a = 0; a < 10; a++) { // Violation
if (a == 5) {
break;
}
if (a == 7) {
break;
}
}
}
REPAIR
void foo( ) {
int a;
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 6, Rule 6-6-4
A function shall have a single point of exit at the end of the function [MISRA2008-6_6_5-3]
DESCRIPTION
Every function should have a single point of exit.
NOTES
Calls of functions exit, abort, and _Exit from standard library stdlib.h
are detected by rule as exit points.
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
int foo(int i)
{
if (i == 0) {
return 0;
// Violation
} else if (i == 1) {
return 1;
// Violation
} else {
return 2;
// Violation
}
}
int foo2(int a) {
int result;
if (a > 0) {
return result;
}
}
REPAIR
int foo(int i)
{
int result = 0;
// Violation
if (i == 0) {
result = 0;
} else if (i == 1) {
result = 1;
} else {
result = 2;
}
return result;
// OK
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 14
2. Origin: Misra Guidelines - Rule 82
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 113
4. ISO/DIS 26262
point 8.4.4
SINCE
v7.0
NOTES
For parameters and variables of pointer type the const qualifier
should be applied to the pointer, not to the pointed object.
BENEFITS
It's safe, it's checked at compile time, and it's integrated
with C++'s type system. It also prevents future revisions
from unintentional changing the caller's data.
EXAMPLE
int foo1(int param1,
int* param2,
const int* param3)
// Violation
// Violation
// Violation - const is applied to the
// pointed object, not to the pointer
{
int var1 = 0;
// Violation
return param1 + *param2 + *param3 + var1;
}
int foo2(int param1,
// OK - param1 is modified
int* param2,
const int* param3)
// OK - param2 is modified
// OK - param3 is modified
{
int var1 = 0;
// OK - var1 is modified
param1++;
param2++;
param3++;
var1 = param1 + *param2 + *param3;
return var1;
}
REPAIR
// Fixed violations - const added
int foo1(const int param1,
int* const param2,
const int* const param3)
// OK
// OK - const is applied to the pointer
// OK - const is applied to the pointed
// object and to the pointer
{
const int var1 = 0;
// OK
return param1 + *param2 + *param3 + var1;
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc., Chapter: "Coding Style", Rule 15
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
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
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
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
REPAIR
struct Foo {
int x;
int y;
};
int Bar( const Foo &f ) {
return f.x;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Declare a type of parameter as typedef to pointer to const if the pointer is not used to modify
the addressed object [MISRA2008-7_1_2_c-3]
DESCRIPTION
The rule reports a violation if a parameter in a function prototype is
declared
as typedef to pointer to non-const object and the pointer is not used to
modify
the addressed object. Then the type of parameter could be changed to
typedef
to pointer to const object.
See also: CODSTA-14, CODSTA-CPP-43, CODSTA-CPP-53, MISRA-104
NOTES
It is not sufficient to add 'const' identifier before typedef's
name in a function declaration, because it is applied to pointer
not to pointed object.
There can already be overloaded function with parameter declared as
typedef
to pointer to const. Then changing the type of parameter to typedef to
pointer
to const will make the code non-compilable.
BENEFITS
Rule prevents unintentional change of data and improves precision in the
definition of the function interface.
EXAMPLE
typedef int* PINT;
typedef const int* CINT;
int function1(PINT ptr)
{
return (*ptr) + 1;
}
// Violation
// Violation
{
return (*ptr) + 1;
}
REPAIR
typedef int* PINT;
typedef const int* CINT;
int function1(CINT ptr)
{
return (*ptr) + 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 1, Item 3
2. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 118
4. Origin: Misra Guidelines - Rule 81
5. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-1-2
The global namespace shall only contain main, namespace declarations and extern "C"
declarations [MISRA2008-7_3_1-3]
DESCRIPTION
This rule detects the use of global variables, classes,
and global functions outside of namespaces.
BENEFITS
Prevents the use of global variables, classes, and global functions
outside namespaces. All data and functions in a file should be inside
one or more namespaces.
EXAMPLE
int var = 0;
// Violation
// Violation
REPAIR
namespace name1 {
int var = 0;
// OK
void globalfoo( ) { // OK
}
class A {
int i;
void foo();
};
}
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.11 Namespaces, AV Rule 98
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-3-1
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
4. ISO/DIS 26262
point 8.4.4
The identifier main shall not be used for a function other than the global function main
[MISRA2008-7_3_2-3]
DESCRIPTION
"main (or its equivalent) is usually the entry point to the program and is
the
only identifier which must be in the global namespace. The use of main for
other functions may not meet developer expectations."
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
namespace
{
int main ( ){} // Violation
}
REPAIR
int main ( ){}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-2
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
// file.hpp
namespace // Violation
{
extern int x;
}
REPAIR
Do not define unnamed namespaces in header files
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using namespace NS1; // Violation
void f ()
{
++j1;
}
REPAIR
typedef int int32_t;
namespace NS1
{
int32_t i1;
int32_t j1;
int32_t k1;
}
using NS1::j1;
// OK
void f ()
{
++j1;
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-4
Multiple declarations for an identifier in the same namespace shall not straddle a usingdeclaration for that identifier [MISRA2008-7_3_5-3]
DESCRIPTION
"The set of identifiers introduced by a using-declaration does not include
any
declarations that may be added by a subsequent declaration in the
namespace.
Any subsequent declarations will not be found through the usingdeclaration,
which may not be consistent with developer expectations."
SINCE
v7.2
BENEFITS
Rule prevents unexpected behaviour.
EXAMPLE
namespace NS
{
void foo( unsigned short );
}
using NS::foo;
namespace NS
{
void foo( unsigned int );
}
void some()
{
foo( 0U );
}
// Violation
REPAIR
namespace NS
{
void foo( unsigned short );
}
namespace NS
{
void foo( unsigned int );
}
// OK
using NS::foo;
void some()
{
foo( 0U );
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-3-5
SINCE
v7.2
NOTES
Rule assumes that the usage of assembler is documented if there is
a comment in the same line as 'asm' instruction or in line directly
before 'asm' instruction.
BENEFITS
Rule improves readability of code.
EXAMPLE
// Violation in line with 'asm' instruction
void foo( void )
{
asm ( "NOP" );
}
REPAIR
void foo( void )
{
// OK - comment before 'asm' instruction
asm ( "NOP" );
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-4-1
Assembler instructions shall only be introduced using the asm declaration [MISRA20087_4_2-3]
DESCRIPTION
"The asm declaration is available to all C++ implementations, allowing
a consistent mechanism to be used. However, the parameters to asm are
still implementation-defined."
Rule reports a violation if '#pragma asm', '#pragma endasm' or an
assembler instruction that form is different than "asm" is found.
SINCE
v7.2
BENEFITS
Rule improves consistency of the code.
EXAMPLE
void foo()
{
#pragma asm
"NOP";
#pragma endasm
}
// Violation
// Violation
REPAIR
void foo()
{
asm ( "NOP" ); // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
/* compilable by cl.exe g++*/
void asmCall( ) {
/* Violation */
int g = 0;
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (
"mov %eax, 0x01\n\t"
"int $0x10"
);
#endif
}
REPAIR
void asmCall( ) {
/* OK */
#ifdef _MSC_VER
__asm {
mov eax, 01h
int 10h
}
#elif __GNUC__
__asm (
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 2
2. Misra Guidelines - Rule 3
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-4-3
SINCE
v7.2
BENEFITS
"Automatic variables are destroyed at the end of the function call.
Returning a reference or pointer to such a variable allows it to be used
after its destruction, leading to undefined behaviour."
EXAMPLE
int* foo( ) {
int i;
return &i; // Violation
}
int& bar( ) {
int i;
return i; // Violation
}
REPAIR
int foo( ) {
int i = 0;
return i; // OK
}
int bar( ) {
int i = 0;
return i;
// OK
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-1
The address of an object with automatic storage shall not be assigned to another object that
may persist after the first object has ceased to exist [MISRA2008-7_5_2-3]
DESCRIPTION
"If the address of an automatic object is assigned to another automatic
object
of larger scope, or to a static object, or returned from a function then
the
object containing the address may exist beyond the time when the original
object
ceases to exist (and its address becomes invalid). For example:
int * foo( void ) {
int local_auto;
return (&local_auto);
}"
BENEFITS
Prevents loss of data
EXAMPLE
int* global;
int* foo() {
int iLocal;
static int* siLocal;
siLocal = &iLocal;
global = &iLocal;
return &iLocal;
}
void goo() {
int* piLocal;
{
int iiLocal;
piLocal = &iiLocal;
}
}
// Violation
// Violation
// Violation
// Violation
REPAIR
Do not assign local address of object to more global,
or static object or return from function.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 17
2. Origin: Misra Guidelines - Rule 106
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.22 Pointers & References, AV Rule 173
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 7, Rule 7-5-2
A function shall not return a reference or a pointer to a parameter that is passed by reference
or const reference [MISRA2008-7_5_3-3]
DESCRIPTION
"A function shall not return a reference or a pointer to a parameter that
is
passed by reference or const reference. It is implementation-defined
behaviour
whether the reference parameter is a temporary object or a reference to
the
parameter. If the implementation uses a local copy (temporary object),
this
will be destroyed when the function returns. Any attempt to use such an
object
after its destruction will lead to undefined behaviour."
SINCE
v7.2
BENEFITS
Rule prevents non-deterministic behaviour.
EXAMPLE
int* foo2 ( int& x )
{
return ( &x );
}
// Violation
REPAIR
Do not return a reference or a pointer to a parameter that is passed by
reference or const reference
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-3
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 */
/* Violation */
REPAIR
void foo1( ) {
/* empty */
}
/* OK */
void foo2( );
/* OK */
void foo3( ) {
foo2( );
}
/* 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 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
BENEFITS
Rule prevents confusion and makes source code more readable.
EXAMPLE
void foo( )
{
int* a, b;
}
// Violation
REPAIR
void foo( )
{
int* a;
int b;
}
// OK
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 39, 6 Style - 6.5 Pointers and References Rec. 26
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-0-1
Parameters in an overriding virtual function shall either use the same default arguments as
the function they override, or else shall not specify any default arguments [MISRA2008-8_3_13]
DESCRIPTION
"Virtual functions are dynamically bound, but default parameters are
statically
bound. That means that you may end up invoking a virtual function defined
in a derived class but using a default parameter value from a base class"
This rule detects cases when you redefine an inherited virtual function
with a different default parameter value.
NOTES
Rule does not check:
- functions with template parameters
- non-constant default parameter values
- default parameter values with complex expressions
BENEFITS
This rule prevents misinterpretation which value is passed as default.
EXAMPLE
class Base
{
public:
virtual void func(int i = 1);
};
class Derived: public Base
{
public:
virtual void func(int i = 0);
};
REPAIR
// Violation
class Base
{
public:
virtual void func1(int i = 1);
virtual void func2(int i = 1);
};
class Derived: public Base
{
public:
virtual void func1(int i);
virtual void func2(int i = 1);
};
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 37
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Inheritance and ObjectOriented Design", Item 38
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 95
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Prevents from a lot of potential problems with this feature.
EXAMPLE
void foo(int x, ...)
{
}
// Violation
REPAIR
Do not use functions with variable numbers of arguments.
REFERENCES
1. Misra Guidelines - Rule 69
2. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Functions - 9.1 Function Arguments - Rule 31
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 98
4. Scott Meyers and Martin Klaus, "Examining C++ Program Analyzers",
Dr. Dobbs' Journal, the February 1997,
Chapter: "Implementation", Item 23
http://www.aristeia.com/ddjpaper1_frames.html
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 108
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-1
The identifiers used for the parameters in a re-declaration of a function shall be identical to
those in the declaration [MISRA2008-8_4_2-3]
DESCRIPTION
If identifiers are given for any of the parameters, then the identifiers
used
in the declaration and definition shall be identical.
BENEFITS
Rule improves readability and clarity of code.
EXAMPLE
void foo(int a, int b);
void foo(int x, int y ) {}
/* Violation */
REPAIR
void foo(int a, int b);
void foo(int a, int b) {}
/* OK */
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. Origin: Misra Guidelines - Rule 74
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-2
All exit paths from a function with non-void return type shall have an explicit return statement
with an expression [MISRA2008-8_4_3-3]
DESCRIPTION
"All exit paths from a function with non-void return type
shall have an explicit return statement with an expression.
This expression gives the value that the function returns.
The absence of a return with an expression leads to undefined
behaviour (and the compiler may not give an error)."
NOTES
"goto" statement is considered as exit point.
The rule does not track the flow. It assumes that each path could
be reachable independently from conditions in conditional statements.
BENEFITS
Rules prevents unpredictable function behaviour.
DRAWBACKS
Rule skips "while", "for", and "catch" sections.
EXAMPLE
int foo1(int x){ // Violation
// in second 'if' statement, 'return' statement is missing
if (x==0) {
if (x==0) {
} else {
return 0;
}
} else {
return 0;
}
}
int foo2(int x){ // Violation
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;
}
}
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Function, AV Rule 114
3. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-4-3
All variables shall have a defined value before they are used [MISRA2008-8_5_1-3]
DESCRIPTION
"The intent of this rule is that all variables shall have been written to
before
they are read. This does not necessarily require initialisation at
declaration.
Ideally a static check should be performed for any automatic variables
which
might be used without having first been assigned a value"
See also: INIT-06, INIT-10, INIT-14, BD-PB-NOTINIT
NOTES
The rule assumes that local variable might be initialized
by passing its non-const pointer to an external function.
BENEFITS
Prevents reading from uninitialized variables.
EXAMPLE
void foo( ) {
int b;
b++;
}
// Violation
REPAIR
void foo( ) {
int b = 0;
b++;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Braces shall be used to indicate and match the structure in the non-zero initialization of arrays
and structures [MISRA2008-8_5_2-3]
DESCRIPTION
"ISO C requires initializer lists for arrays, structures and union types
to be
enclosed in a single pair of braces (though the behaviour if this is not
done
is undefined). The rule given here goes further in requiring the use
of additional braces to indicate nested structures.
The zero initialization of arrays or structures shall only be applied
at the top level. The non-zero initialization of arrays or structures
requires an explicit initializer for each element."
NOTES
Rule checks only up to three-level nested bracket initialization.
EXCEPTIONS
"All the elements of arrays or structures can be initialized (to zero or
NULL)
by giving an explicit initializer for the first element only. If this
method
of initialization is chosen then the first element should be initialized
to zero (or NULL), and nested braces need not be used."
BENEFITS
"This forces the programmer to explicitly consider and demonstrate the
order
in which elements of complex data types are initialized"
EXAMPLE
int y[3][2] = { 1, 2, 3, 4, 5, 6 }; // Violation
struct S {
int i;
struct T {
int j;
}t;
} s = {1, 2}; // Violation
REPAIR
int y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // OK
struct S {
int i;
struct T {
int j;
}t;
} s = {1, { 2 }}; // OK
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Misra Guidelines - Rule 31
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 144
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-2
In an enumerator list, the = construct shall not be used to explicitly initialize members other
than the first, unless all items are explicitly initialized [MISRA2008-8_5_3-3]
DESCRIPTION
"In enumerator list, the '=' construct shall not be used
to explicitly initialize members other than the first,
unless all items are explicitly initialized."
BENEFITS
Helps avoid errors and confusion.
EXAMPLE
enum TEST { /* Violation */
X = 1,
Y,
Z = 3,
};
enum TEST2 { /* Violation */
X2,
Y2 = 2,
Z2,
};
enum TEST3 { /* Violation */
X3,
Y3,
Z3 = 3,
};
REPAIR
enum TEST { /* OK */
X,
Y,
Z,
};
enum TEST2 { /* OK */
X2 = 1,
Y2,
Z2,
};
enum TEST3 { /* OK */
X3 = 1,
Y3 = 2,
Z3 = 3,
};
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 9
2. Origin: Misra Guidelines - Rule 32
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-5-3
const member functions shall not return non-const pointers or references to class-data
[MISRA2008-9_3_1-3]
DESCRIPTION
"When an object is declared with const class type, only const member
functions
can be invoked on that object. The common expectation of const member
functions
is that the state of the object may not be modified when invoking the
functions. However, returning a non-const pointer or reference to classdata
from a const function allows a modification to the conceptual state of an
object."
See also: CODSTA-CPP-06, OOP-12, OOP-36
NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.
BENEFITS
Rule prevents exposing internal state of the object to clients, so they
won't
uncontrollably modify the state of the object. Enforces data encapsulation
that
is a cornerstone of Object Oriented programming. Improves code
maintainability.
Helps const functions act const.
EXAMPLE
class Test
{
public:
Test(int & p) : _i(p)
{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1() const
{
return &_i; // Violation
}
protected:
int& GetI2() const
{
return _i; // Violation
}
int * GetI3() const
{
return _k; // Violation
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
GetI2() = 0; // Modification of possibly-const object
*(GetI3()) = 0; // Modification of possibly-const object
}
private:
int z;
};
void bar()
{
const Child c;
*(c.GetI1()) = 0; // Modification of possibly-const object
}
REPAIR
class Test
{
public:
Test(int & p) : _i(p)
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1() const
{
return &_i; // OK
}
protected:
const int& GetI2() const
{
return _i; // OK
}
const int * GetI3() const
{
return _k; // OK
}
private:
int & _i;
int * _k;
};
class Child: public Test
{
public:
Child() : Test(z)
{
}
void foo() const
{
// GetI2() = 0; // Not compilable - can't modify const object
// *(GetI3()) = 0; // Not compilable - can't modify const
object
}
private:
int z;
};
void bar()
{
const Child c;
// *(c.GetI1()) = 0; // Not compilable - can't modify const object
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
4. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 9-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Protected member functions shall not return non-const handles to class-data [MISRA20089_3_2_a-3]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a protected member function returns nonconst
reference or pointer to private class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-36
NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.
BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.
EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
int* GetI1()
{
REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()
{
return _i; // OK
}
const int * GetI3()
{
return _k; // OK
}
private:
int _i;
int * _k;
};
class Child: public Test
{
public:
void foo()
{
// *(GetI1()) = 0; // Not compilable - not possible to change
private class data
// GetI2() = 0; // Not compilable - not possible to change
private class data
// *(GetI3()) = 0; // Not compilable - not possible to change
private class data
}
};
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
Public member functions shall not return non-const handles to class-data [MISRA20089_3_2_b-3]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a public member function returns non-const
reference or pointer to private/protected class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-12
NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.
BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.
EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1()
{
return &_i; // Violation
}
int& GetI2()
{
return _i; // Violation
}
int * GetI3()
{
return _k; // Violation
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
*(t.GetI1()) = 0; // Encapsulation broken - possible to change private
class data
t.GetI2() = 0; // Encapsulation broken - possible to change private
class data
*(t.GetI3()) = 0; // Encapsulation broken - possible to change private
class data
}
REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()
{
return _i; // OK
}
const int * GetI3()
{
return _k; // OK
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
// *(t.GetI1()) = 0; // Not compilable - not possible to change private
class data
// t.GetI2() = 0; // Not compilable - not possible to change private
class data
// *(t.GetI3()) = 0; // Not compilable - not possible to change private
class data
}
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.8 Member Function Return Types - Rule 29
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
If a member function can be made static then it shall be made static, otherwise if it can be
made const then it shall be made const [MISRA2008-9_3_3-3]
DESCRIPTION
"Declaring a member function static or const limits its access
to the non-static data members."
See also: CODSTA-CPP-54
SINCE
v7.2
BENEFITS
Rule prevents unintentional modification of the data.
EXAMPLE
class A
{
public:
int foo1 ()
{
return m_s;
}
int foo2 ()
{
return m_i;
}
private:
int m_i;
static int m_s;
};
REPAIR
class A
{
public:
static int foo1 ()
{
return m_s;
}
int foo2 () const
{
return m_i;
}
// OK
// OK
private:
int m_i;
static int m_s;
};
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-3-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Note:
Rule reports a violation message on each union's declaration.
BENEFITS
Rule prevents undefined behaviour and erroneous code.
EXAMPLE
union U {
/* Violation */
int _i;
char _buf[ sizeof( int ) ];
};
REPAIR
Do not use union.
REFERENCES
1. MISRA-C:2004 Guidelines for the use of the C language in critical
systems
Chapter 6, Section 18
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 97
3. Origin: Misra Guidelines - Rule 109
Bit-fields shall be either bool type or an explicitly unsigned or signed integral type
[MISRA2008-9_6_2-3]
DESCRIPTION
"Bit-fields shall be either bool type or an explicitly unsigned or signed
integral type Using int is implementation-defined because bit-fields of
type
int can be either signed or unsigned. The use of wchar_t as a bit-field
type
is prohibited as ISO/IEC 14882:2003 does not explicitly define the
underlying
representation as signed or unsigned."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
/* Examples of incorrect code */
struct S
{
char c : 2;
// Violation
short f : 3;
// Violation
int : 0;
// Violation
};
REPAIR
/* Examples of correct code */
struct S
{
unsigned char c : 2;
// OK
signed short f : 3;
// OK
unsigned int : 0;
// OK
bool b : 4
// OK
};
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-2
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
enum Color{RED, BLUE, BLACK};
struct S
{
Color n : 2;
/* ... */
};
// Violation
REPAIR
struct S
{
unsigned int n: 2 // OK
/* ... */
};
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-3
Named bit-fields with signed integer type shall have a length of more than one bit
[MISRA2008-9_6_4-3]
DESCRIPTION
"Named bit-fields with signed integer type shall have a length of more
than one
bit. The values which may be represented by a bit-field of length one may
not
meet developer expectations. Anonymous signed bit-fields of any length are
allowed."
SINCE
v7.2
NOTES
Rule reports violations only for explicitly signed types
BENEFITS
Rule prevents the potential pitfalls and erroneous code.
EXAMPLE
struct MyStruct
{
signed int si01 : 1;
signed int si02 : 1;
};
// Violation
// Violation
REPAIR
struct MyStruct
{
signed int si01 : 2;
signed int : 1;
};
// OK
// OK
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 9, Rule 9-6-4
MRM
Memory and Resource Management
RULES
Do not allocate resources in function argument list because the order of
evaluation of a function's parameters is undefined [MRM-01-1]
Do not allocate more than one resource in a single statement [MRM-02-3]
All classes should contain the assignment operator or appropriate comment
[MRM-04-3]
All classes should contain the copy constructor or appropriate comment
[MRM-05-3]
Use the same form in corresponding calls to new/malloc and delete/free
[MRM-06-1]
Don't memcpy or memcmp non-PODs [MRM-07-3]
Do not invoke malloc/realloc for objects having constructors [MRM-08-1]
Always assign a new value to an expression that points to deallocated
memory [MRM-09-3]
Always assign a new value to global or member variable that points to
deallocated memory [MRM-10-3]
Always assign a new value to parameter or local variable that points to
deallocated memory [MRM-11-3]
Adhere to convention when writing new and delete [MRM-12-3]
Adhere to convention when writing new [MRM-13-3]
If a class defines any overload of operator new, it should provide
overloads of all three of plain, in-place, and non-throwing operator new
[MRM-14-3]
If a class defines any overload of operator new[], it should provide
overloads of all three of plain, in-place, and non-throwing operator new[]
[MRM-15-3]
If a class defines any overload of operator delete, it should provide
overloads of all three of plain, in-place, and non-throwing operator
delete [MRM-16-3]
If a class defines any overload of operator delete[], it should provide
overloads of all three of plain, in-place, and non-throwing operator
delete[] [MRM-17-3]
Do not allocate memory and expect that someone else will deallocate it
later [MRM-18-3]
Do not allocate memory and expect that someone else will deallocate it
later [MRM-19-3]
Do not allocate memory and expect that someone else will deallocate it
later [MRM-20-3]
Use objects to manage resources [MRM-21-3]
Use objects to manage resources [MRM-22-3]
Never return a dereferenced local pointer initialized by new in this
function scope [MRM-23-2]
Do not allocate resources in function argument list because the order of evaluation of a
function's parameters is undefined [MRM-01-1]
DESCRIPTION
"Make sure that all resources are owned by objects. Perform every explicit
resource allocation (e.g., new) in its own statement that immediately
gives
the allocated resource to a manager object (e.g., shared_ptr); otherwise,
you
can leak resources because the order of evaluation of a function's
parameters
is undefined."
Rule disallows resource allocation in argument list of function.
See also: MRM-02
SINCE
v7.0
BENEFITS
"Such code is unsafe. The C++ standard gives compilers great leeway to
reorder
the two expressions building the function's two arguments. In particular,
the
compiler can interleave execution of the two expressions: Memory
allocation
(by calling operator new) could be done first for both object, followed by
attempts to call the two constructors. That very nicely sets things up for
a leak because if one of the constructor calls throws an exception, then
the
other object's memory will never be released."
EXAMPLE
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
REPAIR
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
void Fun2( shared_ptr<int> p1, shared_ptr<int> p2 );
void goo( ) {
shared_ptr<int> p1( new int );
shared_ptr<int> p2( new int );
Fun2( p1, p2 );
// OK
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 13
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
"Memory allocation (by calling operator new) could be done first for both
objects, followed by attempts to call the two constructors. That very
nicely
sets things up for a leak because if one of the constructor calls throws
an
exception, then the other object's memory will never be released."
EXAMPLE
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
class Sport{};
void smartPointer( ) {
shared_ptr<Sport> sport1( new Sport ), sport2( new Sport );
Violation
//
REPAIR
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
class Sport{};
void smartPointer( ) {
shared_ptr<Sport> sport1( new Sport );
shared_ptr<Sport> sport2( new Sport );
}
// OK
// OK
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 13
All classes should contain the assignment operator or appropriate comment [MRM-04-3]
DESCRIPTION
"Ensure that your class provides sensible copying, or none at all.
The choices are:
- If copying doesn't make sense for your type, disable copy assignment by
declaring assignment operator as private unimplemented function
- If copy assignment is warranted, but correct copying behaviour differs
from
what the compiler-generated version will do, then write the function
yourself
and make it non-private
- If copying make sense and the default behaviour is correct, use the
compiler
generated version with an explicit comment, so that readers of your code
will know that you didn't miss one of the other two options by accident"
Comment should contain string "assignment operator" which is checked
insensitive.
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-05, MRM-37,
MRM-40,
MRM-47, OOP-27, OOP-30, OOP-34
BENEFITS
Prevents using compiler-generated assignment operator by accident.
EXAMPLE
class A
{
};
// Violation
class B
{
};
// Violation
class C : public B
{
};
class D
// Violation
// Violation
{
};
REPAIR
class A
// OK
{
public:
A& operator=(const A& a)
{
/* ... */
return *this;
}
};
class B
// OK
{
private:
// copying disabled
B& operator=(const B& b);
};
class C : public B
// OK
{
// copying disabled
// private assignment operator in a base class
};
class D
// OK
{
// class uses compiler-generated assignment operator
};
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
All classes should contain the copy constructor or appropriate comment [MRM-05-3]
DESCRIPTION
"Ensure that your class provides sensible copying, or none at all.
The choices are:
- If copying doesn't make sense for your type, disable copy construction
by
declaring copy constructor as private unimplemented function
- If copy construction is warranted, but correct copying behaviour differs
from
what the compiler-generated version will do, then write the function
yourself
and make it non-private
- If copying make sense and the default behaviour is correct, use the
compiler
generated version with an explicit comment, so that readers of your code
will know that you didn't miss one of the other two options by accident"
Comment should contain string "copy constructor" which is checked
insensitive.
See also: CODSTA-CPP-19, MRM-04, MRM-38, MRM-40, MRM-48, OOP-27, OOP-30,
OOP-34
BENEFITS
Prevents using compiler-generated copy constructor by accident.
EXAMPLE
class A
{
};
// Violation
class B
{
};
// Violation
class C : public B
{
};
class D
// Violation
// Violation
{
};
REPAIR
class A
{
public:
A(const A& a){}
};
// OK
class B
{
private:
// copying disabled
B(const B& b);
};
// OK
class C : public B
// OK
{
// copying disabled
// private copy constructor in a base class
};
class D
// OK
{
// class uses compiler-generated copy constructor
};
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
Use the same form in corresponding calls to new/malloc and delete/free [MRM-06-1]
DESCRIPTION
Use the same form in corresponding calls to new/malloc and delete/free.
This rule checks calls to new, delete, malloc, and free to make sure that
they
use the same form; it reports a violation if you call new and free( ).
If you do not use the same form in corresponding calls to to new, delete,
malloc, and free, an incorrect number of destructors may be called.
See also: MRM-08, MRM-09, MRM-10, MRM-11, MRM-30
SINCE
v7.0
NOTES
Rule will trigger if the same variable is allocated memory in two
different
incompatible ways in the same function.
BENEFITS
Prevents using different kinds of 'new/malloc' and 'delete/free' calls.
EXAMPLE
#include <stdlib.h>
void foo( ) {
char* ptr1 = (char*) malloc( 19 );
char* ptr2 = new char[ 10 ];
delete ptr1;
// Violation
free( ptr2 );
// Violation
}
REPAIR
#include <stdlib.h>
void foo( ) {
char* ptr1 = (char*) malloc( 19 );
char* ptr2 = new char[ 10 ];
free( ptr1 );
// OK
delete[] ptr2;
// OK
}
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Rule improves safety and reliability of code.
EXAMPLE
#include <memory.h>
class A {
int *p;
};
class B {
int *p;
};
void foo( ) {
A p1;
B p2;
memcpy( &p1, &p2, sizeof( p1 ) );
}
// Violation
REPAIR
Memcpy and memcmp should not be used.
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-
Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 96
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule ensures that all member variables are initialized.
EXAMPLE
#include <stdlib.h>
class A {
public:
A( );
};
void foo( ) {
A* a = (A*) malloc( sizeof( A ) );
a
= (A*) malloc( sizeof( A ) );
}
REPAIR
#include <stdlib.h>
class A {
public:
A( );
};
void foo( ) {
A* a = new A( );
a
= new A( );
}
// OK
// OK
// Violation
// Violation
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Always assign a new value to an expression that points to deallocated memory [MRM-09-3]
DESCRIPTION
All pointers should be set to either 0 or to a valid address immediately
after delete statement.
The rule reports a violation if directly after delete used on an
expression
there is no assignment to this expression.
The rule does not report violation only if in assignment is used exactly
the same expression as in delete statement.
See also: MRM-10, MRM-11, MRM-31
NOTES
The rule checks only complex expressions. Simple parameters and variables
are checked by rules MRM-10 and MRM-11.
EXCEPTIONS
The rule does not report violation if an expression that contains
non-static member variables and does not contain global variables
is used as operand of delete in destructor.
BENEFITS
Rule prevents accessing a pointer or a reference to a deleted object.
EXAMPLE
struct S {
int* p;
int* q;
};
void foo(S* s){
s->p = new int;
s->q = new int(5);
//....
delete s->p;// Violation - set deleted pointer in next expression
delete
s->p =
s->q =
//...
delete
struct S {
int* p;
int* q;
};
void foo(S* s){
s->p = new int;
s->q = new int(5);
//....
delete s->p;// OK
s->p = 0;
delete s->q;// OK
s->q = new int(10);
//...
delete s->q;// OK
s->q = 0;
}
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 59
Always assign a new value to global or member variable that points to deallocated memory
[MRM-10-3]
DESCRIPTION
All pointers should be set to either 0 or to a valid address immediately
after delete statement.
The rule reports a violation if directly after delete used on a global
or member variable there is no assignment to this variable.
See also: MRM-09, MRM-11, MRM-31
NOTES
Violation is not reported if delete is used on a non-static member
variable in destructor.
Some violations can be not reported on MSVC compiler
if an assignment is used before delete statement inside macro.
BENEFITS
Rule prevents accessing a pointer or a reference to a deleted object.
EXAMPLE
int* p;
int* q;
void foo(){
p = new int;
q = new int(5);
//....
delete p;// Violation - set deleted pointer in next expression
delete q;// Violation - set deleted pointer in next expression
p = 0;
q = new int(10);
//...
delete q;
// Violation - set deleted pointer to 0
}
class A {
public:
A();
~A();
void clear();
int* ptr;
};
A::A(){
ptr = new int(10);
}
void A::clear(){
delete ptr;
}
REPAIR
int* p;
int* q;
void foo(){
p = new int;
q = new int(5);
//....
delete p;// OK
p = 0;
delete q;// OK
q = new int(10);
//...
delete q;// OK
q = 0;
}
class A {
public:
A();
~A();
void clear();
int* ptr;
};
A::A(){
ptr = new int(10);
}
A::~A(){
delete ptr;
// OK - exception
}
void A::clear(){
delete ptr;
ptr = 0;
}
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 59
Always assign a new value to parameter or local variable that points to deallocated memory
[MRM-11-3]
DESCRIPTION
All pointers should be set to either 0 or to a valid address immediately
after delete statement.
The rule reports a violation if directly after delete used on
local variable there is no assignment to this variable.
See also: MRM-09, MRM-10, MRM-31
NOTES
Violation is not reported if delete is a last statement in function
(ignoring other delete and return statements).
Some violations can be not reported on MSVC compiler
if an assignment is used before delete statement inside macro.
BENEFITS
Rule prevents accessing a pointer or a reference to a deleted object.
EXAMPLE
void foo(int* p){
p = new int;
int* q = new int(5);
//....
delete p;// Violation - set deleted pointer in next expression
delete q;// Violation - set deleted pointer in next expression
p = 0;
q = new int(10);
//...
return;
}
REPAIR
void foo(int* p){
p = new int;
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 59
SINCE
v7.0
BENEFITS
Insures your 'delete' function(s) behavior that is consistent with the
default operator delete.
EXAMPLE
#include <iostream>
#include <cstddef>
class Base {
public:
static void* operator new( size_t size ) throw( std::bad_alloc );
static void operator delete( void* rawMemory, size_t size ) throw( );
};
void Base::operator delete( void* rawMemory, size_t size ) throw( ) {
Violation
if (rawMemory == 0) return;
//
//
REPAIR
#include <iostream>
#include <cstddef>
class Base {
public:
static void* operator new( size_t size ) throw( std::bad_alloc );
static void operator delete( void* rawMemory, size_t size ) throw( );
};
//
//
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
BENEFITS
If you do not adhere to convention when you write new, you may cause
confusing inconsistencies for users of your new and delete operators.
EXAMPLE
#include <stdio.h>
class A {
public:
A( );
void* operator new(size_t size) {
// Violation
// missing ifs checking proper memory allocation
return (int *)(new int);
};
};
REPAIR
#include <stdio.h>
class A {
public:
A( );
// OK
if (size==0) {
size=1;
}
return (int *)(new int);
};
};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 8, Item 51
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 8
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
If a class defines any overload of operator new, it should provide overloads of all three of
plain, in-place, and non-throwing operator new [MRM-14-3]
DESCRIPTION
"If a class defines any overload of operator new, it should provide
overloads of all three of plain, in-place, and non-throwing operator new.
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-17, MRM-16, MRM-15, MRM-32
BENEFITS
This rule prevents hiding other overloaded new operators.
EXAMPLE
#include <new>
class MyClass
// Violation - in-place new only
{
public:
static void * operator new( size_t count, void * object );
};
REPAIR
#include <new>
class MyClass
// OK - all three operators overloaded
{
public:
static void * operator new( size_t count );
static void * operator new( size_t count, std::nothrow_t nt ) throw( );
static void * operator new( size_t count, void * object );
};
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
If a class defines any overload of operator new[], it should provide overloads of all three of
plain, in-place, and non-throwing operator new[] [MRM-15-3]
DESCRIPTION
"If a class defines any overload of operator new[], it should provide
overloads of all three of plain, in-place, and non-throwing operator
new[].
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-17, MRM-16, MRM-14
BENEFITS
This rule prevents hiding other overloaded new[] operators.
EXAMPLE
#include <new>
class MyClass
// Violation - in-place new only
{
public:
static void * operator new[]( size_t count, void * object );
};
REPAIR
#include <new>
class MyClass
// OK - all three operators overloaded
{
public:
static void * operator new[]( size_t count );
static void * operator new[]( size_t count, std::nothrow_t nt ) throw(
);
static void * operator new[]( size_t count, void * object );
};
REFERENCES
If a class defines any overload of operator delete, it should provide overloads of all three of
plain, in-place, and non-throwing operator delete [MRM-16-3]
DESCRIPTION
"If a class defines any overload of operator delete,
it should provide overloads of all three of plain, in-place,
and non-throwing operator delete.
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-17, MRM-15, MRM-14
BENEFITS
This rule prevents hiding other overloaded delete operators.
EXAMPLE
#include <new>
class MyClass
// Violation
{
public:
static void operator delete(void* _Ptr) throw( );
};
REPAIR
#include <new>
class MyClass1
// OK
{
public:
static void operator delete(void* _Ptr) throw( );
static void operator delete(void* _Ptr, const std::nothrow_t&) throw( );
static void operator delete(void*, void*) throw( );
};
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 46
If a class defines any overload of operator delete[], it should provide overloads of all three of
plain, in-place, and non-throwing operator delete[] [MRM-17-3]
DESCRIPTION
"If a class defines any overload of operator delete[],
it should provide overloads of all three of plain, in-place,
and non-throwing operator delete[].
If you don't, they'll be hidden and unavailable to users of your class."
See also: MRM-16, MRM-15, MRM-14
BENEFITS
This rule prevents hiding other overloaded delete[] operators.
EXAMPLE
#include <new>
class MyClass
// Violation
{
public:
static void operator delete[](void* _Ptr) throw( );
};
REPAIR
#include <new>
class MyClass1
// OK
{
public:
static void operator delete[](void* _Ptr) throw( );
static void operator delete[](void* _Ptr, const std::nothrow_t&) throw( );
static void operator delete[](void*, void*) throw( );
};
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 46
Do not allocate memory and expect that someone else will deallocate it later [MRM-18-3]
DESCRIPTION
If local memory in global function is allocated via new it
should be deleted in this function.
See also: MRM-20, MRM-19
BENEFITS
This rule helps to ensure that all allocated memory
is being cleaned up properly.
EXAMPLE
void foo( ) {
int *var = new int( );
}
// Violation
REPAIR
void foo( ) {
int *var = new int( );
delete var;
}
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 58
Do not allocate memory and expect that someone else will deallocate it later [MRM-19-3]
DESCRIPTION
If local memory in class is allocated via new it should be deallocated
in destructor via delete.
See also: MRM-20, MRM-18
BENEFITS
This rule helps to ensure that all allocated memory is being cleaned
up properly.
EXAMPLE
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
~A( ) {}
};
// Violation
REPAIR
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
~A( ) {
delete var;
}
};
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rec. 58
Do not allocate memory and expect that someone else will deallocate it later [MRM-20-3]
DESCRIPTION
If local memory in class is allocated via new a destructor
should be defined as well.
See also: MRM-19, MRM-18
BENEFITS
This rule helps to ensure that all allocated memory is being cleaned
up properly.
EXAMPLE
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
};
// Violation
REPAIR
class A {
private:
int* var;
public:
A( ) {
var = new int( );
}
~A( ) {
delete var;
}
};
REFERENCES
// OK
SINCE
v7.0
BENEFITS
Rule prevents resource leaks by encouraging usage of RAII objects that
acquire
resources in their constructors and release them in their destructors.
EXAMPLE
#include <boost/scoped_array.hpp>
#include <memory>
void myFunction () {
std::auto_ptr<int> pInv(new int[100]);
}
REPAIR
// Violation
#include <boost/scoped_array.hpp>
#include <memory>
void myFunction()
{
boost::scoped_array<int> pFeatureButtons( new int[22] );
}
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 13
// OK
SINCE
v7.0
BENEFITS
Rule prevents resources leaks.
EXAMPLE
#include <boost/tr1/memory.hpp>
using namespace std;
using namespace tr1;
class Investment {};
Investment* createInvestment()
{
Investment * ptr = new Investment();
return ptr;
};
void myFunction()
{
Investment *pInv = createInvestment();
}
// Violation
REPAIR
#include <boost/tr1/memory.hpp>
using namespace std;
using namespace tr1;
class Investment {};
Investment* createInvestment()
{
Investment * ptr = new Investment();
return ptr;
};
void myFunction()
{
std::auto_ptr<Investment> pInv(createInvestment()); // OK
shared_ptr<Investment> pInv2(createInvestment());
// OK
}
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 13
Never return a dereferenced local pointer initialized by new in this function scope [MRM-23-2]
DESCRIPTION
Never return a reference to a local object or a dereferenced pointer
initialized by new within the function. This rule detects when you
return a reference to a local object or dereferenced pointer.
See also: MRM-24
BENEFITS
Returning a reference to a local object or a dereferenced pointer
initialized
by new within the function may cause a memory leak.
EXAMPLE
class A {
public:
A(int xval, int yval) : _x(xval), _y(yval) {}
friend A& operator+(const A& p1, const A& p2);
private:
int _x, _y;
};
A& operator+(const A& p1, const A& p2) {
A *result = new A(p1._x + p2._x, p1._y + p2._y);
return *result;
// Violation
}
REPAIR
class A {
public:
A(int xval, int yval) : _x(xval), _y(yval) {}
friend A operator+(const A& p1, const A& p2);
private:
int _x, _y;
};
A operator+(const A& p1, const A& p2) {
// 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
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
SINCE
v7.0
BENEFITS
Prevention from subtle resource leaks when exceptions are thrown.
EXAMPLE
#include <boost/shared_ptr.hpp>
#include <boost/tr1/memory.hpp>
class Widget {
public:
Widget( ){}
~Widget( ){}
void f( void );
int priority( void );
void processWidget( std::tr1::shared_ptr<Widget>pw, int priority );
};
void Widget::f( void ) {
processWidget(
std::tr1::shared_ptr<Widget>( new Widget ), priority( ) ); //
Violation
}
REPAIR
#include <boost/shared_ptr.hpp>
#include <boost/tr1/memory.hpp>
class Widget {
public:
Widget( ){}
~Widget( ){}
void f( void );
int priority( void );
void processWidget( std::tr1::shared_ptr<Widget>pw, int priority );
};
void Widget::f( void ) {
std::tr1::shared_ptr <Widget> pw( new Widget );
processWidget( pw,priority( ) );
}
// OK
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 17
BENEFITS
Writing operator delete and operator new in concert helps
prevent memory corruption and memory leaks.
EXAMPLE
#include <stdio.h>
class A {
// Violation
public:
A( ) {}
void* operator new(size_t size);
};
REPAIR
#include <stdio.h>
class A {
// OK
public:
A( ) {}
void* operator new(size_t size);
void operator delete( void* );
};
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 10
2. General Principles of Software Validation;
BENEFITS
Writing operator delete and operator new in concert helps
prevent memory corruption and memory leaks.
EXAMPLE
#include <stdio.h>
class A {
// Violation
public:
A( ) {}
void* operator new[](size_t size);
};
REPAIR
#include <stdio.h>
class A {
// OK
public:
A( ) {}
void* operator new[](size_t size);
void operator delete[]( void* );
};
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 10
NOTES
Rule described in Rule 45 of Herb Sutter & Andrei Alexandrescu
"C++ Coding Standards" has been modified to match C++ standard.
EXCEPTIONS
A declaration of a non-placement deallocation function with exactly
two parameters, the second of which has type std::size_t matches
a non-placement allocation function with one parameter.
BENEFITS
Prevents spurious memory leaks in cases when overloaded new operator
fails.
Ensures that corresponding new and delete operators share the same
assumptions.
EXAMPLE
#include <new>
class MemoryPool;
class A {
public:
void * operator new(std::size_t);
// Violation
void * operator new(std::size_t, MemoryPool&);
// Violation
void * operator new(std::size_t, float*);
// Violation
void operator delete(void*, std::size_t, float*);
};
REPAIR
#include <new>
class MemoryPool;
class A {
public:
void * operator new(std::size_t);
// OK
void * operator new(std::size_t, MemoryPool&); // OK
void * operator new(std::size_t, float*);
// OK
void operator delete(void*);
void operator delete(void*, MemoryPool&);
void operator delete(void*, float*);
};
class B {
public:
// non-placement allocation function
void * operator new(std::size_t);
// non-placement deallocation function
void operator delete(void*, std::size_t);
};
// OK
REFERENCES
ISO/IEC 14882:2003(E) C++ standard
Sections 5.3.4, 3.7.3
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 45
NOTES
Rule described in Rule 45 of Herb Sutter & Andrei Alexandrescu
"C++ Coding Standards" has been modified to match C++ standard.
EXCEPTIONS
A declaration of a non-placement deallocation function with exactly
two parameters, the second of which has type std::size_t matches
a non-placement allocation function with one parameter.
BENEFITS
Prevents spurious memory leaks in cases when overloaded new operator
fails.
Ensures that corresponding new and delete operators share the same
assumptions.
EXAMPLE
#include <new>
class MemoryPool;
class A {
public:
void * operator new[](std::size_t);
// Violation
void * operator new[](std::size_t, MemoryPool&);
// Violation
void * operator new[](std::size_t, float*);
// Violation
void operator delete[](void*, std::size_t, float*);
};
REPAIR
#include <new>
class MemoryPool;
class A {
public:
void * operator new[](std::size_t);
// OK
void * operator new[](std::size_t, MemoryPool&); // OK
void * operator new[](std::size_t, float*);
// OK
void operator delete[](void*);
void operator delete[](void*, MemoryPool&);
void operator delete[](void*, float*);
};
class B {
public:
// non-placement allocation function
void * operator new[](std::size_t);
// non-placement deallocation function
void operator delete[](void*, std::size_t);
};
// OK
REFERENCES
ISO/IEC 14882:2003(E) C++ standard
Sections 5.3.4, 3.7.3
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 45
SINCE
v7.0
NOTES
The user need to be aware, because the rule may promote security flaws
and may be not a best practice on stack short devices.
In small systems stack size is critical. It should not be defined arrays
on the stack in case of critical importance to the system.
The change of code may cause that it will be more vulnerable to a buffer
overflow attack.
BENEFITS
Rule improves efficiency of code and prevents memory leaks.
EXAMPLE
#include <string>
using std::string;
void foo( ) {
string* pStr = new string();
// some operation on pStr
delete pStr;
}
REPAIR
// Violation
#include <string>
using std::string;
void foo( ) {
string pStr = "something";
// some operation on pStr
}
REFERENCES
Recommended by ParaSoft
// OK
Freed memory shouldn't be accessed under any circumstances. Destructor should not be
called manually [MRM-31-3]
DESCRIPTION
"There are three major kinds of invalid objects:
- Destroyed objects: Typical examples are automatic objects that have gone
out
of scope and deleted heap-based objects.
- Semantically invalidated objects: Typical examples include dangling
pointers
to deleted objects (e.g., a pointer p after a delete p;) and invalidated
iterators. It is generally undefined and unsafe to do anything except
assign
another valid value to an invalidated object.
- Objects that were never valid.
Be aware of object lifetimes and validity. Never dereference an invalid
iterator
or pointer. Don't make assumptions about what delete does and doesn't do;
freed memory is freed, and shouldn't be subsequently accessed under
any circumstances. Don't try to play with object lifetime by calling
the destructor manually (e.g. obj.~T())."
The rule reports violations on the use of pointers to deleted objects
and on explicit calls of destructors.
NOTES
The rule checks only simple cases (use of variables, parameters,
a[b], a.b, a->b, or *a expressions after they were deleted).
The rule does not check a flow. It assumes that pointer to deleted object
is used if between 'delete' and an use of that pointer there is no
'case', 'default', 'break', 'return', 'throw', 'goto', exit(), abort().
BENEFITS
Rule prevents writing unsafe and error prone code.
EXAMPLE
class A {
public:
A();
~A();
};
void foo1( ) {
A obj;
obj.~A( );
}
// Violation
char* foo2( ) {
char * a = new char;
delete a;
return a;
// Violation
};
char* foo3(char * ptr){
char * a = new char;
if(a > ptr){
delete a;
(*a)++;
// Violation
} else {
(*a)++;
// OK
}
a = ptr + 1;
return a;
// OK
}
REPAIR
Don't use invalid objects.
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 99
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 70.1
BENEFITS
If you hide the global new, normal new operator functionality
will be unavailable to maintainers of your code.
EXAMPLE
#include <stdlib.h>
void ErrorHandler() {};
class A {
// Violation
public:
void* operator new(size_t size, void (*pehf)()) {
return new int[size];
}
void operator delete(void *A) {
delete A;
}
};
template<class T> class D {
// Violation
public:
void* operator new(size_t size, T (*pehf)()) {
return new int[size];
}
void operator delete(void *d) {
delete d;
}
};
void foo() {
D<void> *a = new (ErrorHandler) D<void>;
}
REPAIR
#include <stdlib.h>
void ErrorHandler() {};
class B {
// OK
public:
void* operator new(size_t size, void (*pehf)()) {
return new int[size];
}
void* operator new(size_t size) {
return new int[size];
}
void operator delete(void *A) {
delete A;
}
};
class C {
// OK
public:
void* operator new(size_t size, void (*pehf)()) {
return new int[size];
}
void* operator new(size_t size, int aa=0) {
return new int[size];
}
void operator delete(void *A) {
delete A;
}
};
template<class T> class E {// OK
public:
void* operator new(size_t size, T (*pehf)()) {
return new int[size];
}
void* operator new(size_t size) {
return new int[size];
}
void operator delete(void *e) {
delete e;
}
};
template<class T> class F {// OK
public:
void* operator new(size_t size, T (*pehf)()) {
return new int[size];
}
void* operator new(size_t size, int aa=0) {
return new int[size];
}
void operator delete(void *f) {
delete f;
}
};
void foo() {
E<void> *a = new (ErrorHandler) E<void>;
}
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 9
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
Pointer member can be deleted inside function called from destructor.
The rule checks two nested levels of function's calls.
BENEFITS
Rule prevents memory leaks now and as the code evolves in the future.
EXAMPLE
class A
{
public:
A( );
~A( );
void init();
private:
int* ptr1; //
int* ptr2; //
int* ptr3; //
int* ptr4; //
};
Violation
Violation
Violation
OK - null pointer
init();
}
void A::init(){
ptr2 = new int;
}
A::~A(){
// any delete
}
REPAIR
class A
{
public:
A( );
~A( );
void init();
void freeMem();
private:
int* ptr1; // OK
int* ptr2; // OK
int* ptr3; // OK
int* ptr4; // OK - null pointer
};
A::A() : ptr1(new int), ptr4(0){
ptr3 = new int;
init();
}
void A::init(){
ptr2 = new int;
}
void A::freeMem(){
delete ptr1;
delete ptr2;
}
A::~A(){
freeMem();
delete ptr3;
delete ptr4; // not necessary
}
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
Rule does not report a violation if result of 'new' is passed directly
to function call or 'return' statement.
BENEFITS
Prevents access to null pointer when memory is not allocated.
EXAMPLE
#include <new>
void foo()
{
char *pc;
pc = new char[10*10*10];
pc[0] = 'x';
delete[] pc;
int *p;
if(p){
/*code here*/
// Violation
}
p = new int;
// Violation
REPAIR
#include <new>
void foo()
{
char *pc;
try{
pc = new char[10*10*10];
}catch(std::bad_alloc&){}
pc[0] = 'x';
delete[] pc;
int *p = new int;
if(p){
/*code here*/
}
}
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 8, Item 49
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 7
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Never provide brackets ([]) for delete when deallocating non-arrays [MRM-35-3]
DESCRIPTION
Use the same form in corresponding calls to new and delete.
This rule checks calls to new and delete to make sure that
they use the same form; it reports a violation if you call
new and you [] when calling delete. If you do not use the
same form in corresponding calls to new and delete,
an incorrect number of destructors may be called.
See also: MRM-36
BENEFITS
Prevents using different kinds of 'new' and 'delete' calls.
EXAMPLE
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A;
delete[] a;
}
// Violation
REPAIR
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A;
delete a;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 5
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Always provide empty brackets ([]) for delete when deallocating arrays [MRM-36-3]
DESCRIPTION
Use the same form in corresponding calls to new and delete.
This rule checks calls to new and delete to make sure that
they use the same form; it reports a violation if you call
new[] but forget to use [] when calling delete. If you do
not use the same form in corresponding calls to new and delete,
an incorrect number of destructors may be called.
See also: MRM-35
BENEFITS
Prevents using different kinds of 'new' and 'delete' calls.
EXAMPLE
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A[100];
delete a;
}
// Violation
REPAIR
class A {
public:
A( ) {}
};
void foo( ) {
A *a = new A[100];
delete[] a;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 3, Item 4
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Memory Management", Item 5
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rule 51
4. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Declare an assignment operator for classes with dynamically allocated memory [MRM-37-1]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or
'delete' to deallocate its data member, has an explicitly defined
canonical
assignment operator. A canonical assignment operator returns a class
reference
type and takes a const reference of the type.
"An assignment is not inherited like other operators. If an assignment
operator
is not explicitly defined, then one is automatically defined instead.
If you perform an assignment 'b = a;' (where 'a' and 'b' are pointers)
there is
no client-defined operator= to call, so C++ generates and calls the
default
assignment operator instead.
This default assignment operator performs memberwise assignment from the
members of 'a' to the members of 'b', which for pointers is just a bitwise
copy.
There are at least two problems with this state of affairs.
First, the memory that 'b' used to point to was never deleted;
it is lost forever. This is a classic example of how a memory leak can
arise.
Second, both 'a' and 'b' now contain pointers to the same character
string.
When one of them goes out of scope, its destructor will delete the memory
still pointed to by the other."
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-38,
MRM-40, MRM-47, OOP-27, OOP-30, OOP-34
EXCEPTIONS
Rule does not report violation if there's an assignment operator in a base
class which prevents implicitly declared assignment operator in this class
from being used.
BENEFITS
"Bit-wise copying is only performed for member data having primitive
types.
One consequence of this is that bit-wise copying is performed for member
data
having pointer types. If an object manages the allocation of the instance
of
an object pointed to by a pointer member, this will probably lead to
problems:
either by invoking the destructor for the managed object more than once or
by
attempting to use the deallocated object."
EXAMPLE
class MyClass { // Violation
public:
MyClass( );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}
REPAIR
class MyClass { // OK
public:
MyClass( );
MyClass& operator=( const MyClass& );
~MyClass( ) { delete p; }
private:
int *p;
};
MyClass::MyClass( ) {
p = new int;
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 AssignmentOperators - Rule 27
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Declare a copy constructor for classes with dynamically allocated memory [MRM-38-1]
DESCRIPTION
This rule checks if a class, which uses 'new' to allocate its data member,
or 'delete' to deallocate its data member, has an explicitly defined copy
constructor.
See also: CODSTA-CPP-19, MRM-05, MRM-37, MRM-40, MRM-48, OOP-27, OOP-30,
OOP-34
EXCEPTIONS
Rule does not report violation if there's an copy constructor in a base
class which prevents implicitly declared copy constructor in this class
from being used.
BENEFITS
"A copy constructor is recommended to
is initialized using an object of the
the allocation and deallocation of an
object has a pointer to the object to
constructor),
only the value of the pointer will be
invocations
of the destructor for the same object
in a run-time error."
EXAMPLE
class MyClass{ // Violation
public:
MyClass();
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}
REPAIR
class MyClass{ // OK
public:
MyClass();
MyClass(MyClass&);
~MyClass(){ delete p; }
private:
int *p;
};
MyClass::MyClass() {
p = new int;
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 25
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Constructors,
Destructors, and Assignment Operators", Item 11
3. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 53
4. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 76
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Provide error handling for file opening errors right next to the call to fopen [MRM-39-2]
DESCRIPTION
Provide error handling for file opening errors right next to the call to
fopen.
BENEFITS
Rule prevents accessing a FILE pointer in case
of IO error which will lead to a program crash.
EXAMPLE
#include <stdio.h>
int foo(int c)
{
FILE* data = fopen("data.txt", "r"); // Violation
do {
c = getc(data);
/* ... */
} while (c != EOF);
FILE* data2;
data2 = fopen("data2.txt", "r");
do {
c = getc(data2);
/* ... */
} while (c != EOF);
if (!data2)
{
/* ... */
return 0;
}
return 1;
}
// Violation
REPAIR
#include <stdio.h>
int foo(int c)
{
FILE* data = fopen("data.txt", "r");
// OK
if (data) {
do {
c = getc(data);
/* ... */
} while (c != EOF);
} else {
printf( "File opening error" );
return 0;
}
FILE* data2;
data2 = fopen("data2.txt", "r");
if (!data2) {
printf( "File opening error" );
return 0;
} else {
do {
c = getc(data2);
/* ... */
} while (c != EOF);
}
return 1;
// OK
REFERENCES
1. http://cwe.mitre.org/data/definitions/391.html
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
EXCEPTIONS
"When any of the special functions are declared only to make
them private or virtual, but without special semantics, it doesn't
imply that the others are needed."
BENEFITS
Rule prevents from memory management problems.
EXAMPLE
class A {
public:
A( ) {}
class C {
public:
C( ) {}
C( C& ) {}
C& operator=( const C& f ) {
return *this;
}
};
REPAIR
class A {
destructor
public:
A( ) {}
A( A& ) {}
A& operator=( const A& f ) {
return *this;
}
~A( ) {}
};
class B { // OK no defined copy constructor, assignment operator and
destructor
};
class C { // OK - copy constructor, assignment operator and destructor
public:
C( ) {}
C( C& ) {}
C& operator=( const C& f ) {
return *this;
}
~C( ) {}
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 52
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
A copy constructor shall copy all data members and bases [MRM-41-2]
DESCRIPTION
"A class may contain many data members as well as exist within an
inheritance
hierarchy. Hence the copy constructor must copy all members, including
those
in base classes."
SINCE
v7.1
NOTES
The rule does not report violations on variables of class/struct type.
If a copy constructor of base class is called then the rule assumes
that all variables from a base class are copied.
BENEFITS
"Ensure data members and bases are properly handled when an object is
copied."
EXAMPLE
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:
// Violation
private:
int derived_member_1;
int derived_member_2;
};
REPAIR
class Base
{
public:
Base();
Base (int x) : base_member (x) { }
Base (const Base& rhs) : base_member (rhs.base_member) {}
private:
int base_member;
};
class Derived : public Base
{
public:
Derived (int x, int y, int z) : Base (x),
derived_member_1 (y),
derived_member_2 (z) { }
Derived(const Derived& rhs) : Base(rhs),
derived_member_1 (rhs.derived_member_1),
derived_member_2 (rhs.derived_member_2)
{
}
private:
int derived_member_1;
int derived_member_2;
};
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Call fclose() on pointer member in destructor if the pointer was used to open a file [MRM-42-2]
DESCRIPTION
This rule reports a violation message when pointer member was used to open
a file in constructor and the file is not closed in destructor.
See also: MRM-33
SINCE
v7.1
BENEFITS
Prevention of resource leaks, especially in error cases.
Releasing resources in a destructor provides a convenient means of
resource
management, especially in regards to exceptional cases. Moreover, if it is
possible that a resource could be leaked, then that resource should be
wrapped
in a class whose destructor automatically cleans up the resource.
EXAMPLE
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}
~File_ptr ()
{
}
private:
// Violation
FILE *p;
};
REPAIR
#include <iostream>
using namespace std;
class File_ptr
{
public:
File_ptr (const char *n, const char * a)
{
p = fopen(n,a);
}
~File_ptr ()
{
if (p)
{
fclose(p);
}
}
// OK
private:
FILE *p;
};
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 79
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The assignment operator must assign all members, including those in base classes [MRM-432]
DESCRIPTION
A class may contain many data members as well as exist within
an inheritance hierarchy. Hence the assignment operator must
assign all members, including those in base classes.
Rule reports a violation message if base class assignment
operator is not called or not all base classes' member variables
are assigned within derived class assignment operator.
See also: INIT-11
SINCE
v7.1
BENEFITS
Assign to all member variables in operator= function
in order to prevent data corruption.
EXAMPLE
typedef unsigned int int32;
class Base
{
public:
Base (int32 x) : base_member (x) {}
Base &operator=(const Base& rhs)
{
if (this != &rhs)
{
base_member = rhs.base_member;
}
else
{
}
return *this;
}
private:
int32 base_member;
};
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;
};
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
SINCE
v7.2
BENEFITS
Rule prevents possibility of erroneous code.
EXAMPLE
void foo(int *a[])
{
int n;
a[1] = &n;
// Violation
}
REPAIR
Do not pass address of an auto variable into caller space.
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Do not use sizeof operator on pointer type to specify the size of the memory to be allocated
via 'malloc', 'calloc' or 'realloc' function [MRM-45-3]
DESCRIPTION
Rule reports a violation message if any of the following functions:
'malloc', 'calloc', or 'realloc' is used to allocate memory and the size
of required memory is calculated using a sizeof operator with the pointer
to the type instead of actual type. Using a pointer to the type instead of
actual type as sizeof argument makes the sizeof operator return the size
of pointer (which is 4 in a 32-bit platform).
See also: PB-32
SINCE
v7.2
BENEFITS
Rule prevents incorrect memory allocation.
EXAMPLE
#include <stdlib.h>
typedef struct Str
{
int m1;
int m2;
}*pS;
void foo(int n)
{
pS var = (pS) malloc(n * sizeof(pS));
free(var);
}
REPAIR
#include <stdlib.h>
// Violation
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
2. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-131
http://cwe.mitre.org/top25/#CWE-131
SINCE
v7.2
BENEFITS
The rule prevents or decreases the danger of:
"- invoking delete for a pointer obtained via malloc/realloc,
- invoking malloc/realloc for objects having constructors,
- invoking free for anything allocated using new."
EXAMPLE
#include <malloc.h>
void foo( ) {
char* string;
char* string2;
string = (char *) malloc( 10 );
string2 = (char*) realloc( string, 12 );
free( string );
free( string2 );
/*
/*
/*
/*
Violation
Violation
Violation
Violation
REPAIR
Do not use calloc, malloc, realloc and free functions.
*/
*/
*/
*/
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 16 Memory Allocation - Rule 50
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Shifting from C to C++",
Item 3
Classes containing at least one non-static member variable should declare the assignment
operator or contain appropriate comment [MRM-47-3]
DESCRIPTION
Classes which have at least one non-static member variable should contain
the assignment operator. When behavior of the compiler-generated version
of operator is correct it should be commented. Comment should contain
string "assignment operator" which is checked insensitive.
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37,
MRM-40, MRM-48, OOP-27, OOP-30, OOP-34
SINCE
v7.3
BENEFITS
Prevents using compiler-generated assignment operator by accident.
EXAMPLE
class A
// Violation
{
private:
int* ptr;
};
class B
// Violation
{
private:
int var;
};
REPAIR
class A
// OK
{
public:
A& operator=(const A&);
private:
int* ptr;
};
class B
// OK
{
// Assignment operator is compiler generated
private:
int var;
};
REFERENCES
Recommended by ParaSoft
Classes containing at least one non-static member variable should declare the copy
constructor or contain appropriate comment [MRM-48-3]
DESCRIPTION
Classes which have at least one non-static member variable should declare
the copy constructor. When behavior of the compiler-generated version
of copy constructor is correct it should be commented. Comment should
contain
string "copy constructor" which is checked insensitive.
See also: CODSTA-CPP-19, MRM-05, MRM-38, MRM-40, MRM-47, OOP-27, OOP-30,
OOP-34
SINCE
v7.3
BENEFITS
Prevents using compiler-generated copy constructor by accident.
EXAMPLE
class A
// Violation
{
public:
A();
private:
int* ptr;
};
class B
// Violation
{
private:
int var;
};
REPAIR
class A
// OK
{
public:
A();
A(const A&);
private:
int* ptr;
};
class B
// OK
{
// Copy constructor is compiler generated
private:
int var;
};
REFERENCES
Recommended by ParaSoft
NAMING
Naming Conventions
RULES
All "#define" constants shall be in uppercase [NAMING-01-3]
In an enumerated list, list members (elements) shall be in uppercase and
names or tags for the list shall be in lowercase [NAMING-02-3]
Use lowercase for file names [NAMING-03-3]
Global prefixes should only be used for global variables [NAMING-04-3]
Begin local variable names with a lowercase letters [NAMING-05-3]
Begin global variable names with a lowercase letters [NAMING-06-3]
Begin member variable names with a lowercase letters [NAMING-07-3]
Begin all boolean type variables with 'b' [NAMING-08-3]
Begin class, struct, union, enum, and typedef names with an uppercase
letter [NAMING-09-3]
The names of abstract data types, structures, typedefs, and enumerated
types are to begin with an uppercase letter [NAMING-10-3]
The name of enumeration type shall begin with an uppercase letter and
contain a suffix '_t' at the end [NAMING-11-3]
The names of structures shall begin with an uppercase letter and contain a
suffix '_t' at the end [NAMING-12-3]
Begin constant variables with 'c' [NAMING-13-3]
Begin class data member names with 'its' [NAMING-14-3]
Begin all double type variable with 'd' [NAMING-15-3]
Begin all float type variables with 'f' [NAMING-16-3]
Begin all function names with uppercase letter [NAMING-17-3]
Begin global variable names with 'the' [NAMING-18-3]
Begin all integer type variable with 'i' [NAMING-19-3]
Functions that begin with 'is' should return boolean values [NAMING-20-3]
Begin all long integer variables with 'li' [NAMING-21-3]
Prefix a variable type 'pointer' with a 'p' character [NAMING-22-3]
Begin all short integer variables with 'si' [NAMING-23-3]
Begin all signed character variables with 'c' [NAMING-24-3]
Begin all terminated characters string variables with 'sz' [NAMING-25-3]
Begin all unsigned character type variables with 'uc' [NAMING-26-3]
Begin all unsigned integer type variables with 'ui' [NAMING-27-3]
Use lowercase letters for structure and union member names [NAMING-28-3]
Append names of non-scalar typedefs with "_t" [NAMING-29-3]
Implementation files in C always have the file name extension ".c"
[NAMING-30-3]
Do not use typenames that differ only by the use of uppercase and
lowercase letters [NAMING-31-3]
An include file for a class should have a file name of the form <class
name> + extension [NAMING-32-3]
Do not use identifiers which begin with one or two underscores (`_' or
`__') [NAMING-33-3]
Global function names should start with lowercase [NAMING-34-3]
Member function names should start with lowercase [NAMING-35-3]
Names of parameters in declaration and definition should be identical
[NAMING-36-3]
Include files in C++ always have the file name extension '.hh' [NAMING-373]
Implementation files in C++ always have the file name extension ".cc"
[NAMING-38-3]
Inline definition files always have the file name extension ".icc"
[NAMING-39-3]
Only the first word of the name of a class, structure, namespace,
enumeration, or typedef will begin with an uppercase letter [NAMING-40-3]
Header files will always have a file name extension of '.h' [NAMING-41-3]
Identifiers for constant and enumerator values shall be lowercase [NAMING42-2]
Implementation files will always have a file name extension of ".cpp"
[NAMING-43-3]
All letters contained in function and variable names will be composed
entirely of lowercase letters [NAMING-44-3]
Identifiers will not differ by mixture of case, the underscore character,
interchange of the similarly looking letters and numbers [NAMING-45-3]
The ', ", /* or // characters shall not occur in a header file name
[NAMING-46-3]
Different identifiers shall be typographically unambiguous [NAMING-47-3]
The \ character should not occur in a header file name [NAMING-48-3]
NAMING-HN
Hungarian Notation
RULES
Hungarian notation for array variables and parameters [NAMING-HN-01-3]
Hungarian notation for bool types [NAMING-HN-02-3]
Hungarian notation for bool pointer, array, or reference types [NAMING-HN03-3]
Hungarian notation for byte types [NAMING-HN-04-3]
Hungarian notation for byte pointer, array, or reference types [NAMING-HN05-3]
Hungarian notation for char types [NAMING-HN-06-3]
Hungarian notation for array of char types [NAMING-HN-07-3]
Hungarian notation for pointer, array, or reference to array of char types
[NAMING-HN-08-3]
Hungarian notation for char pointer, array, or reference types [NAMING-HN09-3]
Hungarian notation for char pointer or reference types [NAMING-HN-10-3]
Hungarian notation for constant parameters [NAMING-HN-11-3]
Hungarian notation for double-precision floating point types [NAMING-HN12-3]
Hungarian notation for double-precision floating point pointer, array, or
reference types [NAMING-HN-13-3]
Hungarian notation for dword types [NAMING-HN-14-3]
Hungarian notation for dword pointer, array, or reference types [NAMINGHN-15-3]
Hungarian notation for dynamically allocated array [NAMING-HN-16-3]
Hungarian notation for floating point types [NAMING-HN-17-3]
Hungarian notation for floating point pointer, array, or reference types
[NAMING-HN-18-3]
Hungarian notation for class declaration [NAMING-HN-19-3]
Hungarian notation for structs declaration [NAMING-HN-20-3]
Hungarian notation for ifstream type variables and parameters [NAMING-HN21-3]
Hungarian notation for int types [NAMING-HN-22-3]
Hungarian notation for int pointer, array, or reference types [NAMING-HN23-3]
Hungarian notation for istream type parameters and variables [NAMING-HN24-3]
Hungarian notation for long int types [NAMING-HN-25-3]
Hungarian notation for long double-precision floating point types [NAMINGHN-26-3]
Hungarian notation for long double-precision floating point pointer,
array, or reference types [NAMING-HN-27-3]
Hungarian notation
[NAMING-HN-28-3]
Hungarian notation
Hungarian notation
Hungarian notation
31-3]
Hungarian notation
32-3]
Hungarian notation
33-3]
Hungarian notation
Hungarian notation
Hungarian notation
Hungarian notation
[NAMING-HN-37-3]
Hungarian notation
Hungarian notation
Hungarian notation
HN-40-3]
Hungarian notation
Hungarian notation
Hungarian notation
Hungarian notation
44-3]
pointer [NAMING-HN-34-3]
reference parameters [NAMING-HN-35-3]
short int types [NAMING-HN-36-3]
short int pointer, array, or reference types
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
const int kiMAX=10;
float fTmp[kiMAX];
void foo()
{
int iTab[10];
int iTab2[kiMAX];
}
// Violation
// Violation
// Violation
REPAIR
const int kiMAX=10;
float rgfTmp[kiMAX];
void foo()
{
int rgiTab[10];
int rgiTab2[kiMAX];
}
// OK
// OK
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
bool g_bmyVar;
bool g_MyVariable;
static const bool g_skMyVariable = true;
class A {
bool m_MyVariable;
static const bool m_skMyVariable = true;
void foo( bool MyParam ) {
bool MyVariable;
static const bool skMyVariable = true;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
bool g_bMyVar;
bool g_bMyVariable;
static const bool g_skbMyVariable = true;
class A {
bool m_bMyVariable;
static const bool m_skbMyVariable = true;
void foo( bool bMyParam ) {
bool bMyVariable;
static const bool skbMyVariable = true;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
bool* g_pbmyVar;
bool* g_pMyVariable;
static const bool* g_spkMyVariable;
class A {
bool* m_pMyVariable;
static const bool* m_spkMyVariable;
void foo( bool* pMyParam ) {
bool* pMyVariable;
static const bool* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
bool* g_pbMyVar;
bool* g_pbMyVariable;
static const bool* g_spkbMyVariable;
class A {
bool* m_pbMyVariable;
static const bool* m_spkbMyVariable;
void foo( bool* pbMyParam ) {
bool* pbMyVariable;
static const bool* spkbMyVariable;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
char g_cmyVar;
char g_MyVariable;
static const char g_skMyVariable = 'a';
class A {
char m_MyVariable;
static const char m_skMyVariable = 'a';
void foo( char MyParam ) {
char MyVariable;
static const char skMyVariable = 'a';
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
char g_cMyVar;
char g_cMyVariable;
static const char g_skcMyVariable = 'a';
class A {
char m_cMyVariable;
static const char m_skcMyVariable = 'a';
void foo( char cMyParam ) {
char cMyVariable;
static const char skcMyVariable = 'a';
}
};
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
char* g_pcmyVar;
char* g_pMyVariable;
static const char* g_spkMyVariable;
class A {
char* m_pMyVariable;
static const char* m_spkMyVariable;
void foo( char* pMyParam ) {
char* pMyVariable;
static const char* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
};
REPAIR
char* g_pcMyVar;
char* g_pcMyVariable;
static const char* g_spkcMyVariable;
class A {
char* m_pcMyVariable;
static const char* m_spkcMyVariable;
void foo( char* pcMyParam ) {
char* pcMyVariable;
static const char* spkcMyVariable;
}
};
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
char g_cmyVar;
char g_MyVariable;
static const char g_skMyVariable = 'a';
class A {
char m_MyVariable;
static const char m_skMyVariable = 'a';
void foo( char MyParam ) {
char MyVariable;
static const char skMyVariable = 'a';
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
char g_cMyVar;
char g_cMyVariable;
static const char g_skcMyVariable = 'a';
class A {
char m_cMyVariable;
static const char m_skcMyVariable = 'a';
void foo( char cMyParam ) {
char cMyVariable;
static const char skcMyVariable = 'a';
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
char g_szmyVar[1];
char g_MyVariable[1];
static const char g_skMyVariable[1] = {0};
class B {
char m_MyVariable[1];
static const char m_skMyVariable[1];
void foo( char MyParam[1] ) {
char MyVariable[1];
static const char skMyVariable[1] = {0};
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
char g_szMyVar[1];
char g_szMyVariable[1];
static const char g_skszMyVariable[1] = {0};
class A {
char m_szMyVariable[1];
static const char m_skszMyVariable[1];
void foo( char szMyParam[1] ) {
char szMyVariable[1];
static const char skszMyVariable[1] = {0};
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
Hungarian notation for pointer, array, or reference to array of char types [NAMING-HN-08-3]
DESCRIPTION
For pointer, array, or reference to old-style null terminated
string variables and parameters use "sz" prefix.
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
char (*g_pszmyVar)[1];
char (*g_pMyVariable)[1];
static const char (*g_spkMyVariable)[1];
class B {
char (*m_pMyVariable)[1];
static const char (*m_spkMyVariable)[1];
void foo( char (*pMyParam)[1] ) {
char (*pMyVariable)[1];
static const char (*spkMyVariable)[1];
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
char (*g_pszMyVar)[1];
char (*g_pszMyVariable)[1];
static const char (*g_spkszMyVariable)[1];
class A {
char (*m_pszMyVariable)[1];
static const char (*m_spkszMyVariable)[1];
void foo( char (*pszMyParam)[1] ) {
char (*pszMyVariable)[1];
static const char (*spkszMyVariable)[1];
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
char* g_pcmyVar;
char* g_pMyVariable;
static const char* g_spkMyVariable;
class B {
char* m_pMyVariable;
static const char* m_spkMyVariable;
void foo( char* pMyParam ) {
char* pMyVariable;
static const char* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
char* g_pcMyVar;
char* g_pcMyVariable;
static const char* g_spkcMyVariable;
class A {
char* m_pcMyVariable;
static const char* m_spkcMyVariable;
void foo( char* pcMyParam ) {
char* pcMyVariable;
static const char* spkcMyVariable;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
char* g_cmyVar;
char* g_MyVariable;
static const char* g_skMyVariable;
class A {
char* m_MyVariable;
static const char* m_skMyVariable;
void foo( char* MyParam ) {
char* MyVariable;
static const char* skMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
char* g_cMyVar;
char* g_cMyVariable;
static const char* g_skcMyVariable;
class A {
char* m_cMyVariable;
static const char* m_skcMyVariable;
void foo( char* cMyParam ) {
char* cMyVariable;
static const char* skcMyVariable;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
void foo( const unsigned char ucLabel )
{
}
// Violation
REPAIR
void foo( const unsigned char kucLabel )
{
}
REFERENCES
// OK
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
double g_dmyVar;
double g_MyVariable;
static const double g_skMyVariable = 0.0;
class B {
double m_MyVariable;
static const double m_skMyVariable;
void foo( double MyParam ) {
double MyVariable;
static const double skMyVariable = 0.0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
double g_dMyVar;
double g_dMyVariable;
static const double g_skdMyVariable = 0.0;
class A {
double m_dMyVariable;
static const double m_skdMyVariable;
void foo( double dMyParam ) {
double dMyVariable;
static const double skdMyVariable = 0.0;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
Hungarian notation for double-precision floating point pointer, array, or reference types
[NAMING-HN-13-3]
DESCRIPTION
For double-precision floating point pointer, array,
or reference variables and parameters use "d" prefix.
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
double* g_pdmyVar;
double* g_pMyVariable;
static const double* g_spkMyVariable;
class B {
double* m_pMyVariable;
static const double* m_spkMyVariable;
void foo( double* pMyParam ) {
double* pMyVariable;
static const double* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
double* g_pdMyVar;
double* g_pdMyVariable;
static const double* g_spkdMyVariable;
class A {
double* m_pdMyVariable;
static const double* m_spkdMyVariable;
void foo( double* pdMyParam ) {
double* pdMyVariable;
// OK
// OK
// OK
//
//
//
//
OK
OK
OK
OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
// OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
long g_limyVar;
long g_MyVariable;
static const long g_skMyVariable = 0;
class A {
long m_MyVariable;
static const long m_skMyVariable;
void foo( long MyParam ) {
long MyVariable;
static const long skMyVariable = 0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
long g_liMyVar;
long g_liMyVariable;
static const long g_skliMyVariable = 0;
class A {
long m_liMyVariable;
static const long m_skliMyVariable;
void foo( long liMyParam ) {
long liMyVariable;
static const long skliMyVariable = 0;
}
};
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
long* g_plimyVar;
long* g_pMyVariable;
static const long* g_spkMyVariable;
class A {
long* m_pMyVariable;
static const long* m_spkMyVariable;
void foo( long* pMyParam ) {
long* pMyVariable;
static const long* spkMyVariable;
}
};
unsigned long* g_pdwmyVar2;
unsigned long* g_pMyVariable2;
static const unsigned long* g_spkMyVariable2;
class B {
unsigned long* m_pMyVariable;
static const unsigned long* m_spkMyVariable;
void foo( unsigned long* pMyParam ) {
unsigned long* pMyVariable;
static const unsigned long* spkMyVariable;
}
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
};
REPAIR
long* g_pliMyVar;
long* g_pliMyVariable;
static const long* g_spkliMyVariable;
class A {
long* m_pliMyVariable;
static const long* m_spkliMyVariable;
void foo( long* pliMyParam ) {
long* pliMyVariable;
static const long* spkliMyVariable;
}
};
unsigned long* g_pdwMyVar2;
unsigned long* g_pdwMyVariable2;
static const unsigned long* g_spkdwMyVariable2;
class B {
unsigned long* m_pdwMyVariable;
static const unsigned long* m_spkdwMyVariable;
void foo( unsigned long* pdwMyParam ) {
unsigned long* pdwMyVariable;
static const unsigned long* spkdwMyVariable;
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
const int kiMAX=10;
int *iGrade = new int [kiMAX];
void foo()
{
int *p=new int;
int *iNote = new int[kiMAX];
int *iMark;
iMark = new int[10];
}
// Violation
// Violation
// Violation
REPAIR
const int kiMAX=10;
int *prgiGrade = new int [kiMAX];
void foo()
{
int *p=new int;
int *prgiNote = new int[kiMAX];
int *prgiMark;
prgiMark = new int[10];
// OK
// OK
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
float g_fmyVar;
float g_MyVariable;
static const float g_skMyVariable = 0.0;
class B {
float m_MyVariable;
static const float m_skMyVariable;
void foo( float MyParam ) {
float MyVariable;
static const float skMyVariable = 0.0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
float g_fMyVar;
float g_fMyVariable;
static const float g_skfMyVariable = 0.0;
class A {
float m_fMyVariable;
static const float m_skfMyVariable;
void foo( float fMyParam ) {
float fMyVariable;
static const float skfMyVariable = 0.0;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
Hungarian notation for floating point pointer, array, or reference types [NAMING-HN-18-3]
DESCRIPTION
For floating point pointer, array, or reference
variables and parameters use "f" prefix.
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
float* g_pfmyVar;
float* g_pMyVariable;
static const float* g_spkMyVariable;
class B {
float* m_pMyVariable;
static const float* m_spkMyVariable;
void foo( float* pMyParam ) {
float* pMyVariable;
static const float* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
float* g_pfMyVar;
float* g_pfMyVariable;
static const float* g_spkfMyVariable;
class A {
float* m_pfMyVariable;
static const float* m_spkfMyVariable;
void foo( float* pfMyParam ) {
float* pfMyVariable;
static const float* spkfMyVariable;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
class Figure
{
};
// Violation
REPAIR
class CFigure
{
};
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
struct Figure
{
};
// Violation
REPAIR
struct SFigure
{
};
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
#include <fstream>
using namespace std;
ifstream NameFile;
void foo( ) {
ifstream Filename;
ifstream *pFilename;
}
// Violation
// Violation
// Violation
REPAIR
#include <fstream>
using namespace std;
ifstream ifNameFile;
void foo( ) {
ifstream ifFilename;
ifstream *pifFilename;
}
// OK
// OK
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
int g_imyVar;
int g_MyVariable;
static const int g_skMyVariable = 0;
class A {
int m_MyVariable;
static const int m_skMyVariable;
void foo( int MyParam ) {
int MyVariable;
static const int skMyVariable = 0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
int g_iMyVar;
int g_iMyVariable;
static const int g_skiMyVariable = 0;
class A {
int m_iMyVariable;
static const int m_skiMyVariable;
void foo( int iMyParam ) {
int iMyVariable;
static const int skiMyVariable = 0;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
int* g_pimyVar;
int* g_pMyVariable;
static const int* g_spkMyVariable;
class A {
int* m_pMyVariable;
static const int* m_spkMyVariable;
void foo( int* pMyParam ) {
int* pMyVariable;
static const int* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
int* g_piMyVar;
int* g_piMyVariable;
static const int* g_spkiMyVariable;
class A {
int* m_piMyVariable;
static const int* m_spkiMyVariable;
void foo( int* piMyParam ) {
int* piMyVariable;
static const int* spkiMyVariable;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
#include <istream>
using namespace std;
void foo( istream &rIn )
{
}
// Violation
REPAIR
#include <istream>
using namespace std;
void foo( istream &risIn )
{
}
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
long int g_limyVar;
long int g_MyVariable;
static const long int g_skMyVariable = 0;
class B {
long int m_MyVariable;
static const long int m_skMyVariable;
void foo( long int MyParam ) {
long int MyVariable;
static const long int skMyVariable = 0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
long int g_liMyVar;
long int g_liMyVariable;
static const long int g_skliMyVariable = 0;
class A {
long int m_liMyVariable;
static const long int m_skliMyVariable;
void foo( long int liMyParam ) {
long int liMyVariable;
static const long int skliMyVariable = 0;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
long double g_ldmyVar;
long double g_MyVariable;
static const long double g_skMyVariable = 0.0;
class B {
long double m_MyVariable;
static const long double m_skMyVariable;
void foo( long double MyParam ) {
long double MyVariable;
static const long double skMyVariable = 0.0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
long double g_ldMyVar;
long double g_ldMyVariable;
static const long double g_skldMyVariable = 0.0;
class A {
long double m_ldMyVariable;
static const long double m_skldMyVariable;
void foo( long double ldMyParam ) {
long double ldMyVariable;
static const long double skldMyVariable = 0.0;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
Hungarian notation for long double-precision floating point pointer, array, or reference types
[NAMING-HN-27-3]
DESCRIPTION
For long double-precision floating point pointer, array,
or reference variables and parameters use "ld" prefix.
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
long double* g_pldmyVar;
long double* g_pMyVariable;
static const long double* g_spkMyVariable;
class B {
long double* m_pMyVariable;
static const long double* m_spkMyVariable;
void foo( long double* pMyParam ) {
long double* pMyVariable;
static const long double* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
long double* g_pldMyVar;
long double* g_pldMyVariable;
static const long double* g_spkldMyVariable;
class A {
long double* m_pldMyVariable;
static const long double* m_spkldMyVariable;
void foo( long double* pldMyParam ) {
long double* pldMyVariable;
// OK
// OK
// OK
//
//
//
//
OK
OK
OK
OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
// OK
Hungarian notation for long int pointer, array, or reference types [NAMING-HN-28-3]
DESCRIPTION
For long int pointer, array, or reference
variables and parameters use "li" prefix.
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
long int* g_plimyVar;
long int* g_pMyVariable;
static const long int* g_spkMyVariable;
class B {
long int* m_pMyVariable;
static const long int* m_spkMyVariable;
void foo( long int* pMyParam ) {
long int* pMyVariable;
static const long int* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
long int* g_pliMyVar;
long int* g_pliMyVariable;
static const long int* g_spkliMyVariable;
class A {
long int* m_pliMyVariable;
static const long int* m_spkliMyVariable;
void foo( long int* pliMyParam ) {
long int* pliMyVariable;
static const long int* spkliMyVariable;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
class CSample
{
int iSize;
};
// Violation
REPAIR
class CSample
{
int m_iSize;
};
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
int g_nmyVar;
int g_MyVariable;
static const int g_skMyVariable = 0;
class A {
int m_MyVariable;
static const int m_skMyVariable;
void foo( int MyParam ) {
int MyVariable;
static const int skMyVariable = 0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
int g_nMyVar;
int g_nMyVariable;
static const int g_sknMyVariable = 0;
class A {
int m_nMyVariable;
static const int m_sknMyVariable;
void foo( int nMyParam ) {
int nMyVariable;
static const int sknMyVariable = 0;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
int* g_pnmyVar;
int* g_pMyVariable;
static const int* g_spkMyVariable;
class A {
int* m_pMyVariable;
static const int* m_spkMyVariable;
void foo( int* pMyParam ) {
int* pMyVariable;
static const int* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
int* g_pnMyVar;
int* g_pnMyVariable;
static const int* g_spknMyVariable;
class A {
int* m_pnMyVariable;
static const int* m_spknMyVariable;
void foo( int* pnMyParam ) {
int* pnMyVariable;
static const int* spknMyVariable;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
#include <fstream>
using namespace std;
ofstream NameFile;
// Violation
REPAIR
#include <fstream>
using namespace std;
ofstream ofNameFile;
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
#include <fstream>
using namespace std;
void foo(ostream &rOut)
{
}
// Violation
REPAIR
#include <fstream>
using namespace std;
void foo(ostream &rosOut)
{
}
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
const int kiMAX=10;
int *iGrade;
void foo()
{
int *iMark;
char * cLetter = 0;
}
// Violation
// Violation
// Violation
REPAIR
const int kiMAX=10;
int *piGrade;
void foo()
{
int *piMark;
char * pcLetter = 0;
}
// OK
// OK
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
void foo(const unsigned char &kucLabel)
{
}
// Violation
REPAIR
void foo(const unsigned char &rkucLabel)
{
}
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
short int g_simyVar;
short int g_MyVariable;
static const short int g_skMyVariable = 0;
class B {
short int m_MyVariable;
static const short int m_skMyVariable;
void foo( short int MyParam ) {
short int MyVariable;
static const short int skMyVariable = 0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
short int g_siMyVar;
short int g_siMyVariable;
static const short int g_sksiMyVariable = 0;
class A {
short int m_siMyVariable;
static const short int m_sksiMyVariable;
void foo( short int siMyParam ) {
short int siMyVariable;
static const short int sksiMyVariable = 0;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
Hungarian notation for short int pointer, array, or reference types [NAMING-HN-37-3]
DESCRIPTION
For short int pointer, array, or reference
variables and parameters use "si" prefix.
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
short int* g_psimyVar;
short int* g_pMyVariable;
static const short int* g_spkMyVariable;
class B {
short int* m_pMyVariable;
static const short int* m_spkMyVariable;
void foo( short int* pMyParam ) {
short int* pMyVariable;
static const short int* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
short int* g_psiMyVar;
short int* g_psiMyVariable;
static const short int* g_spksiMyVariable;
class A {
short int* m_psiMyVariable;
static const short int* m_spksiMyVariable;
void foo( short int* psiMyParam ) {
short int* psiMyVariable;
static const short int* spksiMyVariable;
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
static int g_iMark;
// Violation
REPAIR
static int g_siMark;
// OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
#include <string>
using namespace std;
string g_strmyVar;
string g_MyVariable;
static const string g_skMyVariable;
class A {
string m_MyVariable;
static const string m_skMyVariable;
void foo( string MyParam ) {
string MyVariable;
static const string skMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
#include <string>
using namespace std;
string g_strMyVar;
string g_strMyVariable;
static const string g_skstrMyVariable;
class A {
// OK
// OK
// OK
string m_strMyVariable;
static const string m_skstrMyVariable;
void foo( string strMyParam ) {
string strMyVariable;
static const string skstrMyVariable;
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
#include <string>
using namespace std;
string* g_pstrmyVar;
string* g_pMyVariable;
static const string* g_spkMyVariable;
class A {
string* m_pMyVariable;
static const string* m_spkMyVariable;
void foo( string* pMyParam ) {
string* pMyVariable;
static const string* spkMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
#include <string>
using namespace std;
string* g_pstrMyVar;
string* g_pstrMyVariable;
static const string* g_spkstrMyVariable;
// OK
// OK
// OK
class A {
string* m_pstrMyVariable;
static const string* m_spkstrMyVariable;
void foo( string* pstrMyParam ) {
string* pstrMyVariable;
static const string* spkstrMyVariable;
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
unsigned int g_iSize;
// Violation
// Violation
class CSample
{
unsigned int m_iStudent;
};
// Violation
// Violation
REPAIR
unsigned int g_uiSize;
// OK
// OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
void* g_pvmy;
void* g_pMyVariable;
static const void* g_skpMyVariable;
class A {
void* m_pMyVariable;
static const void* m_skpMyVariable;
void foo( void* pMyParam ) {
void* pMyVariable;
static const void* skpMyVariable;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
void* g_pvMyV;
void* g_pvMyVariable;
static const void* g_skpvMyVariable;
class A {
void* m_pvMyVariable;
static const void* m_skpvMyVariable;
void foo( void* pvMyParam ) {
void* pvMyVariable;
static const void* skpvMyVariable;
}
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
int g_imyVar;
int g_MyVariable;
static const int g_skMyVariable = 0;
class A {
int m_MyVariable;
static const int m_skMyVariable;
void foo( int MyParam ) {
int MyVariable;
static const int skMyVariable = 0;
}
};
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
// Violation
// Violation
// Violation
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
int g_iMyVar;
int g_iMyVariable;
static const int g_skiMyVariable = 0;
class A {
int m_iMyVariable;
static const int m_skiMyVariable;
void foo( int iMyParam ) {
int iMyVariable;
static const int skiMyVariable = 0;
}
};
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
// OK
// OK
// OK
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
BENEFITS
Improves readability and maintainability.
EXAMPLE
int* g_pimyVar;
int* g_pMyVariable;
static const int* g_spkMyVariable;
class A {
int* m_pMyVariable;
static const int* m_spkMyVariable;
void foo( int* pMyParam ) {
int* pMyVariable;
static const int* spkMyVariable;
}
};
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
// Violation
REPAIR
int* g_piMyVar;
// OK
int* g_piMyVariable;
// OK
static const int* g_spkiMyVariable;
// OK
class A {
int* m_piMyVariable;
// OK
static const int* m_spkiMyVariable;
// OK
void foo( int* piMyParam ) {
// OK
int* piMyVariable;
// OK
static const int* spkiMyVariable;
// OK
}
};
unsigned int* g_pwMyVar2;
// OK
unsigned int* g_pwMyVariable2;
// OK
static const unsigned int* g_spkwMyVariable2;
// OK
class B {
unsigned int* m_pwMyVariable;
// OK
static const unsigned int* m_spkwMyVariable;
// OK
void foo( unsigned int* pwMyParam ) {
// OK
unsigned int* pwMyVariable;
// OK
static const unsigned int* spkwMyVariable;
// OK
}
};
REFERENCES
http://web.mst.edu/~cpp/common/hungarian.html
BENEFITS
This convention will make the recognition of constants easier
and support future maintenance efforts.
EXAMPLE
#define max_value 255 // Violation
REPAIR
#define MAX_VALUE 255 // OK
REFERENCES
Recommended by ParaSoft
In an enumerated list, list members (elements) shall be in uppercase and names or tags for the
list shall be in lowercase [NAMING-02-3]
DESCRIPTION
In an enumerated list, list members (elements) shall be in uppercase.
The name or tag for the list shall be in lowercase. The members of a list
are equivalent to a defined constant, only the compiler is doing the
definition.
BENEFITS
Because members of enum are equivalent to a defined constant,
allows to keep naming convention of constants.
EXAMPLE
enum Color {
red,
blue,
green
};
// Violation
// Violation
// Violation
// Violation
REPAIR
enum color {
RED,
BLUE,
GREEN
};
// OK
// OK
// OK
// OK
REFERENCES
Motorola Coding Standards R-18
BENEFITS
Rule determine standard file names.
EXAMPLE
// filename: Test.c
// Violation
REPAIR
// filename: test.c
// OK
REFERENCES
Motorola Coding Standards G-2
BENEFITS
Makes code more legible.
EXAMPLE
void foo()
{
int theVar = 0; // Violation
}
REPAIR
int theVar = 0; // OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo() {
int Count;
};
// Violation
REPAIR
void foo() {
int count;
};
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13
2. Motorola Coding Standards R-20
BENEFITS
Rule improves readability of code.
EXAMPLE
int Count;
// Violation
REPAIR
int count;
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13
BENEFITS
Rule improves readability of code.
EXAMPLE
class A {
int Count;
};
// Violation
REPAIR
class A {
int count;
};
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
bool Var; // Violation
}
REPAIR
void foo()
{
bool bVar; // OK
}
REFERENCES
Recommended by ParaSoft
Begin class, struct, union, enum, and typedef names with an uppercase letter [NAMING-09-3]
DESCRIPTION
Begin class, struct, union, enum, and typedef names
with an uppercase letter.
See also: NAMING-10, NAMING-11, NAMING-12
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class myClass{}; // Violation
struct myStruct{}; // Violation
union myUnion{}; // Violation
enum myEnum{ val1, val2 }; // Violation
typedef int myInt; // Violation
REPAIR
class MyClass{}; // OK
struct MyStruct{}; // OK
union MyUnion{}; // OK
enum MyEnum{ val1, val2 }; // OK
typedef int MyInt; // OK
REFERENCES
Recommended by ParaSoft
The names of abstract data types, structures, typedefs, and enumerated types are to begin
with an uppercase letter [NAMING-10-3]
DESCRIPTION
"The names of abstract data types, structures, typedefs, and enumerated
types
are to begin with an uppercase letter. A class/struct/union is said to be
an abstract data type if it does not have any public or protected member
data."
See also: NAMING-09, NAMING-11, NAMING-12
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class
struct
union
enum
typedef
myClass
myStruct
myUnion
myEnum
int
{};
{};
{};
{ val1, val2 };
myInt;
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
MyClass
MyStruct
MyUnion
MyEnum
int
{};
{};
{};
{ val1, val2 };
MyInt;
//
//
//
//
//
OK
OK
OK
OK
OK
REPAIR
class
struct
union
enum
typedef
class myClass{
public:
void foo();
};
enum {
E1, E2
};
// OK - unnamed type
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 14
The name of enumeration type shall begin with an uppercase letter and contain a suffix '_t' at
the end [NAMING-11-3]
DESCRIPTION
The rule reports a violation if the name of enumeration type does not
begin
with an uppercase letter or is not followed by a suffix '_t'.
See also: NAMING-09, NAMING-10, NAMING-12
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
enum possibleColors1_t { RED, BLUE, GREEN };
// Violation
enum PossibleColors2
{ YELLOW, BLACK, WHITE }; // Violation
REPAIR
enum PossibleColors1_t { RED, BLUE, GREEN };
// OK
enum PossibleColors2_t { YELLOW, BLACK, WHITE }; // OK
REFERENCES
Recommended by ParaSoft
The names of structures shall begin with an uppercase letter and contain a suffix '_t' at the
end [NAMING-12-3]
DESCRIPTION
The rule reports a violation if the name of struct does not begin
with an uppercase letter or is not followed by a suffix '_t'.
See also: NAMING-09, NAMING-10, NAMING-11
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
struct Str1
{
int i;
};
struct str2_t
{
int i;
};
// Violation
// Violation
REPAIR
struct Str1_t
{
int i;
};
struct Str2_t
{
int i;
};
// OK
// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
const int Foo = 0;// Violation
REPAIR
const int cFoo = 0;// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class Foo {
private:
int bar;// Violation
};
REPAIR
class Foo {
private:
int itsBar;// OK
};
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
double Var;
}
// Violation
REPAIR
void foo()
{
double dVar;
}
// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
float Var;// Violation
}
REPAIR
void foo()
{
float fVar;// OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo();// Violation
REPAIR
void Foo();// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
int global_var;
// Violation
REPAIR
int theWindows; // OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
int Var;
}
// Violation
REPAIR
void foo()
{
int iVar;
}
// OK
REFERENCES
Recommended by ParaSoft
Functions that begin with 'is' should return boolean values [NAMING-20-3]
DESCRIPTION
Rule checks if a function that begins with 'is_' or 'is[A-Z]' return a
boolean
value.
NOTES
As boolean types are recognized typedefs which have names
begin with 'bool' (ignoring case)
BENEFITS
Improvement of legibility and clarifies what the return value means.
EXAMPLE
int
{
isPositive(int x) // Violation
return x > 0;
REPAIR
bool isPositive(int x)
{
return x > 0;
}
REFERENCES
Recommended by ParaSoft
// OK
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
long int Var;// Violation
}
REPAIR
void foo()
{
long int liVar;// OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
int *Foo;// Violation
REPAIR
int *pFoo;// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
short int Var;
}
// Violation
REPAIR
void foo()
{
short int siVar;
}
// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
signed char Var;// Violation
}
REPAIR
void foo()
{
signed char cVar;// OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
char Var[] = "\n"; // Violation
}
REPAIR
void foo()
{
char szVar[] = "\n";
}
REFERENCES
// OK
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
unsigned char Var;// Violation
}
REPAIR
void foo()
{
unsigned char ucVar;// OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo()
{
unsigned int Var;
}
// Violation
REPAIR
void foo()
{
unsigned int uiVar;
}
// OK
REFERENCES
Recommended by ParaSoft
Use lowercase letters for structure and union member names [NAMING-28-3]
DESCRIPTION
All structure and union members shall be lowercase proper. This convention
will
make the recognition of structure/union members easier.
BENEFITS
Makes code more readable
EXAMPLE
struct
int
int
int
};
date_foo2 {
datemonth;
DateDay;
// Violation
Dateyear;
// Violation
REPAIR
struct
int
int
int
};
date_foo1 {
dateMonth;
dateDay;
// OK
dateYear;
// OK
REFERENCES
Motorola Coding Standards R-19
BENEFITS
Makes code more readable.
EXAMPLE
class MyClass {
int count;
};
typedef MyClass My;// Violation
REPAIR
class MyClass {
int count;
};
typedef MyClass My_t;// OK
REFERENCES
Motorola Coding Standards R-17
Implementation files in C always have the file name extension ".c" [NAMING-30-3]
DESCRIPTION
The rule reports violations on implementation files which are used in C
language and does not have '.c' extension.
See also: NAMING-38, NAMING-41
NOTES
An implementation file is defined as any file that is not included via
#include.
BENEFITS
Rule makes source code more readable.
EXAMPLE
// file.c90
// Violation
void foo( ) {}
REPAIR
// file.c
// OK
void foo( ) {}
REFERENCES
Motorola Coding Standards R-12
Do not use typenames that differ only by the use of uppercase and lowercase letters
[NAMING-31-3]
DESCRIPTION
"Do not use typenames that differ only by the use
of uppercase and lowercase letters."
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
typedef int MyInt; // Violation
typedef int myInt; // Violation
REPAIR
typedef int MyInt; // OK
typedef int myInt2; // OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rec. 14
An include file for a class should have a file name of the form <class name> + extension
[NAMING-32-3]
DESCRIPTION
"An include file for a class should have a file name of the form
<class name> + extension. Use uppercase and lowercase letters in the same
way
as in the source code. Since class names must generally be unique within
a large context, it is appropriate to utilize this characteristic when
naming
its include file."
The rule reports a violation if in a header file is declared more than one
class
or a name of header file (ignoring extension) is not the same as a name of
class
inside.
See also: PFO-03
NOTES
A header file is defined as any file that is included via #include.
BENEFITS
Makes easy to locate a class definition using a file-based tool.
EXAMPLE
// file.cpp
#include "MyClass1.hh"
#include "MyClass2.hh"
// MyClass1.hh
class MyClass{
int i;
};
// MyClass2.hh
class MyClass1{
int i;
// Violation
// Violation
};
class MyClass2{
int i;
};
REPAIR
// file.cpp
#include "MyClass1.hh"
// MyClass1.hh
class MyClass1{
int i;
};
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.2 Naming Files - Rec. 7
Do not use identifiers which begin with one or two underscores (`_' or `__') [NAMING-33-3]
DESCRIPTION
"Do not use identifiers which begin with one or two underscores (`_' or
`__')."
See also: CODSTA-92, CODSTA-93
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
void _foo( );
// Violation
REPAIR
void foo( );
// OK
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 47
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void Foo( ) {}
// Violation
REPAIR
void foo( ) {}
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class A {
void Foo( ) {}
};
// Violation
REPAIR
class A {
void foo( ) {}
};
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 5 Assigning Names - Rule 13
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
void foo1( int a, int b );
void foo1( int x, int y ) {}
// Violation
REPAIR
void foo1( int a, int b );
void foo1( int a, int b ) {}
void foo2( int, int );
void foo2( int x, int y ) {}
// OK
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.3 Formal Arguments - Rule 32
Include files in C++ always have the file name extension '.hh' [NAMING-37-3]
DESCRIPTION
The rule reports violations on header files which are used in C++ language
and does not have '.hh' extension.
See also: NAMING-38, NAMING-41
NOTES
A header file is defined as any file that is included via #include.
BENEFITS
Rule makes source code more readable.
EXAMPLE
// file.cpp
#include "file.hpp"
// file.hpp
extern int i;
// Violation
REPAIR
// file.cpp
#include "file.hh"
// file.hh
extern int i;
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rule 1
Implementation files in C++ always have the file name extension ".cc" [NAMING-38-3]
DESCRIPTION
The rule reports violations on implementation files which are used in C++
language and does not have '.cc' extension.
See also: NAMING-37, NAMING-41
NOTES
An implementation file is defined as any file that is not included via
#include.
BENEFITS
Rule makes source code more readable.
EXAMPLE
// file.cpp
// Violation
void foo( ) {}
REPAIR
// file.cc
void foo( ) {}
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rule 2
Inline definition files always have the file name extension ".icc" [NAMING-39-3]
DESCRIPTION
"Inline definition files - files which contain definitions of inline
functions should always have the file extension ".icc"."
BENEFITS
Rule makes source code more readable.
EXAMPLE
// file.cpp
inline int sum( int a, int b ) {
return a + b;
}
// Violation
REPAIR
// file.icc
inline int sum( int a, int b ) {
return a + b;
}
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rule 3
Only the first word of the name of a class, structure, namespace, enumeration, or typedef will
begin with an uppercase letter [NAMING-40-3]
DESCRIPTION
The first word of the name of a class, structure, namespace, enumeration,
or type created with typedef will begin with an uppercase letter.
All others letters will be lowercase.
SINCE
v7.1
NOTES
If one wants to eliminate some abbreviations from checking it can be done
by
adding abbreviation string to array abb_table in rule's python method
checkNamingConvention() e.g. abb_table = ["RGB", "IBM"]
EXCEPTIONS
The first letter of a typedef name may be in lowercase if the typedef is a
class member or
when it is used as a replacement for primitive types.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class sample_Class
{
// ...
};
// Violation
REPAIR
class Sample_class
{
// ...
};
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 50
Header files will always have a file name extension of '.h' [NAMING-41-3]
DESCRIPTION
The rule reports violations on header files which does not have '.h'
extension.
See also: PREPROC-08, NAMING-37, NAMING-38
SINCE
v7.1
NOTES
A header file is defined as any file that is included via #include.
BENEFITS
Rule makes source code more readable.
EXAMPLE
// file.cpp
#include "file.hpp"
// file.hpp
extern int i;
// Violation
REPAIR
// file.cpp
#include "file.h"
// file.h
extern int i;
REFERENCES
// OK
SINCE
v7.1
BENEFITS
Although it is an accepted convention to use uppercase letters for
constants and enumerators, it is possible for third party libraries
to replace constant/enumerator names as part of the macro substitution
process (macros are also typically represented with uppercase letters).
EXAMPLE
const int Max_pressure = 100;
// Violation
enum Switch_position {Up, down}; // Violation
REPAIR
const int max_pressure = 100;
enum Switch_position {up, down};
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 52
Implementation files will always have a file name extension of ".cpp" [NAMING-43-3]
DESCRIPTION
If a file name extension is not ".h" (reserved for header file) than
it should be ".cpp" (implementation file).
Rule detects file name extensions different than ".cpp" and ".h".
".cpp" extension should be used for implementation files whereas
".h" are reserved for headers (rule NAMING-41).
See also: NAMING-41
SINCE
v7.1
NOTES
Rule is enabled for C++ only.
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
//file.cc
// Violation
REPAIR
//file.cpp
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 54
All letters contained in function and variable names will be composed entirely of lowercase
letters [NAMING-44-3]
DESCRIPTION
All letters contained in function and variable names will be composed
entirely of lowercase letters.
SINCE
v7.1
EXCEPTIONS
Constructors and destructors.
BENEFITS
Rule improves readability and maintainability.
EXAMPLE
class Sample_class
{
public:
int Some_function();
private:
int Some_variable;
};
// Violation
// Violation
REPAIR
class Sample_class
{
public:
int some_function();
private:
int some_variable;
};
// OK
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 51
Identifiers will not differ by mixture of case, the underscore character, interchange of the
similarly looking letters and numbers [NAMING-45-3]
DESCRIPTION
Identifiers will not differ by:
- Only a mixture of case
- The presence/absence of the underscore character
- The interchange of the letter 'O', with the number '0' or the letter 'D'
- The interchange of the letter 'I', with the number '1' or the letter 'l'
- The interchange of the letter 'S' with the number '5'
- The interchange of the letter 'Z' with the number '2'
- The interchange of the letter 'n' with the letter 'h'.
SINCE
v7.1
BENEFITS
Rule improves readability of code.
EXAMPLE
void foo(int paramS, int param5);
// Violation
REPAIR
void foo(int param1, int param2);
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 48
The ', ", /* or // characters shall not occur in a header file name [NAMING-46-3]
DESCRIPTION
"It is undefined behaviour if the ', ", /* or // characters are used
between < and > delimiters or the ', /* or // characters are used
between the " delimiters in a header name preprocessing token."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include "fi'le.h" // Violation
REPAIR
#include "file.h"
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-4
SINCE
v7.2
BENEFITS
Rule improves readability of code.
EXAMPLE
typedef int id1_uint32; // Violation - interchange Z and 2
short id1_uint3Z;
// Violation - interchange Z and 2
void id2_foo(
void id2_foo_(){
// Violation - presence underscore
int id5_BO;
// Violation - interchange B and 8, O and 0
int id5_80;
// Violation - interchange B and 8, O and 0
int id6_modem; // Violation - interchange rn and m
}
REPAIR
typedef int id1_uint32_t; // OK
int id1_uint32_v;
// OK
void id2_foo_1(
// OK
int id4_param1, // OK
int id4_param2
// OK
){
int id3_abc_1; // OK
int id3_ABC_2; // OK
}
int id6_modern;
// OK
void id2_foo_2(){ // OK
int id5_BO_1; // OK
int id5_80_2; // OK
int foo_2_id6_modem; // OK
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-10-1
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include "fi\\le.h" // Violation
REPAIR
#include "file.h"
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-5
OOP
Object Oriented
RULES
Base class copy constructor should be protected or public with smart
pointer as parameter [OOP-01-3]
Avoid slicing. Consider Clone instead of copying in base classes [OOP-023]
Class cannot inherit other class more than once unless it is virtual
inheritance [OOP-03-1]
Do not derive functions with the same name from more than one base class
[OOP-04-3]
Do not use multiple inheritance [OOP-05-2]
For multiple inheritance use virtual common base class [OOP-06-3]
Be wary about using multiple inheritance of classes that are not abstract
interfaces [OOP-07-1]
Do not directly access global data from a constructor [OOP-08-1]
Avoid the use of global objects in destructors [OOP-09-3]
Avoid using global data in member functions [OOP-10-2]
Avoid using the friend mechanism [OOP-11-3]
Protected member function shall not return non-const handles to private
class-data [OOP-12-3]
Do not redefine an inherited virtual function with a different default
parameter value [OOP-13-3]
Consider use composition instead of private inheritance [OOP-14-3]
Don't change default arguments of virtual functions [OOP-15-1]
Avoid calling virtual functions from constructors and destructors [OOP-161]
Write a using declaration to redeclare overloaded functions [OOP-17-4]
Avoid "public" data members [OOP-18-2]
Avoid 'protected' data members [OOP-19-2]
Avoid explicit cast from derived to a base class [OOP-20-3]
Use the virtual keyword if a subclass implements a virtual function [OOP21-3]
Define a virtual destructor in classes used as base classes which have
virtual functions [OOP-22-1]
If a class has virtual functions it shall have a virtual destructor [OOP23-2]
Make destructors virtual in base classes [OOP-24-1]
Avoid declaring virtual functions inline [OOP-25-3]
Never convert pointers to objects of a derived class to pointers to
objects of a virtual base class [OOP-26-3]
Declare copy assignment operator for class with reference or const members
[OOP-27-3]
Base class copy constructor should be protected or public with smart pointer as parameter
[OOP-01-3]
DESCRIPTION
"Sliced objects aren't good. (...)
There is a better way that portably achieves the goal of preventing
slicing
and delivers more value to boot. The more general idiomatic solution is to
make the copy constructor for base classes protected"
See also: OOP-02
EXCEPTIONS
"Some designs might require that the copy constructor of base classes
are left public. In that case, prefer passing by (smart) pointer to
passing
by reference. Passing by pointer is much less vulnerable to slicing and
unwanted temporary construction."
BENEFITS
Rule prevents using of sliced objects.
"Object slicing is automatic, invisible, and likely to bring wonderful
polymorphic designs to a screeching halt"
EXAMPLE
class A
{
public:
A(A&);
};
class B
{
private:
B(B &); // Violation
};
REPAIR
#include <memory>
using namespace std;
class C
{
public:
C(auto_ptr<C>); // OK
};
class D
{
protected:
D(D&);
};
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 54
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
EXAMPLE
#include <assert.h>
#include <typeinfo>
#include <memory>
using namespace std;
class A
{
public:
A* Clone() const
{
A* p = 0;
return p;
}
protected:
A(A&);
virtual A* DoClone() const = 0;
};
class B
{
protected:
B(B&);
};
REPAIR
#include <assert.h>
#include <typeinfo>
#include <memory>
using namespace std;
class C
{
public:
// OK
C* Clone() const
{
C* p = DoClone();
assert(typeid(p) == typeid(this));
return p;
}
protected:
C(C&);
virtual C* DoClone() const = 0;
};
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 54
Class cannot inherit other class more than once unless it is virtual inheritance [OOP-03-1]
DESCRIPTION
"Multiple inheritance is more complex than single inheritance. It can lead
to
new ambiguity issues and to the need for virtual inheritance. Any time you
have an inheritance hierarchy with more than one path between a base class
and a derived class , you must confront the question of whether you want
the
data members in the base class to be replicated for each of the paths."
See also: OOP-07, OOP-06, OOP-05, OOP-04
SINCE
v7.0
BENEFITS
"Multiple inheritance just means inheriting from more than one base class,
but
it is not uncommon for MI to be found in hierarchies that have higherlevel
base classes, too. That can lead to what is sometimes known as the "deadly
MI
diamond". (..) "
EXAMPLE
class
class
class
class
class
PreBase {};
Base: public PreBase {};
Empty {};
Intermediate: public Base, public Empty
NonEmpty: public PreBase {};
{};
REPAIR
class
class
class
class
class
PreBase {};
Base: public virtual PreBase {};
Empty {};
Intermediate: public virtual Base, public virtual Empty
NonEmpty: public virtual PreBase {};
{};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 40
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
//
//
Do not derive functions with the same name from more than one base class [OOP-04-3]
DESCRIPTION
"One of the first things to recognize is that when MI enters the
designscape,
it becomes possible to inherit the same name (e.g., function, typedef,
etc.)
from more than one base class."
Rule checks if in parent classes exist fields or methods with the same
names
that are not redefined in child class.
See also: OOP-07, OOP-06, OOP-05, OOP-03
SINCE
v7.0
BENEFITS
Rule checks possibility of ambiguity in code.
EXAMPLE
class BaseOne {
public:
int field;
};
class BaseTwo {
public:
int field;
void foo( );
};
class BaseThree {
public:
void foo( );
};
class MyClassOne: public BaseOne, public BaseTwo {};
// Violation
// Violation
REPAIR
class BaseOne {
public:
int field;
};
class BaseTwo {
public:
int field;
void foo();
};
class BaseThree {
public:
void foo();
};
class MyClassOne: public virtual BaseOne, public virtual BaseTwo {};
OK
//
//
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 40
BENEFITS
Clarity, maintainability. Following this rule prevents ambiguity when
classes
derive from one object through multiple objects as in the "diamond of
death".
EXAMPLE
class A {};
class B {};
class C : public A, public B {}; // Violation
REPAIR
class B {};
class A : public B {}; // OK
class C : public B {}; // OK
REFERENCES
Scott Meyers,
"More Effective C++: 35 New Ways to Improve Your Programs and Designs"
Chapter: Efficiency, Item 24
SINCE
v7.0
BENEFITS
Protect from no virtual multiple inheritance.
EXAMPLE
class
class
class
class
A
B
C
D
{};
: public A {};
: public A {};
: public B, public C {};
// Violation
REPAIR
class
class
class
class
A
B
C
D
{};
: virtual public A {};
: virtual public A {};
: public B, public C {};
// OK
REFERENCES
Scott Meyers,
"More Effective C++: 35 New Ways to Improve Your Programs and Designs"
Chapter: Efficiency, Item 24
Be wary about using multiple inheritance of classes that are not abstract interfaces [OOP-071]
DESCRIPTION
"Be wary about using multiple inheritance of classes that are not abstract
interfaces. Designs that use multiple inheritance can be very expressive,
but are harder to get right and easier to get wrong. In particular,
state management is particularly hard in designs using multiple
inheritance."
See also: OOP-06, OOP-05, OOP-04, OOP-03
NOTES
Rule allows for only one direct not interface parent class.
By interface class is meant class which has no member variables
and all member functions (except for destructor) are pure virtual.
BENEFITS
"Avoiding state in abstract interfaces simplifies the entire hierarchy
design."
EXAMPLE
class A {
public:
void foo1( );
};
class B {
public:
void foo2( );
};
class C: public A, public B {
};
// Violation
REPAIR
class A {
public:
void foo1( );
};
class B {
public:
virtual void foo2( ) = 0;
};
class C: public A, public B {
};
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 36
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
EXCEPTIONS
Global constants can be used in a constructor.
BENEFITS
The order of initialization of static objects defined in different
compilation
units is not defined in the C++ language definition. Therefore, accessing
global
data from a constructor may result in reading from uninitialized objects.
EXAMPLE
int globalVar;
class A {
public:
A( ) {
b = globalVar;
}
private:
int b;
};
// Violation
REPAIR
Do not use global variables in constructors.
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 7 Classes - 7.5 Constructors and Destructors - Rec. 33
BENEFITS
Rule prevents using global objects in destructors.
EXAMPLE
int globalVar = 0;
class A {
public:
~A( ) {
globalVar--;
}
};
// Violation
REPAIR
Do not use global objects in destructors.
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
from: 7 Classes - 7.5 Constructors and Destructors - Rec. 33
BENEFITS
Prevents using global references.
EXAMPLE
int globalVar = 1;
class A {
public:
void foo( ) {
// Violation
memberVar = globalVar;
}
private:
int memberVar;
};
REPAIR
Do not use global variables in member functions.
REFERENCES
By Mark Schroeder "A Practical Guide to Object-Oriented Metrics"
IT Professional, Novemeber/December, 1999, pg. 33.
BENEFITS
This rule detects if you use the friend mechanism.
EXAMPLE
int foo( );
class A {
friend int foo( );
};
// Violation
REPAIR
int foo( );
class A {}; // OK - No friend functions
REFERENCES
Recommended by ParaSoft
Protected member function shall not return non-const handles to private class-data [OOP-123]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a protected member function returns nonconst
reference or pointer to private class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-36
NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.
BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.
EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
int* GetI1()
{
REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
protected:
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()
{
return _i; // OK
}
const int * GetI3()
{
return _k; // OK
}
private:
int _i;
int * _k;
};
class Child: public Test
{
public:
void foo()
{
// *(GetI1()) = 0; // Not compilable - not possible to change
private class data
// GetI2() = 0; // Not compilable - not possible to change
private class data
// *(GetI3()) = 0; // Not compilable - not possible to change
private class data
}
};
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
Do not redefine an inherited virtual function with a different default parameter value [OOP-133]
DESCRIPTION
"Virtual functions are dynamically bound, but default parameters are
statically
bound. That means that you may end up invoking a virtual function defined
in a derived class but using a default parameter value from a base class"
This rule detects cases when you redefine an inherited virtual function
with a different default parameter value.
NOTES
Rule does not check:
- functions with template parameters
- non-constant default parameter values
- default parameter values with complex expressions
BENEFITS
This rule prevents misinterpretation which value is passed as default.
EXAMPLE
class Base
{
public:
virtual void func(int i = 1);
};
class Derived: public Base
{
public:
virtual void func(int i = 0);
};
REPAIR
class Base
// Violation
{
public:
virtual void func1(int i = 1);
virtual void func2(int i = 1);
};
class Derived: public Base
{
public:
virtual void func1(int i);
virtual void func2(int i = 1);
};
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 37
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Inheritance and ObjectOriented Design", Item 38
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 95
4. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 8, Rule 8-3-1
5. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
"Private inheritance means nothing during software design, only during
software implementation. And it is useful only in some edge cases."
EXAMPLE
class BaseEmpty {};
class BaseWithOnlyStaticData
{
public:
static int sd;
};
class BaseWithNonVirtualFunction
{
public:
int foo();
};
class Derived1: private BaseEmpty
{
public:
int v;
};
class Derived2: private BaseWithOnlyStaticData
{
public:
int v;
};
// Violation
// Violation
REPAIR
class BaseEmpty {};
class BaseWithNonStaticData
{
public:
int sd;
};
class BaseWithVirtualFunction
{
public:
virtual int foo();
};
class Intermediate: public virtual BaseEmpty {};
class Derived4: private BaseWithNonStaticData
{
// OK
public:
int v;
};
class Derived5: private Intermediate
{
public:
int v;
};
class Derived6: private BaseWithVirtualFunction
{
public:
int v;
};
// OK
// OK
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 39
BENEFITS
This rule prevents misinterpretation which value is passed as default.
EXAMPLE
class A
{
public:
virtual void foo( float x = 1 );
};
class B:public A
{
void foo( float x = 2);
};
// Violation
REPAIR
class A
{
public:
virtual void foo( float x = 1 );
};
class B:public A
{
void foo( float x = 1);
};
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Improves code reliability and maintainability, may identify runtime bugs
in the application.
EXAMPLE
class Base {
public:
Base( ) {
init_Base( );
// Violation
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
init_Base( );
// Violation
init_Derived1( );
// Violation
this->init_Derived2( ); // Violation
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}
REPAIR
class Base {
public:
Base( ) {
Base::init_Base( );
// OK
}
virtual void init_Base( );
};
class Derived : public Base {
Derived* derived;
public:
Derived( ) {
Base::init_Base( );
// OK
Derived::init_Derived1( ); // OK
derived->init_Derived2( ); // OK
}
virtual void init_Derived1( );
virtual void init_Derived2( );
};
void Base::init_Base(){}
void Derived::init_Derived1( ) {}
void Derived::init_Derived2( ) {}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 49
EXCEPTIONS
Rule checks the nearest base classes.
BENEFITS
This rule prevents hiding overloads in base function.
EXAMPLE
class A {
public:
virtual void foo( float x );
virtual void foo( float x, float y );
};
class B : public A {
// Violation
public:
void foo( float x );
};
REPAIR
class A {
public:
virtual void foo( float x );
virtual void foo( float x, float y );
};
class B : public A {
public:
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 6, Item 33
NOTES
Rule skips 'static const' variables.
BENEFITS
Prevents the use of "public" data members. Public data members can be
directly
accessed by any user code.
Using public accessor member functions to return data instead
will prevent unauthorized access.
EXAMPLE
class A {
public:
int iData;
};
// Violation
REPAIR
class A {
private:
int iData;
// OK
public:
const int accessiData( );
};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.1 Considerations Regarding Access Rights - Rule 22
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 41
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 22
4. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Design and Declaration", Item 20
5. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 67
6. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
Rule skips 'static const' variables.
BENEFITS
Prevents the use of "protected" data members. Protected data members,
while
inaccessible within their classes, can be directly accessed by other
untrusted
classes using inheritance. Using protected accessor member functions to
return
data instead will prevent unauthorized access.
EXAMPLE
class A {
protected:
int iProtectedData;
};
// Violation
REPAIR
class A {
private:
int iPrivateData;
protected:
const int accessData();
};
REFERENCES
// OK
BENEFITS
Simplifies code, protects from errors.
EXAMPLE
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = (Base *)d;
}
class Base1 {
int f();
};
class Base2 {
int f();
};
};
// Violation
// Violation
REPAIR
class Base { };
class Derived : public Base {
void Func() {
Derived *d = new Derived();
Base *b = d;
}
};
// OK - cast removed
class Base1 {
int f();
};
class Base2 {
int f();
};
class Derived1 : public Base1, public Base2 { };
int Func1() {
Derived1 *d = new Derived1();
return d->Base1::f();
// OK - scope operator used
}
class Child1 : public Base1 {};
class Child2 : public Base1 {};
void foo(Child1* c1, Child2* c2, bool b) {
Base1* p = 0;
if (b) {
p = c1;
// OK - code rewritten
} else {
p = c2;
// OK - code rewritten
}
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 181
BENEFITS
Readability, as well as more intuitive behavior for deep inheritance
hierarchies, in that functions that are virtual in a base class will
remain virtual in all inherited classes.
EXAMPLE
class A {
public:
virtual int foo( );
};
class B : public A {
public:
int foo( );
};
int B::foo() {
return 5;
}
REPAIR
class A {
public:
virtual int foo( );
};
// Violation
class B : public A {
public:
virtual int foo( );
};
// OK
int B::foo() {
return 5;
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-3-2
Define a virtual destructor in classes used as base classes which have virtual functions [OOP22-1]
DESCRIPTION
All classes which are used as base classes and which have virtual
functions
must define a virtual destructor. If a class, having virtual functions but
without virtual destructors, is used as a base class, there may be a
surprise
if pointers to the class are used. If such a pointer is assigned to an
instance
of a derived class and if delete is then used on this pointer, only the
base
class' destructor will be invoked. If the program depends on the derived
class'
destructor being invoked, the program will fail.
See also: OOP-23, OOP-24, OOP-31
BENEFITS
Define a virtual destructor in order to prevent data corruption.
EXAMPLE
class Base
// Violation
{
public:
virtual void foo( );
~Base( );
};
class Derived : public Base{};
REPAIR
class Base
// OK
{
public:
virtual void foo( );
virtual ~Base( );
};
class Derived : public Base{};
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.5 Constructors and Destructors - Rule 26
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 78
BENEFITS
Prevents memory leaks in derived classes. A class that has virtual
functions
is intended to be used as a base class, so it should have a virtual
destructor
to guarantee that the destructor will be called when the derived object
is referenced through a pointer to the base class.
EXAMPLE
class A
// Violation
{
public:
~A( );
virtual int foo( );
};
REPAIR
class A
// OK
{
public:
virtual ~A( );
virtual int foo( );
};
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 7
BENEFITS
Prevents using non-virtual destructor in base classes.
EXAMPLE
class BaseB
{
public:
BaseB() {}
~BaseB() {}
};
// Violation
REPAIR
class BaseA
{
public:
BaseA() {}
virtual ~BaseA() {}
};
class Derived : public BaseA
{
public:
// OK
Derived() {};
~Derived() {};
};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 7
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Constructors, Destructors, and Assignment Operators", Item 14
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
Inline destructors defined in interfaces are allowed.
By interface class is meant class which has no member variables
and all member functions (except for destructor) are pure virtual.
"All the destructor calls except for the initial resolution are resolved
statically. Without making the base class virtual destructors inline,
we cannot take advantage of this. If the hierarchy is deep and there
are many objects destructed, it make much of a difference"
EXCEPTIONS
The rule does not report violations on template functions.
Compiler must know the body of a template function. It instantiates and
puts
implementation in each object that uses it. Thus, removing inline does not
help
because virtual table is still put in each object that uses it.
BENEFITS
"The size of a class's vtbl is proportional to the number of virtual
functions
declared for that class (including those it inherits from its base
classes).
There should be only one virtual table per class, so the total amount of
space
required for virtual tables is not usually significant, but if you have a
large
number of classes or a large number of virtual functions in each class,
you may
find that the vtbls take a significant bite out of your address space.
If all virtual functions in a class are declared inline, the most
implementations
then generate a copy of the class's in every object file that uses it.
In large systems, this can lead to programs containing hundreds or
thousands
of copies of a class's!"
EXAMPLE
class A
{
public:
A(int i) : _i( i ) {}
virtual ~A( ) {}
// Violation
private:
int _i;
};
REPAIR
class A
{
public:
A( int i ) : _i( i ) {}
virtual ~A( );
// OK
private:
int _i;
};
A::~A() { }
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 24
2. Jose Lajoie and Stanley Lippman, "Standard C++ Programming:
Virtual Functions and Inlining", September 2000
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Never convert pointers to objects of a derived class to pointers to objects of a virtual base
class [OOP-26-3]
DESCRIPTION
"Never convert pointers to objects of a derived class to
pointers to objects of a virtual base class."
BENEFITS
Rule prevents casting to pointer to virtual base class.
EXAMPLE
class Base {};
class Derived: virtual Base {};
void foo( ) {
Base *b = 0;
Derived *d = 0;
b = (Base*) d;
};
// Violation
REPAIR
Do not convert pointers to objects of a derived class to
pointers to objects of a virtual base class.
REFERENCES
1. Origin: Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 13 Type Conversions - Rule 45
2. ISO/DIS 26262
point 8.4.4
Declare copy assignment operator for class with reference or const members [OOP-27-3]
DESCRIPTION
"If you want to support assignment in a class containing a reference
member,
you must define the copy assignment operator yourself. Compilers behave
similarly for classes containing const members. It's not legal to modify
const
members, so compilers are unsure how to treat them during an implicitly
generated assignment function. Finally, compilers reject implicit copy
assignment operators in derived classes that inherit from base classes
declaring the copy assignment operator private. After all, compilergenerated
copy assignment operators for derived classes are supposed to handle base
class
parts, too but in doing so, they certainly can't invoke member functions
the derived class has no right to call."
See also: CODSTA-CPP-02, CODSTA-CPP-21, CODSTA-CPP-24, MRM-04, MRM-37,
MRM-40,
MRM-47, OOP-30, OOP-34
SINCE
v7.0
BENEFITS
Support assignment in a class containing a reference
member or const members.
EXAMPLE
class Sample {
public:
Sample( const int value );
const int s;
};
// Violation
REPAIR
class Sample {
public:
Sample( const int value );
Sample& operator=( Sample& );
const int s;
};
// OK
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 5
A pointer to a class may not be converted to a pointer of a second class unless the first class
inherits from the second [OOP-28-4]
DESCRIPTION
This rule detects if a pointer to a class is converted to a pointer of a
second
class when the first class does not inherit from the second.
Such "invalid" downcasting can result in wild pointers and other
disasters.
Use virtual function calls instead.
See also: MISRA2004-11_4
BENEFITS
This rule prevents memory and data corruption.
EXAMPLE
class A {};
class B {};
class D : public B {};
void
{
A
B
D
b
d
}
main( )
*a;
*b;
*d;
= (B*) a; // Violation
= (D*) b; // Violation
REPAIR
class A {};
class B {};
class D : public B {};
void main( )
{
A *a;
B *b;
D *d;
b = (B*) d; // OK
}
REFERENCES
1. ISO/DIS 26262
point 8.4.4
A pointer to an abstract class shall not be converted to a pointer of a class that inherits from
that abstract class [OOP-29-1]
DESCRIPTION
The rule reports a violation if a pointer to an abstract class is cast
to a pointer to class that inherits from that abstract class.
See also: OOP-49, OOP-50
BENEFITS
Prevents illegal casts and ensures that abstraction layer is not bypassed.
EXAMPLE
class B
{
public:
virtual int foo( ) = 0;
};
class D : public B
{
public:
int foo( );
};
void
{
B
D
d
}
main( )
*b;
*d;
= (D*) b; // Violation
REPAIR
Do not cast a pointer to an abstract class to a pointer
to a class that inherits from it.
REFERENCES
1. ISO/DIS 26262
point 8.4.4
Declare the copy constructor and copy assignment operator private not in class itself, but in a
specifically designed base class [OOP-30-3]
DESCRIPTION
"It's possible to move the link-time error up to compile time (always a
good
thing earlier error detection is better than later) by declaring the
copy
constructor and copy assignment operator private not in class itself,
but in a base class specifically designed to prevent copying.
This works, because compilers will try to generate a copy constructor
and a copy assignment operator if anybody even a member or friend
function tries to copy a class object."
See also: CODSTA-CPP-02, CODSTA-CPP-19, CODSTA-CPP-21, CODSTA-CPP-24, MRM04,
MRM-05, MRM-37, MRM-38, MRM-40, MRM-47, MRM-48, OOP-27, OOP-34
SINCE
v7.0
BENEFITS
"The compiler-generated versions of these functions will try
to call their base class counterparts, and those calls will be
rejected, because the copying operations are private in the
base class."
EXAMPLE
class HomeForSale {
public:
HomeForSale();
private:
HomeForSale(const HomeForSale&);
// Violation
HomeForSale& operator=(const HomeForSale&); // Violation
};
REPAIR
class Uncopyable {
protected:
Uncopyable() {}
~Uncopyable() {}
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
};
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 2, Item 6
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 68
Make base class destructors public and virtual, or protected and nonvirtual [OOP-31-1]
DESCRIPTION
"If deletion through a pointer to a base class should be allowed,
then base class destructor must be public and virtual.
Otherwise, it should be protected and nonvirtual."
See also: OOP-22, OOP-23, OOP-24
EXCEPTIONS
Base class has no virtual functions and is not meant to be used
polymorphically.
BENEFITS
Rule prevents undefined behaviour of the delete calls on base class
pointers pointing to a derived object.
EXAMPLE
class Base {
public:
virtual int foo();
~Base(); // Violation
};
class Derived : public Base {};
REPAIR
class Base {
public:
virtual int foo();
protected:
~Base(); // OK
};
class Derived : public Base {};
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Construction, Destruction, and Copying", Rule 50
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
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) {}
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) {}
};
// 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
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
BENEFITS
Allowing casts down the inheritance hierarchy leads to maintenance
problems,
and downcasting from a base class is always illegal.
EXAMPLE
class Base {};
class Derived: public Base {};
class Derived2: public Derived {};
void foo() {
Base *pb;
Derived *pd = (Derived *) pb;
Base *pb2;
Derived *pd2 = (Derived2 *) pb2;
// Violation
// Violation
REPAIR
class Base {};
void foo() {
Base *pb0;
Base *pd0 = (Base *) pb0;
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Public member functions shall not return non-const handles to private/protected class-data
[OOP-36-3]
DESCRIPTION
"By implementing class interfaces with member functions the implementation
retains more control over how the object state can be modified and helps
to allow a class to be maintained without affecting clients.
Returning a handle to class-data allows for clients to modify the state
of the object without using any interfaces."
The rule reports a violation if a public member function returns non-const
reference or pointer to private/protected class-data.
See also: CODSTA-CPP-06, CODSTA-CPP-77, OOP-12
NOTES
Handle to class-data is:
- reference to member variable/member function
- pointer to member variable/member function
- pointer/reference to data allocated in constructor or deallocated in
destructor
Static variables are not considered class-data.
BENEFITS
Rule improves encapsulation and prevents from data changing in ways not
intended by the class designer.
EXAMPLE
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
int* GetI1()
{
return &_i; // Violation
}
int& GetI2()
{
return _i; // Violation
}
int * GetI3()
{
return _k; // Violation
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
*(t.GetI1()) = 0; // Encapsulation broken - possible to change private
class data
t.GetI2() = 0; // Encapsulation broken - possible to change private
class data
*(t.GetI3()) = 0; // Encapsulation broken - possible to change private
class data
}
REPAIR
class Test
{
public:
Test()
{
_k = new int; // makes data pointed by _k a "class-data"
}
const int* GetI1()
{
return &_i; // OK
}
const int& GetI2()
{
return _i; // OK
}
const int * GetI3()
{
return _k; // OK
}
private:
int _i;
int * _k;
};
void foo()
{
Test t;
// *(t.GetI1()) = 0; // Not compilable - not possible to change private
class data
// t.GetI2() = 0; // Not compilable - not possible to change private
class data
// *(t.GetI3()) = 0; // Not compilable - not possible to change private
class data
}
REFERENCES
1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 29
3. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 28
4. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 42
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.8 Member Function Return Types - Rule 29
6. MISRA C++:2008 Guidelines for the use of the C++ language in critical
BENEFITS
Rule improves greater flexibility, compile-time insulation,
shorter compile times and less weirdness.
EXAMPLE
class Base {
public:
virtual int virtualFoo( );
int publicData;
protected:
int protectedData;
};
class DerivedA : public Base {
public:
virtual int moo();
};
// Violation
// Violation
REPAIR
class Base {
public:
virtual int virtualFoo( );
int publicData;
protected:
int protectedData;
};
class DerivedA : public Base {
public:
virtual int virtualFoo( );
};
// OK
// OK
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 34
If a class destructor is called and the class has virtual functions it shall have a virtual
destructor [OOP-38-1]
DESCRIPTION
Declaring virtual destructors in classes that have virtual functions
causes
the compiler to call destructors for each class from which the object
inherits.
If a class has virtual functions, has no virtual destructor, and class
destructor is called then the rule reports a violation message.
See also: OOP-23
SINCE
v7.1
BENEFITS
Prevents memory leaks in derived classes. A class that has virtual
functions
is intended to be used as a base class, so it should have a virtual
destructor
to guarantee that the destructor will be called when the derived object
is referenced through a pointer to the base class.
EXAMPLE
class A
{
public:
~A( );
// Violation
virtual int foo( );
};
void foo1(A* a)
{
delete a;
}
REPAIR
class A
{
public:
virtual ~A( );
// OK
virtual int foo( );
};
void foo1(A* a)
{
delete a;
}
REFERENCES
Recommended by Parasoft.
A stateful virtual base shall be explicitly declared in each derived class that accesses it [OOP39-2]
DESCRIPTION
A stateful virtual base shall be explicitly declared
in each derived class that accesses it.
SINCE
v7.1
BENEFITS
"Explicitly declaring a stateful virtual base at each level in a hierarchy
(where that base is used), documents that fact that no assumptions
can be made with respect to the exclusive use of the data contained
within the virtual base."
EXAMPLE
class
class
class
class
class
class
AA
BB
CC
DD
EE
FF
{};
: virtual AA {};
: virtual AA {};
: BB{};
// Violation
: CC{};
// Violation
: DD{};
// Violation
REPAIR
class
class
class
class
class
class
AA
BB
CC
DD
EE
FF
{};
: virtual AA {};
: virtual AA {};
: BB, virtual AA {};
// OK
: CC, virtual AA {};
// OK
: DD, EE, virtual AA {}; // OK
REFERENCES
SINCE
v7.1
BENEFITS
Hierarchies based on abstract classes tend to focus designs toward
producing clean interfaces, keep implementation details out of
interfaces, and minimize compilation dependencies while allowing
alternative implementations to coexist.
EXAMPLE
class B
{
};
class A: public B // Violation
{
};
REPAIR
class B
{
public:
virtual int foo()=0;
/* ... */
};
class A: public B // OK
{
};
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 87
A base class shall not be both virtual and non-virtual in the same hierarchy [OOP-41-2]
DESCRIPTION
A base class shall not be both virtual and non-virtual
in the same hierarchy.
SINCE
v7.1
BENEFITS
Hierarchy becomes easier to comprehend and use.
EXAMPLE
class A {};
class B : virtual A {};
class C : B, A {};
// Violation
REPAIR
class A {};
class B : virtual A {};
class C : B, virtual A {};
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 89
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 10, Rule 10-1-3
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The copy assignment operator shall be declared protected or private in an abstract class
[OOP-42-3]
DESCRIPTION
"An abstract class represents the interface part of a hierarchy.
Invoking the copy assignment operator from the top of such
a hierarchy bypasses the underlying implementation resulting
in only the base subobjects being copied."
SINCE
v7.2
NOTES
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.
BENEFITS
"Making the abstract copy assignment operator protected allows
access from the derived classes but not from outside the hierarchy.
Making the copy assignment operator private is a common idiom used
to restrict copying objects of the class type."
EXAMPLE
typedef int int32_t;
class B1
{
public:
virtual void f( ) = 0;
B1 & operator= ( B1 const & rhs );
};
REPAIR
// Violation
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-2
A virtual function shall only be overridden by a pure virtual function if it is itself declared as
pure virtual [OOP-43-4]
DESCRIPTION
"A virtual function shall only be overridden by a pure
virtual function if it is itself declared as pure virtual."
SINCE
v7.2
BENEFITS
Rule prevents writing a code contrary to developer expectations.
EXAMPLE
class A
{
public:
virtual void foo ( );
};
class B: public A
{
public:
virtual void foo ( ) = 0; // Violation
};
REPAIR
Do not override non-pure virtual functions by pure virtual functions
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-3
There shall be no more than one definition of each virtual function on each path through the
inheritance hierarchy [OOP-44-3]
DESCRIPTION
"The main aim of this rule is clarity for maintainers and reviewers,
by ensuring that the version of a function that can be executed from
any point in a class hierarchy is unambiguous."
SINCE
v7.2
EXCEPTIONS
"Destructors may be declared virtual in multiple members of a class
hierarchy.
If a function is declared pure and defined in the same class, then that
definition is ignored for this rule."
BENEFITS
"Additionally, where classes form a diamond hierarchy, call
by dominance may occur resulting in a call to a function that
is inconsistent with developer expectations.
This rule also prevents call by dominance."
EXAMPLE
/* Examples of incorrect code */
class A
{
public:
virtual void f1 ( );
virtual void f2 ( ) { }
};
void A::f1 ( )
{
}
class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
};
void B::f2 ( )
{
}
// Violation
// Violation
REPAIR
/* Examples of
class A
{
public:
virtual
virtual
virtual
};
void A::f2 ( )
{
}
correct code */
void f1 ( );
void f2 ( ) = 0;
~A(){}
class B : public A
{
public:
virtual void f1 ( ) { }
virtual void f2 ( );
virtual ~B(){}
};
void B::f2 ( )
{
}
// OK
// OK
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-3-1
All constructors that are callable with a single argument of fundamental type shall be declared
explicit [OOP-45-3]
DESCRIPTION
"All constructors that are callable with a single argument
of fundamental type shall be declared explicit."
SINCE
v7.2
NOTES
The following types are fundamental: bool, char, short, int,
long, long long, float, double, long double, wchar_t.
BENEFITS
Rule prevents the constructor from being used to implicitly
convert from a fundamental type to the class type.
EXAMPLE
class C
{
public:
C ( int a ) // Violation
{
}
};
REPAIR
class C
{
public:
explicit C ( int a ) // OK
{
}
};
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-3
A copy constructor shall only initialize its base classes and the non-static members of the
class of which it is a member [OOP-46-3]
DESCRIPTION
"If a compiler implementation detects that a call to a copy constructor
is redundant, then it is permitted to omit that call, even if the copy
constructor has a side effect other than to construct a copy of the
object."
Rule reports a violation if global or static member variable is modified
within a copy constructor.
SINCE
v7.2
NOTES
Rule checks only one nested level of function call.
BENEFITS
"It is therefore important to ensure that a copy constructor does not
modify
the program state as the number of such modifications may be
indeterminate."
EXAMPLE
class A
{
public:
A ( A const & rhs )
: m_i ( rhs.m_i )
{
++m_static;
// Violation
}
private:
int m_i;
static int m_static;
};
REPAIR
Do not modify global or static member variable within a copy constructor.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-8-1
SINCE
v7.2
BENEFITS
"The use of virtual base classes can introduce a number of undefined
and potentially confusing behaviours."
EXAMPLE
class B {};
class D: public virtual B {}; // Violation
REPAIR
Do not inherit from virtual base classes
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 10, Rule 10-1-1
SINCE
v7.2
BENEFITS
"By implementing class interfaces with member functions,
the implementation retains more control over how the object
state can be modified, and helps to allow a class to be
maintained without affecting clients.
EXAMPLE
typedef signed int int32_t;
class C
{
public:
int32_t b; // Violation
protected:
int32_t c; // Violation
};
REPAIR
typedef signed int int32_t;
class C
{
private:
int32_t b; // OK
int32_t c; // OK
protected:
const int32_t access_b();
const int32_t access_c();
};
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 11, Rule 11-0-1
Casts from a base class to a derived class should not be performed on polymorphic types
[OOP-49-1]
DESCRIPTION
"A downcast occurs when a class type is converted to another class type
that is derived from that first class.
Polymorphism enables strong abstraction between the interface and
implementation
of a hierarchy. Explicit casts bypass this layer of abstraction resulting
in higher levels of coupling and dependency."
"Casting from a base class to a derived class is unsafe unless some
mechanism
is provided to ensure that the cast is legitimate."
See also: OOP-29, OOP-50
SINCE
v7.2
BENEFITS
Prevents illegal casts and ensures that abstraction layer is not bypassed.
EXAMPLE
class B
{
public:
virtual int foo( );
};
class D : public B
{
public:
int foo( );
};
void main( )
{
B *b;
D *d;
d = (D*) b; // Violation
}
REPAIR
Do not cast a pointer to a base class to a pointer to a class
that inherits from it.
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-3
A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of
dynamic_cast [OOP-50-3]
DESCRIPTION
"Since the virtualness of inheritance is not a property of a base class,
the layout of a derived class object, referenced through a virtual base
pointer, is unknown at compile time."
"Casting from a virtual base to a derived class, using any means
other than dynamic_cast has undefined behaviour.
The behaviour for dynamic_cast is defined."
See also: OOP-29, OOP-49
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviours.
EXAMPLE
// The code is not compilable with all compilers
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = static_cast<D*>(pB); // Violation
}
REPAIR
class B {
public:
virtual int foo();
};
class D: public virtual B {
public:
virtual int foo(){}
};
void fun(){
D d;
B *pB = &d;
D *pD = dynamic_cast<D*>(pB);
}
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.23 Type Conversions, AV Rule 179
2. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-2
Use namespace instead of class or structure containing only static functions [OOP-51-5]
DESCRIPTION
Use namespace instead of class or structure containing only static
functions.
Rule reports a violation if a non-template class contains only static
functions
and does not inherit from any base class.
SINCE
v7.3
BENEFITS
Rule prevents creating unnecessary objects.
EXAMPLE
class A{
static void foo(){}
};
// Violation
void foo(){
A a;
a.foo();
}
REPAIR
namespace A{
void foo(){}
};
void foo(){
A::foo();
}
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
OPT
Optimization
RULES
Declare variables as locally as possible [OPT-01-3]
Avoid unused local variables [OPT-02-4]
Eliminate unused parameters [OPT-03-2]
Prefer canonical form of ++ and --. Prefer calling the prefix forms [OPT04-3]
Eliminate unused private member variables [OPT-05-3]
Avoid unnecessary local variables [OPT-06-4]
Prefer "a @= b" than "a = a @ b", where "@" is +, -, *, /, % [OPT-07-3]
Prefer "a @= b" than "a = a @ b", where "@" is &, |, ^, <<, >> [OPT-08-3]
Remove unnecessary '== true' in Boolean functions [OPT-09-5]
Do not declare variables in "if", "for", "while", and "do while" statement
[OPT-10-3]
If a file-level static variable is used/referenced in one function only
then include that variable in the function itself [OPT-11-3]
If a file-level static variable is used/referenced in one class only then
include that variable in the class itself [OPT-12-3]
Declare member variables in the descending size order [OPT-13-3]
Pass objects by reference instead of by value [OPT-14-3]
Consider overloading to avoid implicit type conversions [OPT-15-3]
Global function containing recursion, loops or virtual function call
should not be inlined [OPT-16-3]
Avoid inline constructors and destructors [OPT-17-3]
Member function containing recursion or loops should not be inlined [OPT18-3]
Consider using op= instead of stand-alone op [OPT-19-3]
Postpone variable definitions as long as possible [OPT-20-3]
Every switch statement shall have at least one non-empty case clause [OPT21-3]
Useless case statement shall not be permitted [OPT-22-3]
Trivial accessor and mutator functions should be inlined [OPT-23-4]
Trivial forwarding functions should be inlined [OPT-24-4]
Only functions with 1 or 2 statements should be considered candidates for
inline functions [OPT-25-4]
Variables will not be introduced until they can be initialized with
meaningful values [OPT-26-2]
The number of accessor and mutator functions should be minimized [OPT-274]
'strlen' function should not be used to check string against NULL/non-NULL
[OPT-28-3]
Redundant explicit cast to the same type is not allowed [OPT-29-4]
BENEFITS
Rule prevents from making the program harder to understand and maintain.
EXAMPLE
void foo( ) {
int a;
{
a = 0;
}
}
// Violation
REPAIR
void foo( ) {
{
int a;
a = 0;
// OK
}
}
void fooOK1(){
int b;
if (b > 0) {
b = 10;
}
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#11
From: 11 Variables - Rule 41
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 18
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-4-1
4. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 6
NOTES
Objects can perform some actions in their constructors. Even if they are
not
used later they might have done their job during creation. This rule does
not
consider such objects as "used" and will report a violation.
BENEFITS
Eliminating unused local variables increases efficiency and legibility.
EXAMPLE
class A {
public:
void displBalance();
};
void foo( ) {
A a;
}
// Violation
int func(int j) {
int i = 0; // Violation
return j;
}
REPAIR
class A {
public:
void displBalance( );
};
void foo( ) {
A a;
a.displBalance( );
}
int func(int j) {
int i = j + 1;
return i;
}
// OK
// OK
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3
EXCEPTIONS
The rule does not report violations on virtual functions and on functions
that are used as callback (an address of function is taken in translation
unit).
The rule does not report violations on unnamed parameters.
BENEFITS
The rule improves legibility and increases efficiency of code.
EXAMPLE
int foo(int i, int k) {
i = 5 * i;
return i;
}
REPAIR
int foo(int i) {
i = 5 * i;
return i;
}
// OK
// Exceptions
class A {
public:
virtual void foo(int a);
};
// Violation
// OK - virtual function
// OK - unnamed parameter
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison Wesley, (31 Mar 1996), Item 6
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Prefer canonical form of ++ and --. Prefer calling the prefix forms [OPT-04-3]
DESCRIPTION
"In calling code, prefer using the prefix form unless you actually need
the
original value returned by the postfix version. The prefix form is
semantically
equivalent, just as much typing, and often slightly more efficient by
creating
one less object. It is not premature optimization; it is avoiding
premature
pessimization"
BENEFITS
Using rule helps to avoid potential inefficiencies resulting from a need
to
make a temporary copy of a variable or object when postfix form is used.
EXAMPLE
class SampleMemberO {
public:
SampleMemberO& operator++();
SampleMemberO& operator++(int x);
};
class SampleGlobalO {};
SampleGlobalO& operator++( SampleGlobalO& t );
SampleGlobalO& operator++( SampleGlobalO& t, int x );
void myFunction()
{
SampleMemberO obj_MemberO;
SampleGlobalO obj_GlobalO;
obj_MemberO++;
obj_GlobalO++;
// Violation
// Violation
int i=0;
i++;
// Violation
REPAIR
class SampleMemberO {
public:
int m;
SampleMemberO& operator++();
SampleMemberO& operator++(int x);
};
class SampleGlobalO {};
SampleGlobalO& operator++( SampleGlobalO& t );
SampleGlobalO& operator++( SampleGlobalO& t, int x );
void myFunction()
{
SampleMemberO obj_MemberO;
SampleGlobalO obj_GlobalO;
++obj_MemberO;
++obj_GlobalO;
// OK
// OK
int i=0;
++i;
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 28
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
3. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Operators", Item 6
NOTES
The rule does not report violations if a class
contains a member function with non accessible body.
BENEFITS
Eliminating unused private member variables
improves legibility and increases efficiency.
EXAMPLE
class A {
public:
A();
int foo(A
private:
int x; //
int y; //
int z; //
};
a);
Violation
Violation
Violation
REPAIR
class A {
public:
A();
int foo(A
private:
int x; //
int y; //
int z; //
};
a);
OK
OK
OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
NOTES
The rule does not report violations on variables of type class/struct that
have explicitly declared constructor or destructor.
BENEFITS
Eliminating local variables that are not useful increases efficiency
and legibility of code.
EXAMPLE
class A {
};
int func(int p) {
A a;
// Violation
int i = 0; // Violation
i = p;
i++;
return p;
}
REPAIR
class A {
public:
A();
};
int func(int p) {
A a;
// OK - implicit call of constructor can cause additional
action
int i = 0; // OK
i = p;
i++;
return i;
}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 0, Rule 0-1-3
BENEFITS
Rule improves legibility and increases efficiency of code.
EXAMPLE
void
x
x
x
x
x
}
foo( int
= x + 2;
= x - 2;
= x * 2;
= x / 2;
= x % 2;
x,
//
//
//
//
//
int y ) {
Violation
Violation
Violation
Violation
Violation
x,
//
//
//
//
//
int y ) {
OK
OK
OK
OK
OK
REPAIR
void
x
x
x
x
x
}
foo( int
+= 2;
-= 2;
*= 2;
/= 2;
%= 2;
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Prefer "a @= b" than "a = a @ b", where "@" is &, |, ^, <<, >> [OPT-08-3]
DESCRIPTION
Prefer "a @= b" than "a = a @ b", where "@" is &, |, ^, <<, >>.
See also: OPT-07
BENEFITS
Rule improves legibility and increases efficiency of code.
EXAMPLE
void
x
x
x
x
x
}
REPAIR
void
x
x
x
x
x
}
foo( int
&= 2;
|= 2;
^= 2;
<<= 2;
>>= 2;
x, int y ) {
// OK
// OK
// OK
// OK
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Checking bool expressions equality with true is unnecessary.
Removing unnecessary "== true"s increases legibility and efficiency.
EXAMPLE
bool isPositive(int a);
bool foo()
{
return isPositive(5) == true;
}
// Violation
REPAIR
bool isPositive(int a);
bool foo1()
{
return isPositive(5);
}
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Do not declare variables in "if", "for", "while", and "do while" statement [OPT-10-3]
DESCRIPTION
Do not declare variables in "if", "for", "while", and "do while"
statement.
Because such declaration can lead to confusion caused by hiding variable
with
the same name in more global context.
BENEFITS
Rule prevents writing ambiguous code.
EXAMPLE
int bar( int& x );
int lookup( int& x );
void foo( int x ){
if (x == 0) {
int y;
// Violation
y = bar(x);
}
for (x = 0; x < 2;x++) {
int y;
// Violation
y = lookup(x);
bar(y);
}
while (x < 0) {
int y;
// Violation
y = bar(x);
}
do {
int y;
// Violation
y = bar(x);
} while (x < 0);
}
REPAIR
REFERENCES
Recommended by ParaSoft
If a file-level static variable is used/referenced in one function only then include that variable
in the function itself [OPT-11-3]
DESCRIPTION
If a file-level static variable is used/referenced in one function only,
it is
better to include that variable in the function itself, as if the function
is
never called, the memory for variable will not be allocated.
See also: OPT-12
SINCE
v7.0
NOTES
In C++, global variables which are defined as a const are static by
default.
Ref: ISO14882/1998 (3.5 #3, 7.1.5.1 #2)
BENEFITS
Memory optimization and clarity of intent expression/maintainability.
EXAMPLE
static int i = 0;
const int ci = 0;
// Violation
// Violation only for C++
void clear( ) {
i = ci;
}
REPAIR
void clear( ) {
static int i = 0;
// OK
const int ci = 0;
i = ci;
// OK
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
If a file-level static variable is used/referenced in one class only then include that variable in
the class itself [OPT-12-3]
DESCRIPTION
If a file-level static variable is used/referenced in one class only,
it is better to include that variable in the class itself.
See also: OPT-11
SINCE
v7.0
BENEFITS
Memory optimization and clarity of intent expression/maintainability.
EXAMPLE
static int s;
const static int cs = 0;
// Violation
// Violation
class A
{
void foo1(int i) {
s = i + cs;
}
void foo2(int j ) {
s = j + cs;
}
};
REPAIR
class A
{
static int s;
const static int cs = 0;
void foo1(int i) {
s = i + cs;
// OK
// OK
}
void foo2(int j ) {
s = j + cs;
}
};
REFERENCES
Recommended by ParaSoft
SINCE
v7.0
NOTES
Following dependencies assumed for this rule:
bool < long
float < double < long double
char < short < int < reference, pointer, long
arrays and objects should be at the beginning of the list of members
BENEFITS
Rule helps to minimize memory consumption
EXAMPLE
class A {
char c;
short int si;
int i;
void* p;
long int li;
// Violation
// Violation
// Violation
// Violation
};
REPAIR
class A {
long int li;
void* p;
int i;
short int si;
char c;
};
REFERENCES
http://www.ddj.com/184406427
// OK
EXCEPTIONS
There also may be a situation where the object is so small that it would
be
more efficient to pass by value instead of by reference.
Due to C++'s type system and the fact that QString, RWCString and CString
are implicitly shared, they may be treated like ints or other basic types.
BENEFITS
Improves code consistency and runtime performance.
EXAMPLE
class A {
public:
const A violation( A a ) {
value
return a;
}
};
REPAIR
class A {
public:
const A& valid( const A &a ) {
return a;
}
// OK
// OK
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Design Style", Rule 09
2. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 20
3. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 22
4. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 1, Item 3
5. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 9 Function - 9.1 Function Arguments - Rec. 43
6. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125
7. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule prevents from creating temporary objects and improve optimization of
code.
EXAMPLE
class A {
public:
A(int);
bool operator==(A);
};
class C;
class B {
public:
B(C);
bool operator==(B);
};
class C {
public:
bool operator==(B);
};
// Violation
// Violation
class AR {
public:
AR(int&);
bool operator==(AR&);
};
class CR;
class BR {
public:
BR(CR&);
bool operator==(BR&);
};
// Violation
// Violation
class CR {
public:
bool operator==(BR&);
};
REPAIR
class A {
public:
A(int);
bool operator==(A);
bool operator==(int);
};
bool operator==(int, A);
class C;
class B {
public:
B(C);
bool operator==(B);
bool operator==(C);
};
class C {
public:
bool operator==(B);
};
class AR {
// OK
// OK
public:
AR(int&);
// OK
bool operator==(AR&);
bool operator==(int&);
};
bool operator==(int&, AR&);
class CR;
class BR {
public:
BR(CR&);
bool operator==(BR&);
bool operator==(CR&);
};
// OK
class CR {
public:
bool operator==(BR&);
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Functions and Operators", Rule 29
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Global function containing recursion, loops or virtual function call should not be inlined [OPT16-3]
DESCRIPTION
"Limit most inlining to small, frequently called functions."
Rule disallows inlining for:
global functions with loops, global recursion functions,
global functions with virtual function calls.
See also: OPT-17, OPT-18
SINCE
v7.0
BENEFITS
"This facilitates debugging and binary upgradeability,
minimizes potential code bloat, and maximizes the chances
of greater program speed."
EXAMPLE
inline void sampleFunction( int p ) {
for (int i = 0; i < 10; i++) {
p = p + i;
}
}
inline void otherFunction( ) {
otherFunction( );
}
// Violation
// Violation
REPAIR
void sampleFunction( int p ) {
for (int i = 0; i < 10; i++) {
p = p + i;
}
}
// OK
void otherFunction( ) {
otherFunction( );
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison Wesley,
(C) 2005 Pearson Education, Inc., Chapter: "Classes and Functions:
Implementation", Item 33
NOTES
Inline destructors defined in interfaces are allowed.
By interface class is meant class which has no member variables
and all member functions (except for destructor) are pure virtual.
BENEFITS
"This facilitates debugging and binary upgradeability, minimizes potential
code bloat, and maximizes the chances of greater program speed."
EXAMPLE
class MyClass1 {
public:
inline MyClass1( );
inline ~MyClass1( );
private:
int i;
};
class MyClass2 {
public:
MyClass2( ) {};
~MyClass2( ) {};
private:
int i;
// Violation
// Violation
// Violation
// Violation
};
class MyClass3 {
public:
MyClass3( );
~MyClass3( );
private:
int i;
};
// Violation
// Violation
inline MyClass3::MyClass3(){}
inline MyClass3::~MyClass3(){}
REPAIR
class MyClass1 {
public:
MyClass1( );
~MyClass1( );
private:
int i;
};
// OK
// OK
MyClass1::MyClass1(){}
MyClass1::~MyClass1(){}
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 33
3. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 7 Classes - 7.2 Inline Functions - Rec. 31
SINCE
v7.0
BENEFITS
"This facilitates debugging and binary upgradeability, minimizes potential
code bloat, and maximizes the chances of greater program speed."
EXAMPLE
class MyClass{
public:
void foo1( ) {
foo1( );
}
// Violation
REPAIR
class MyClass {
// Violation
public:
void foo1( ) ;
void foo2( int i );
};
// OK
// OK
void MyClass::foo1( ) {
foo1( );
}
void MyClass::foo2( int i ) {
while (i > 0) {
i--;
}
}
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 30
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Implementation", Item 33
BENEFITS
"Assignment versions of operators are more efficient than stand-alone
versions,
because stand-alone versions must typically return a new object, and that
costs
us the construction and destruction of a temporary. Assignment versions of
operators write to their left-hand argument, so there is no need to
generate
a temporary to hold the operator's return value."
EXAMPLE
class A {
public:
};
A& operator+( A& a, A& b );
A& operator-( A& a, A& b );
class B {
public:
B& operator+=( B& b );
};
B& operator+( B& a, B& b );
void foo( ) {
B ba, bb ,bc, bd;
// Violation
// Violation
bb = ba + bc + bd;
// Violation
REPAIR
class A {
public:
A& operator+=( A& a );
A& operator-=( A& a );
};
A& operator+( A& a, A&
A& operator-( A& a, A&
class B {
public:
B& operator+=( B& b
};
B& operator+( B& a, B&
void foo( ) {
B ba, bb ,bc, bd;
bb = ba;
bb += bc;
bb += bd;
}
b );
b );
// OK
// OK
);
b );
// OK
// OK
// OK
REFERENCES
1. Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Efficiency", Item 22
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 125
SINCE
v7.0
BENEFITS
Rule improves efficiency of code.
EXAMPLE
class BaseOne {};
int main( ) {
int gc = 0;
BaseOne one;
BaseOne two;
if (gc == 0) {
return 0;
}
one = two;
return gc;
}
// Violation
// Violation
REPAIR
class BaseOne {};
int main( ) {
int gc = 0;
if (gc == 0) {
return 0;
}
BaseOne one;
BaseOne two;
one = two;
return gc;
}
// OK
// OK
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 5, Item 26
Every switch statement shall have at least one non-empty case clause [OPT-21-3]
DESCRIPTION
A switch statement with no non-empty case-clauses is redundant.
If a switch statement yields a result that can be proven to be always
the same, it is highly likely that there is a programming error.
See also: MISRA2004-15_5, OPT-22
SINCE
v7.1
BENEFITS
The rule detects unneeded code and possible programming errors.
EXAMPLE
int foo(int i) {
switch(i) {
// Violation
case 1:
case 2:
default:
return 0;
}
}
REPAIR
int foo(int i) {
return 0;
}
// OK
REFERENCES
Recommended by ParaSoft
SINCE
v7.1
BENEFITS
If an empty case statement is found it is highly likely that there
is a programming error.
EXAMPLE
int foo(int i) {
switch(i)
/* Violation */
{
case 0:
return 1;
case 1:
case 2:
default:
return 0;
}
}
REPAIR
int foo(int i) {
switch(i)
/* OK */
{
case 0:
return 1;
default:
return 0;
}
REFERENCES
Recommended by ParaSoft
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();
};
// OK
// OK
REFERENCES
SINCE
v7.1
EXCEPTIONS
Constructors, destructors, template methods, virtual methods.
BENEFITS
Inlining short, simple functions can save both time and space.
EXAMPLE
int goo(int a, int b)
{
/* code */
return 1;
}
int foo(int a, int b)
{
return(goo(a,b));
}
REPAIR
int goo(int a, int b)
{
/* code */
return 1;
// Violation
}
inline int foo(int a, int b) // OK
{
return(goo(a,b));
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 124
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Only functions with 1 or 2 statements should be considered candidates for inline functions
[OPT-25-4]
DESCRIPTION
Only functions with 1 or 2 statements should be considered
candidates for inline functions.
Rule reports a violation message if inlined function has more
than 2 statements.
SINCE
v7.1
BENEFITS
Inlining complex functions may lead to significant code bloat
as well as to complicate debugging efforts.
DRAWBACKS
Each declared variable is counted as a separate statement.
int a, b, c;
// counted as 3 statements
EXAMPLE
inline int foo(int a)
{
int b = 0;
b = (b-a)/a;
return b;
}
// Violation
REPAIR
int foo(int a)
{
int b = 0;
// OK
b = (b-a)/a;
return b;
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 121
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Variables will not be introduced until they can be initialized with meaningful values [OPT-26-2]
DESCRIPTION
Variables will not be introduced until they can be initialized with
meaningful values.
Rule reports a violation message if:
- value assigned to local variable during initialization is not used (i.e.
there is
no variable usage after initialization statement and before new value
assignment)
- local variable is prematurely declared and is only used in for loop
SINCE
v7.1
NOTES
Rule is enabled for C++ only.
BENEFITS
Prevent clients from accessing variables without meaningful values.
EXAMPLE
int f(int);
void fun_1(int x)
{
int i;
int max=0;
max = f(x);
for (i=0 ; i<max ; ++i)
{
}
REPAIR
int f(int);
void fun_2(int x)
{
int max = f(x);
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.16 Initialization, AV Rule 143
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.1
NOTES
Rule assumes that setter/getter (mutator/accessor) methods are methods
with names starting from get/Get or set/Set prefix and followed by
underscoring or capitalized letter.
BENEFITS
Numerous accessors and mutators may indicate that a class simply serves
to aggregate a collection of data rather than to embody an abstraction
with a well-defined state or invariant. In this case, a struct with
public data may be a better alternative.
EXAMPLE
class Sample // Violation
{
private:
int m_var;
public:
int get_m_var();
void set_m_var();
void set_m_var(int a);
};
REPAIR
class Sample // OK
{
private:
int m_var;
public:
int get_m_var();
void set_m_var(int a = 0);
};
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 123
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
'strlen' function should not be used to check string against NULL/non-NULL [OPT-28-3]
DESCRIPTION
Rule reports a violation if strlen() is used to check strings for
NULL/non-NULL. Using the strlen() forces the processor to walk
through the whole string what is very costly. Such checks can
be performed more efficiently if only the first character of the
string is checked for NULL/non-NULL.
SINCE
v7.2
BENEFITS
Rule improves efficiency of code.
EXAMPLE
#include <string.h>
void myFunction()
{
const char* x = "string";
int a = 1;
if (strlen(x) == 0)
a++;
}
REPAIR
#include <string.h>
void myFunction()
{
const char* x = "string";
int a = 1;
// Violation
if (x[0] == 0)
a++;
// OK
REFERENCES
Recommended by ParaSoft
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
SINCE
v7.2
NOTES
The rule checks following functions:
- in C:
- static functions,
- in C++:
- non-template global static functions,
- non-template global functions in anonymous namespaces,
- non-template non-static non-operator private member functions
BENEFITS
"Functions or procedures that are not called may be symptomatic of a
serious
problem, such as missing paths."
EXAMPLE
static void foo() // Violation
{
/* ... */
}
int main()
{
return (0);
}
REPAIR
static void foo() // OK
{
/* ... */
}
int main()
{
foo();
return (0);
}
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-10
SINCE
v7.2
EXCEPTIONS
"An unnamed parameter in the definition of a function that is used as
a callback does not violate this rule."
BENEFITS
"Unused function parameters are often due to design changes and can
lead to mismatched parameter lists."
EXAMPLE
int Foo(int i, int k)
{
i = 5;
return i;
}
// Violation
REPAIR
int Foo(int i)
{
i = 5;
return i;
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-11
All functions with void return type shall have external side effect(s) [OPT-32-3]
DESCRIPTION
A function which does not return a value and which does not have external
side
effects will only consume time and will not contribute to the generation
of any
outputs, which may not meet developer expectations.
The following are examples of external side effects:
- Reading or writing to a file, stream, etc.;
- Changing the value of a non local variable;
- Changing the value of an argument having reference type;
- Using a volatile object;
- Raising an exception.
SINCE
v7.2
BENEFITS
Rule prevents unnecessary time consumption.
EXAMPLE
void foo( void ) // Violation
{
int local;
local = 0;
}
REPAIR
int foo( int p ) // OK
{
int local;
local = 10*p;
/* ... */
return local;
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-1-8
SINCE
v7.2
BENEFITS
Improves code consistency and runtime performance.
EXAMPLE
class Foo{};
class A {
public:
Foo foo();
Foo goo( A& a ) {
return foo();
}
};
// Violation
// Violation
REPAIR
class A2 {
public:
Foo& foo();
Foo& goo( A2& a ) {
return foo();
}
// OK
};
REFERENCES
Recommended by ParaSoft
PB
Possible Bugs
RULES
Do not dereference pointer type expressions [PB-01-3]
Do not use assignments inside a(b), a[b], and cast [PB-02-3]
Using mixed types in ternary operator is not allowed [PB-03-3]
Return value of a function must match declared return type [PB-05-3]
Assignment operator should have operands of compatible types [PB-06-3]
Do not assign signed constants to unsigned integer variables [PB-08-3]
Operators should not return value by reference [PB-09-2]
Don't treat arrays polymorphically [PB-10-3]
Declared types of formal and actual parameters to functions must match
[PB-11-3]
Do not cast a signed char to an unsigned int [PB-12-3]
Do not call delete on non-pointers [PB-13-1]
Incorrect End-Of-String (EOS) definition [PB-14-3]
Don't assign the dividend of two integers to a floating-point type [PB-153]
Avoid assigning out-of-range value to char type [PB-16-3]
Avoid assigning out-of-range value to unsigned char type [PB-17-3]
Avoid overloading on a pointer and a numerical type [PB-18-3]
Do not create inline non-member functions that contain local static data
[PB-19-3]
Avoid slicing function arguments / return value [PB-20-3]
Properly terminate character strings [PB-21-1]
Do not use increment and decrement expressions inside a(b), a[b], and cast
[PB-22-3]
The class object should be passed by reference if the class has non-static
pointers and has no declared copy constructor [PB-23-1]
The definition of a constructor shall not contain default arguments that
produce a signature identical to that of the implicitly-declared copy
constructor [PB-24-2]
Unsigned arithmetic shall not be used [PB-25-2]
Public and protected methods should not be invoked by class constructor
[PB-26-2]
A string literal shall not be modified [PB-27-2]
The following character sequences shall not appear in header file names:
', \, /*, //, or " [PB-28-2]
The left-hand operand of a right-shift operator shall not have a negative
value [PB-29-2]
More than one 'enum' type shall not be used as a switch condition or a
label in a case statement [PB-30-3]
Do not call 'sizeof' on constants [PB-31-3]
BENEFITS
Improves safety and readability of code.
EXAMPLE
int* pFun();
void goo()
{
int* ptr;
int a, b, c;
a = *ptr++;
b = *pFun();
c = *(ptr + 5);
}
// Violation
// Violation
// Violation
REPAIR
int* pFun();
void goo()
{
int* ptr;
int* ptr2;
int a, b, c;
ptr++;
a = *ptr;
// OK
ptr2 = pFun();
b = *ptr2;
// OK
ptr2 = ptr + 5;
c = *ptr2;
// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule increases legibility, efficiency and prevents possible bugs
related to aftereffects of unnecessary shortcuts in the code.
EXAMPLE
void foo( int i )
{
int* x;
x[ i = 0 ];
// Violation
foo( i = 0 );
// Violation
i = (int) (x = 0); // Violation
}
REPAIR
Do not use assignments inside a(b), a[b] and cast.
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule prevents implicit conversions which may result in a loss of
information
and improves readability and maintainability of code.
EXAMPLE
void foo( ) {
int x;
int y;
x = ((y > 5) ? 1.1 : 0.2);
}
// Violation
REPAIR
void foo( ) {
int x;
int y;
x = ((y > 5) ? 1 : 0);
}
REFERENCES
Recommended by ParaSoft
// OK
NOTES
In C language the type of a single character constant is 'int', but this
rule
assumes it as 'char' (similarly as is defined in C++) to prevents
confusions.
BENEFITS
Rule prevents implicit conversions which may result in a loss of
information
and improves readability and maintainability of code.
EXAMPLE
float foo1( int i ) {
return i;
}
// Violation
REPAIR
typedef int int_t;
// OK
// OK
REFERENCES
Recommended by ParaSoft
// OK
NOTES
The rule does not report violation if object or reference/pointer to
object
from derived class is assigned to reference/pointer to object from base
class.
BENEFITS
Rule prevents data loss and improves readability
and maintainability of code.
EXAMPLE
void foo1(signed int a, int& ref, int* ptr){
const short cs = 10;
unsigned int b;
float f;
void* pvoid;
b = a;
b = ref;
a = f;
pvoid = ptr;
b = cs + 10;
}
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
typedef unsigned int u_int;
void foo1(u_int a, u_int& ref, int* ptr){
short s;
unsigned int b;
float f;
void* pvoid;
b = a;
b = ref;
a = (unsigned int)f;
pvoid = (void*)ptr;
s = 10;
}
REFERENCES
Recommended by ParaSoft
//
//
//
//
//
OK
OK
OK
OK
OK
SINCE
v7.0
NOTES
Rule does not report violations on initializations. In this case
violations
are reported by rule INIT-02.
BENEFITS
Rule prevents undesirable implicit casts.
EXAMPLE
void foo1(unsigned int ui){
unsigned char uc;
ui = -10;
// Violation
uc = -20;
// Violation
}
unsigned int foo2(){
foo1(-10);
return -20;
}
// Violation
// Violation
REPAIR
void foo1(signed int ui){
signed char uc;
ui = -10;
// OK
uc = -20;
// OK
}
signed int foo2(){
foo1(-10);
return -20;
}
REFERENCES
Recommended by ParaSoft
// OK
// OK
BENEFITS
Prevents returning a reference instead of an object
what may result in corrupt data or a memory leak.
EXAMPLE
class A {
public:
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
const A&
};
operator&
operator^
operator|
operator!=
operator<=
operator<
operator==
operator>=
operator>
operator&&
operator||
operator%
operator*
operator+
operatoroperator/
operator~
operator!
operator+
operator-
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
Violation
(a & b)
(a ^ b)
(a | b)
(a != b)
(a <= b)
(a < b)
(a == b)
(a >= b)
(a > b)
(a && b)
(a || b)
(a % b)
(a * b)
(a + b)
(a - b)
(a / b)
(~a)
(!a)
(+a)
(-a)
REPAIR
class A {
public:
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
const A
};
operator&
operator^
operator|
operator!=
operator<=
operator<
operator==
operator>=
operator>
operator&&
operator||
operator%
operator*
operator+
operatoroperator/
operator~
operator!
operator+
operator-
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
(
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
A &x
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
(a & b)
(a ^ b)
(a | b)
(a != b)
(a <= b)
(a < b)
(a == b)
(a >= b)
(a > b)
(a && b)
(a || b)
(a % b)
(a * b)
(a + b)
(a - b)
(a / b)
(~a)
(!a)
(+a)
(-a)
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 21
2. Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 23
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
Declared types of formal and actual parameters to functions must match [PB-11-3]
DESCRIPTION
The type of parameters passed to a function should be compatible
with expected types defined in prototype.
BENEFITS
Rule improves readability and maintainability and prevents errorneous
code.
EXAMPLE
void foo(int a, int b)
{
}
void goo(float a, float b)
{
foo(a, b);
// Violation
}
REPAIR
void foo(int a, int b)
{
}
void goo(int a, int b)
{
foo(a, b);
// OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Prevents loss of sign (sign errors).
EXAMPLE
int foo( char ch )
{
unsigned int i = 10u
if((unsigned int) ch > i){
return 0;
} else {
return 1;
}
}
// Violation
REPAIR
int foo( unsigned char ch )
{
unsigned int i = 10u
if((unsigned int) ch > i){
return 0;
} else {
return 1;
}
}
// OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Prevents calling delete on non-pointer what results in an invalid operand.
EXAMPLE
class Rhino {
public:
Rhino( );
Rhino( char* );
Rhino( const char* );
operator char*( );
};
void func()
{
Rhino r;
delete( r );
}
// Violation
REPAIR
class Rhino {
public:
Rhino( );
Rhino( char* );
Rhino( const char* );
operator char*( );
};
void func()
{
Rhino *r = new Rhino();
delete r ; // OK
}
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#define EOS 0 // Violation
#undef EOS
#define EOS NULL // Violation
#undef EOS
REPAIR
#define EOS '\0' // OK
#undef EOS
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule prevents possible loss of fraction.
EXAMPLE
void func()
{
int a = 3;
int b = 4;
double d;
d = a / b;// Violation
}
REPAIR
void func()
{
int a = 3;
int b = 4;
double d;
d = ((double)a) / b;// OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Prevents using illegal values as chars.
EXAMPLE
void foo()
{
char c1, c2;
char c3 = 170;
char c4 = -130;
c1 = 145;
c2 = -154;
}
//
//
//
//
Violation
Violation
Violation
Violation
//
//
//
//
OK
OK
OK
OK
REPAIR
void fooOK()
{
char c1, c2;
char c3 = 70;
char c4 = -30;
c1 = 45;
c2 = -54;
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Prevents using illegal values as chars.
EXAMPLE
void foo()
{
unsigned char uc1, uc2 = 0;
unsigned char uc3 = 298;
// Violation
unsigned char uc4 = -15;
// Violation
uc1 = 289;
// Violation
uc2 = (-5);
// Violation
}
REPAIR
void fooOK()
{
unsigned char uc1, uc2 = 0;
unsigned char uc3 = 98;
// OK
unsigned char uc4 = 15;
// OK
uc1 = 89;
// OK
uc2 = (5);
// OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
Prevents overloading on a pointer and a numerical type.
EXAMPLE
class A {
public:
void func(A a, int *i) { }
void func(A a, long i) { }// Violation
};
REPAIR
Do not overload on a pointer and a numerical type.
REFERENCES
Scott Meyers, "Effective C++: 50 Specific Ways to Improve
Your Programs and Design", Second Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc.,
Chapter: "Classes and Functions: Design and Declaration", Item 25
Do not create inline non-member functions that contain local static data [PB-19-3]
DESCRIPTION
"If you create an inline non-member function containing a local static
object,
you may end up with more than one copy of the static object in your
program!"
SINCE
v7.0
BENEFITS
Rule prevents from declaring inline local variable inside inline function.
EXAMPLE
inline int increase( ) {
static int count = 0;
count++;
return count;
}
// Violation
REPAIR
int increase( ) {
static int count = 0;
count++;
return count;
}
// OK
REFERENCES
Scott Meyers, "More Effective C++: 35 New Ways to Improve
Your Programs and Designs", Addison-Wesley, Copyright 1996,
Chapter: "Techniques", Item 26
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;
}
};
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
SINCE
v7.0
BENEFITS
Rule prevents a possible program crash by checking proper string
termination.
EXAMPLE
struct S {
char pc[10];
}* ps = 0;
void foo( ) {
char pc[10];
ps->pc[0] = "\0";
pc[0] = "\0";
}
REPAIR
struct S {
char pc[10];
}* ps = 0;
void foo( ) {
char pc[10];
// Violation
// Violation
ps->pc[0] = '\0';
pc[0] = '\0';
// OK
// OK
REFERENCES
1. http://cwe.mitre.org/data/definitions/170.html
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Do not use increment and decrement expressions inside a(b), a[b], and cast [PB-22-3]
DESCRIPTION
Do not use increment and decrement expressions inside a(b), a[b], and
cast.
See also: MISRA2004-12_3 (operator sizeof), PB-02 (assign expression)
BENEFITS
Rule increases legibility, efficiency and prevents possible bugs
related to aftereffects of unnecessary shortcuts in the code.
EXAMPLE
void foo( int i )
{
int* x;
x[ i++ ];
foo( i++ );
i = (int) (x++);
}
// Violation
// Violation
// Violation
REPAIR
Do not use increment and decrement expressions inside a(b), a[b] and cast.
REFERENCES
Recommended by ParaSoft
The class object should be passed by reference if the class has non-static pointers and has
no declared copy constructor [PB-23-1]
DESCRIPTION
This rule detects where an object containing pointer member fields has
been
passed by value using a compiler-generated copy constructor. Passing such
objects by reference avoids possible problems with improper bitwise
copying
member pointers.
If a class/struct has non-static pointer member fields, has no declared
copy
constructor, and class/struct object is passed by value then the rule
reports
a violation message.
See also: OPT-14, PB-20
SINCE
v7.1
EXCEPTIONS
The rule excludes from checking objects of type class/struct which names
end with 'iterator' (e.g 'iterator', 'const_iterator',
'normal_iterator',...)
BENEFITS
Rule helps to avoid possible problems with bitwise copying member
pointers.
EXAMPLE
class A;
void foo1(A a);
class A
{
int *x;
};
void foo(void)
{
A a;
foo1(a);
}
// Violation
REPAIR
class A;
void foo1(A &a);
class A
{
int *x;
};
void foo(void)
{
A a;
foo1(a);
}
// OK - passed by reference
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.13 Functions, AV Rule 117
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The definition of a constructor shall not contain default arguments that produce a signature
identical to that of the implicitly-declared copy constructor [PB-24-2]
DESCRIPTION
The definition of a member function shall not contain default arguments
that
produce a signature identical to that of the implicitly-declared copy
constructor for the corresponding class/structure.
SINCE
v7.1
BENEFITS
If the class definition does not explicitly declare a copy constructor,
one is declared implicitly. Thus, for the class definition
class X
{
X(const X&, int);
};
a copy constructor is implicitly-declared. If the user-declared
constructor
is later defined as
X::X(const X& x, int i =0)
{
/* ... */
}
then any use of X's copy constructor is ill-formed because of the
ambiguity.
EXAMPLE
class A
{
A(const A&, int);
A(const A&);
};
A::A(const A& x, int i =0) // Violation
{
/* ... */
}
REPAIR
class A
{
A(const A&, int i=0);
A(const A&);
};
A::A(const A& x, int i) // OK
{
/* ... */
}
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 77.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.1
BENEFITS
Over time, unsigned values will likely be mixed with signed values what
is error prone as it subjects operations to numerous arithmetic
conversion and integral promotion rules.
EXAMPLE
void foo(unsigned p)
{
unsigned int a = 0;
int b = 0;
b = p + a;
// Violation
REPAIR
void foo(signed p)
{
signed int a = 0;
int b = 0;
b = p + a;
}
// OK
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 163
Public and protected methods should not be invoked by class constructor [PB-26-2]
DESCRIPTION
The intent of this rule is to prevent an object from being used before it
is in
a fully initialized state. This may occur when a class constructor invokes
a public or protected method that requires the object to be fully
initialized as a pre-condition of method invocation.
Rule reports a violation message if class constructor invokes public or
protected method.
See also: OOP-16, INIT-06
SINCE
v7.1
BENEFITS
Public (and in some cases protected) methods assume object initialization
and class invariants have been established prior to invocation. Thus,
invocation of such methods during object construction risks the use of
uninitialized or invalid data since class invariants can not be guaranteed
before an object is fully constructed.
EXAMPLE
class A
{
public:
A();
void foo();
private:
int obj1;
};
A::A()
{
foo();
}
// Violation
REPAIR
Do not call public/protected methods from constructor.
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.10 Classes, AV Rule 71
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.1
BENEFITS
The effect of attempting to modify a string literal is undefined.
EXAMPLE
void moo(char * p)
{
}
void foo()
{
char* c1 = "Hello";
char c2[] = "Hello";
char c3[6] = "Hello";
char* c12;
c12 = "Hello";
moo("Hello");
}
// Violation
// Violation
// Violation
// Violation
// Violation
REPAIR
void moo(const char * p)
{
}
void foo()
{
// OK
// OK
// OK
// OK
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.18 Constants, AV Rule 151.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The following character sequences shall not appear in header file names: ', \, /*, //, or " [PB-282]
DESCRIPTION
The following character sequences shall not appear in header file
names: ', \, /*, //, or ".
SINCE
v7.1
BENEFITS
If any of the character sequences ', \, /*, //, or " appears in a
header file name (i.e. <h-char-sequence>), the resulting behavior is
undefined.
EXAMPLE
#include "foo's.h" // Violation
REPAIR
#include <foo_s.h> // OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.9 Style, AV Rule 53.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The left-hand operand of a right-shift operator shall not have a negative value [PB-29-2]
DESCRIPTION
The rule reports a violation message if as left-hand operand of rightshift
operator is used one from the following options:
- constant with a negative value
- unary operator '-' followed by parameter, variable or expression
- parameter or variable of signed type
- expression of signed type that contains parameter, variable,
dereferenced
pointer or function call of signed type
SINCE
v7.1
BENEFITS
Rule prevents implementation-defined behaviours.
"For e1 >> e2, if e1 has a signed type and a negative value, the value
of (e1 >> e2) is implementation-defined."
EXAMPLE
void foo(signed int signed_param)
{
signed int signed_variable;
int variable;
signed int* ptr_signed_variable;
signed_param >> 5;
signed_variable >> 5;
-variable >> 5;
-100 >> 5;
-100u >> 5;
*ptr_signed_variable >> 5;
}
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
REPAIR
void foo(unsigned int unsigned_param)
{
unsigned int unsigned_variable;
int variable;
unsigned int* ptr_signed_variable;
unsigned_param >> 5;
unsigned_variable >> 5;
(unsigned int)variable >> 5;
100 >> 5;
100u >> 5;
*ptr_signed_variable >> 5;
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.21 Operators, AV Rule 164.1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
More than one 'enum' type shall not be used as a switch condition or a label in a case
statement [PB-30-3]
DESCRIPTION
Using labels with different enum types in a switch statement may cause
problem because enum members from different enum types could have the
same value but different meanings. Using different enum types in a switch
statement expression and labels may lead to unreachable code because the
two enum types could be in different ranges.
Rule reports a violation message in situations where enum type used as a
switch
expression is different than enums type used as labels in a switch
statement
or more than one enum type is used as labels in a switch statement.
SINCE
v7.2
BENEFITS
Rule prevents unreachable code and improves readability and
maintainability.
DRAWBACKS
Rule may not detect all violation cases in C code.
EXAMPLE
typedef enum E1 {EA, EB, EC} E1;
typedef enum F1 {FA = 3, FB = 4, FC = 5} F1;
void MyFunction(E1 e, int i) {
switch(e)
{
case FA :
// Violation
i++;
case FB :
// Violation
break;
default:
i++;
break;
}
}
REPAIR
typedef enum E1 {EA, EB, EC} E1;
typedef enum F1 {FA = 3, FB = 4, FC = 5} F1;
void MyFunction(E1 e, int i) {
switch(e)
{
case EA :
// OK
i++;
case EB :
// OK
break;
default:
i++;
break;
}
}
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
Rule prevents situations in which instead of using the actual type as
the argument of the sizeof operator, the constant is mistakenly used.
EXAMPLE
#define MAX 10
void myFunction()
{
sizeof(MAX);
sizeof(2);
}
// Violation
// Violation
REPAIR
Do not use sizeof on constants.
REFERENCES
Recommended by ParaSoft
SINCE
v7.2
BENEFITS
Rule prevents situations in which instead of using the actual type as the
argument of the sizeof operator, the pointer of the type is mistakenly
used.
EXAMPLE
typedef int * pint;
void myFunction(int* ptr_a)
{
pint ptr_b;
sizeof(ptr_a);
sizeof(ptr_b);
sizeof(pint);
sizeof(int *);
//
//
//
//
Violation
Violation
Violation
Violation
}
void mySndFunction(char tab10[10], char tabX[], char * ptr)
{
sizeof tab10;
// Violation
sizeof tabX;
// Violation
sizeof ptr;
// Violation
}
REPAIR
Do not use sizeof on pointers.
REFERENCES
1. ISO/DIS 26262
point 8.4.4
SINCE
v7.2
BENEFITS
Prevents depending on the value of enum constant which can change
EXAMPLE
enum ABC0{A0, B0, C0};
void foo1(int arg1){}
int foo(int p)
{
ABC0 x;
int i = x; // Violation
foo1(x);
// Violation
return x; // Violation
}
REPAIR
enum ABC0{A0, B0, C0};
void foo1(int arg1){}
int foo(int p)
{
ABC0 x;
int i = (int)x; // OK
foo1((int)x);
// OK
return (int)x; // OK
}
REFERENCES
1. ISO/DIS 26262
point 8.4.4
SINCE
v7.2
BENEFITS
Rule prevents undefined behavior.
EXAMPLE
#include <string.h>
void foo(void)
{
const int array1[10] = {0,1,2,3,4,5,6,7,8,9};
int array2[10];
memcpy ( array2, array1, sizeof(array1)); // Violation
}
REPAIR
#include <string.h>
void foo(void)
{
const int array1[10] = {0,1,2,3,4,5,6,7,8,9};
int array2[10];
memcpy ( array2, array1, sizeof(array2)); // OK
}
REFERENCES
Recommended by ParaSoft
SINCE
v7.2
BENEFITS
Rule prevents unexpected program behavior.
EXAMPLE
class A
{
void foo();
};
void A::foo()
{
int i = 1;
int j = 0;
if(i = j)j++;
}
REPAIR
class A
{
void foo();
};
void A::foo()
{
// Violation
int i = 1;
int j = 0;
if( (i = j) )j++;
// OK
REFERENCES
Recommended by ParaSoft
An object's dynamic type shall not be used from the body of its constructor or destructor [PB36-3]
DESCRIPTION
"During construction and destruction of an object, its final type
may be different to that of the completely constructed object."
"Member functions (including virtual member functions) can be called for
an
object under construction. Similarly, an object under construction can be
the
operand of the typeid operator or of a dynamic_cast. However, if these
operations are performed in a ctor-initializer (or in a function called
directly or indirectly from a ctor-initializer) before all the meminitializers
for base classes have completed, the result of the operation is
undefined."
SINCE
v7.2
BENEFITS
"The result of using an object's dynamic type in a constructor or
destructor may not be consistent with developer expectations."
EXAMPLE
/* Examples of incorrect code */
#include <typeinfo>
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
typeid ( B2 );
// Violation
foo ( );
// Violation
dynamic_cast< B2* > ( this ); // Violation
}
};
REPAIR
/* Examples of correct code */
#include <typeinfo>
class B1
{
public:
B1 ( )
{
typeid ( B1 ); // OK - B1 not polymorphic
}
};
class B2
{
public:
virtual ~B2 ( );
virtual void foo ( );
B2 ( )
{
B2::foo ( );
// OK - not a virtual call
}
};
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-1
2. ISO/DIS 26262
point 8.4.4
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strcpy ( array, pChar ); // Violation
}
REPAIR
/* Ideally, a safe string handling library should be used.
Use of bounded functions (e.g. strncpy) is also possible. */
typedef char char_t;
#include <cstring>
void fn ( const char_t * pChar )
{
char_t array [ 10 ];
strncpy ( array, pChar, 10 ); // OK
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 18, Rule 18-0-5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
wchar_t array[] = "Hello" L"World";
// Violation
REPAIR
wchar_t array[] = L"Hello" L"World";
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 2, Rule 2-13-5
A function shall not return a reference or a pointer to a parameter that is passed by reference
or const reference [PB-39-3]
DESCRIPTION
"A function shall not return a reference or a pointer to a parameter that
is
passed by reference or const reference. It is implementation-defined
behaviour
whether the reference parameter is a temporary object or a reference to
the
parameter. If the implementation uses a local copy (temporary object),
this
will be destroyed when the function returns. Any attempt to use such an
object
after its destruction will lead to undefined behaviour."
SINCE
v7.2
BENEFITS
Rule prevents non-deterministic behaviour.
EXAMPLE
int* foo2 ( int& x )
{
return ( &x );
}
// Violation
REPAIR
Do not return a reference or a pointer to a parameter that is passed by
reference or const reference
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-3
SINCE
v7.2
BENEFITS
"Automatic variables are destroyed at the end of the function call.
Returning a reference or pointer to such a variable allows it to be used
after its destruction, leading to undefined behaviour."
EXAMPLE
int* foo( ) {
int i;
return &i; // Violation
}
int& bar( ) {
int i;
return i; // Violation
}
REPAIR
int foo( ) {
int i = 0;
return i; // OK
}
int bar( ) {
int i = 0;
return i;
// OK
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 7, Rule 7-5-1
An identifier with array type passed as a function argument shall not decay to a pointer [PB41-3]
DESCRIPTION
"When a variable with array type decays to a pointer, its bounds are
lost."
SINCE
v7.2
BENEFITS
"If a design requires arrays of different lengths, then a class should
be used to encapsulate the array objects and so ensure that the
dimensionality
is maintained."
EXAMPLE
typedef int int32_t;
void f1( int32_t p[ 10 ] );
void f2( int32_t *p );
void b ()
{
int32_t a[ 10 ];
f1( a ); // Violation
f2( a ); // Violation
}
REPAIR
typedef int int32_t;
void f1( int32_t ( &p )[ 10 ] );
void b ()
{
int32_t a[ 10 ];
f1( a );
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 5, Rule 5-2-12
SINCE
v7.2
BENEFITS
"Assigning between objects that have an overlap in their physical storage
leads to undefined behaviour."
EXAMPLE
union U {
int
long
double
};
iValue;
lValue;
dValue;
void main( ) {
union U a, b;
union U *p;
a.dValue = a.lValue;
p->dValue = p->iValue;
}
REPAIR
union U {
int
long
double
};
iValue;
lValue;
dValue;
// Violation
// Violation
void main( ) {
union U a, b;
union U *p, *q;
a.dValue = b.lValue;
p->dValue = q->iValue;
}
// OK
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 0, Rule 0-2-1
All constructors of a class should explicitly call a constructor for all of its immediate base
classes and all virtual base classes [PB-43-3]
DESCRIPTION
"All constructors of a class should explicitly call a constructor for all
of
its immediate base classes and all virtual base classes."
SINCE
v7.2
NOTES
Rule will also report a violation if class does not define any
constructors
and has a base class with a constructor.
BENEFITS
This rule reduces confusion over which constructor will be used,
and with what parameters.
EXAMPLE
class A
{
public:
A ( )
{
}
};
class B : public A
{
public:
B ( ) // Violation
{
}
};
REPAIR
class A
{
public:
A ( )
{
}
};
class B : public A
{
public:
B ( ): A() // OK
{
}
};
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 12, Rule 12-1-2
SINCE
v7.2
BENEFITS
Rule prevents implementation-defined behaviour.
EXAMPLE
class C
{
public:
C() { throw 1; }
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}
REPAIR
class C
{
// Violation
public:
C()
{
try
{
/* ... */
throw 1;
}
catch(...)
{
/* ... */
}
}
};
void fnExit1 (void)
{
C c;
/* ... */
}
void foo()
{
atexit (fnExit1);
/* ... */
}
// OK
REFERENCES
MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 15, Rule 15-5-3
There should be no mismatch between the '%s' or '%c' tag from format string and its
corresponding argument in 'printf' function invocation [PB-45-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if an argument passed in for a tag "%s" is
not:
- pointer to char or void
- array of char type
- class containing 'String' in name and member function conversion
operator
- typedefs to above types
- constant '0' (null)
or if an argument passed in for a tag "%c" is not:
- unsigned char
- integer constant with a value lower than 256
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-46, PB-47, PB-48, PB-49, PB-50
NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n
BENEFITS
The rule prevents program crashes and unintended side-effects.
EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
printf("file %s, number %s", name, value);
printf("file %s, letter %c", name, value);
}
// Violation
// Violation
REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
unsigned char ch = 'c';
printf("file %s, number %u", name, value);
printf("file %s, letter %c", name, (unsigned char)value);
printf("file %s, letter %c", name, ch);
}
REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/
// OK
// OK
// OK
There should be no mismatch between the '%f' tag from format string and its corresponding
argument in 'printf' function invocation [PB-46-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if an argument passed in for a tag "%f" is
not:
- float type
- double type
or if an argument passed in for a tag "%Lf" is not:
- long double type
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-47, PB-48, PB-49, PB-50
NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n
BENEFITS
The rule prevents program crashes and unintended side-effects.
EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
float fl = 10.2f;
long double ld = 1.0001L;
printf("Value: %f", value);
printf("Value: %Lf", fl);
printf("Value: %f", ld);
}
// Violation
// Violation
// Violation
REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
float fl = 10.2f;
long double ld = 1.0001L;
printf("Value: %u", value);
printf("Value: %f", (float)value);
printf("Value: %f", fl);
printf("Value: %Lf", ld);
}
//
//
//
//
OK
OK
OK
OK
REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/
There should be no mismatch between the '%i' or '%d' tag from format string and its
corresponding argument in 'printf' function invocation [PB-47-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if:
- an argument passed in for a tag "%i", "%d", "%li", "%ld", "%Ii", "%Id",
"%I32i", "%I32d" is not:
- parameter/variable of type signed int, signed long, short, char, enum,
bool
- expression of type int, long, short, char, enum, bool
- typedefs to above types
- constants of int or long type in a range: -2147483648 to 2147483647
- an argument passed in for a tag "%hi", "%hd" is not:
- parameter/variable of type signed short, char, enum, bool
- expression of type short, char, enum, bool
- typedefs to above types
- constants in a range: -32768 to 32767
- an argument passed in for a tag "%hhi", "%hhd" is not:
- parameter/variable of type signed char
- expression of type char, enum, bool
- typedefs to above types
- constants in a range: -128 to 127
- an argument passed in for a tag "%lli", "%lld" is not:
- signed long long
- typedef to above type
- constants of long long type
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-46, PB-48, PB-49, PB-50
NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n
BENEFITS
The rule prevents program crashes and unintended side-effects.
EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value
signed
signed
signed
signed
signed
REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
signed short s;
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
long l;
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/
There should be no mismatch between the '%u' tag from format string and its corresponding
argument in 'printf' function invocation [PB-48-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if:
- an argument passed in for a tag "%u", "%lu", "%Iu", "%I32u" is not:
- parameter/variable/expression of type unsigned char, unsigned short,
unsigned int or unsigned long
- typedefs to above types
- constants of int or long type in a range: 0 to 4294967295
- an argument passed in for a tag "%hu" is not:
- parameter/variable/expression of type unsigned char or unsigned short
- typedefs to above types
- constants in a range: 0 to 65535
- an argument passed in for a tag "%hhu" is not:
- parameter/variable/expression of type unsigned char
- typedef to unsigned char type
- constants in a range: 0 to 255
- an argument passed in for a tag "%llu" is not:
- parameter/variable/expression of type unsigned long long
- typedef to above type
- constants of long long type
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-46, PB-47, PB-49, PB-50
NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n
BENEFITS
The rule prevents program crashes and unintended side-effects.
EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
printf("Value
printf("Value
printf("Value
printf("Value
printf("Value
unsigned
unsigned
unsigned
unsigned
unsigned
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
int i;
float f;
unsigned short int us;
unsigned long int ul;
printf("Value unsigned int: %u", value);
printf("Value unsigned short: %hu", us);
// OK
// OK
printf("Value
printf("Value
printf("Value
printf("Value
unsigned
unsigned
unsigned
unsigned
REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/
//
//
//
//
OK
OK
OK
OK
There should be no mismatch between the '%p' tag from format string and its corresponding
argument in 'printf' function invocation [PB-49-3]
DESCRIPTION
The goal of this rule is to prevent a type mismatch between an argument
type
specified as a tag in 'format' string and the actual type of an optional
argument passed in to function invocation.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
The rule reports a violation if an argument passed in for a tag "%p" is
not:
- pointer
- typedef to pointer
The rule does not report a violation if a number of tags specified in a
'format'
string is different than the number optional function arguments.
See also: PB-45, PB-46, PB-47, PB-48, PB-50
NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n
BENEFITS
The rule prevents program crashes and unintended side-effects.
EXAMPLE
#include <stdio.h>
int main(){
int i;
int* ptr;
printf("Value: %p", i);
printf("Value: %p", 0);
printf("Value: %p", *ptr);
}
// Violation
// Violation
// Violation
REPAIR
#include <stdio.h>
int main(){
int i;
int* ptr;
printf("Value: %p", &i);
printf("Value: %i", 0);
printf("Value: %p", ptr);
}
// OK
// OK
// OK
REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/
There should be no difference between the number of tags from format string and the number
of corresponding argument in 'printf' function invocation [PB-50-3]
DESCRIPTION
The rule reports a violation if a number of tags specified in a 'format'
string is different than the number optional function arguments.
The rule looks for invocations of functions which match "printf-like"
pattern:
- contain "printf" in name (case insensitive)
- two last parameters in function declaration are a string and ellipsis
- the argument corresponding to the string parameter contains recognized
"%" tags
See also: PB-45, PB-46, PB-47, PB-48, PB-49
NOTES
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
where specifier is the most significant one and defines the type
and the interpretation of the value of the corresponding argument.
The tag can also contain flags, width, .precision and modifiers subspecifiers,
which are optional.
This rule as specifiers detects the following values:
c, d, i, e, E, f, g, G, a, A, o, s, u, x, X, p, n
BENEFITS
The rule prevents program crashes and unintended side-effects.
EXAMPLE
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
printf("file %s, number %u", name);
printf("file %s, number %u", name, name, value);
}
// Violation
// Violation
REPAIR
#include <stdio.h>
int main(){
unsigned int value = 10;
const char* name = "file.c";
printf("file %s, number %u", name, value);
}
// OK
REFERENCES
1. ISO/IEC 9899:1999 Programming languages -- C
7.19.6 Formatted input/output functions
2. http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Pointer arithmetic shall not be applied to pointers that address variables of non-array type
[PB-51-3]
DESCRIPTION
"Pointer arithmetic shall only be applied to pointers that address an
array or
array element.
Addition and subtraction of integers (including increment and decrement)
from
pointers that do not point to an array or array element results in
undefined
behaviour."
See also: MISRA2004-17_1
SINCE
v9.0
NOTES
The rule assumes that a pointer does not point to an array or array
element
if to pointer is assigned null or an address of variable of non-array
type.
BENEFITS
Rule makes the code more readable and less confusing.
EXAMPLE
/* example of incorrect code */
void func(int* ptr1, int a[5]){
int i;
int* ptr2 = 0;
int* ptr3;
ptr1 = &i;
ptr1++;
/* Violation */
REPAIR
/* example of correct code */
void func(int* ptr1, int a[5]){
int i;
int* ptr2 = &a;
int* ptr3 = &a[3];
ptr1++;
/* OK - ptr1 may points to whatever */
ptr1 = ptr2 + 1; /* OK - ptr2 points to an array */
ptr3++;
/* OK - ptr3 points to an array element */
}
REFERENCES
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 17
PFO
Physical File Organization
RULES
Don't define entities with linkage in a header file [PFO-01-3]
Use multiple include guards [PFO-02-3]
An include file should not contain more than one class definition [PFO-033]
Include constant string describing file [PFO-04-3]
File with extension '.c' may not include other files with extension '.c'
[PFO-05-3]
Never include other files in a file with extension '.icc' [PFO-06-3]
Use multiple include guards with pattern based on the header file name
[PFO-07-3]
Use mechanism that prevents multiple inclusion of the file i.e. include
guards or "#pragma once" preprocessor directive [PFO-08-3]
"#pragma once" preprocessor directive should not be used in source files
[PFO-09-3]
NOTES
As a headers rule detects files with extensions ".h", ".hh", ".hxx", ".i"
(e.g. "file.h", "file.hh", "file.hxx", "file.i").
EXCEPTIONS
The following definitions are allowed in a header file:
- inline functions
- function templates
- static data members of class templates
- const variables if they have internal or no linkage (C++ mode)
- static const variables
BENEFITS
Rule improves readability and maintainability.
By not having definitions in header files it's possible to
include headers in multiple translation units.
EXAMPLE
/* file.h */
void f1(){}
int var;
class C {
void f2();
};
// Violation
// Violation
void C::f2() {}
// Violation
/* file.cpp */
#include "file.h"
REPAIR
/* file.h */
void f1();
extern int var;
class C {
void f2();
};
template <typename T>
void f3 ( T ) { }
// OK
// OK
// OK
/* file.cpp */
#include "file.h"
void f1(){}
int var;
void C::f2() {}
REFERENCES
1. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 3, Rule 3-1-1
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Namespaces and Modules", Rule 61
3. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 39
BENEFITS
Rule improves maintainability and optimization of code.
EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present
REPAIR
// file foo.hh
// OK
#ifndef FOO_HH
#define FOO_HH
int i;
#endif
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 27
3. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-3
An include file should not contain more than one class definition [PFO-03-3]
DESCRIPTION
The rule reports a violation if in a header file is declared
more than one class. Rule does not count nested classes.
See also: NAMING-32
NOTES
A header file is defined as any file that is included via #include.
BENEFITS
Rule makes source code more readable.
EXAMPLE
// file.cpp
#include "file.hh"
// file.hh
class testClass1{};
class testClass2{};
// Violation
REPAIR
// file.cpp
#include "file.hh"
// file.hh
class testClass1{};
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#4.1
From: 4 Source Code in Files - 4.1 Structure of Code - Rec. 3
BENEFITS
Improves possibility of obtaining information on the file revision.
EXAMPLE
// Violation - No local constant string describing the file
REPAIR
// OK
static const char* sccsid =
"@(#) Exception.cc ; rev. A, Copyright ... ";
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 include Files - Rec 12
File with extension '.c' may not include other files with extension '.c' [PFO-05-3]
DESCRIPTION
.c or .C files (implementation files) are intended to be
compiled on their own, and not included in other files.
This is a well accepted physical organization model for
C and C++ code.
Many build environments are set up
to automatically compile every .c file. If in addition a .c
file is included in another .c file, this will result in
link errors.
BENEFITS
Rule improves maintainability and readability of code, as
well as prevents build errors.
EXAMPLE
//file.c
#include "file2.c"
// Violation
REPAIR
1. Compile each .c file separately and link them.
2. Develop a convention for naming implementation files
to be included that does not use .c or .C extensions.
REFERENCES
Recommended by Parasoft
BENEFITS
Rule prevents including other files in an .icc file.
EXAMPLE
// some.icc
#include <stdio.h>
// Violation
REPAIR
// File some.icc do not include any other files
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rec. 13
Use multiple include guards with pattern based on the header file name [PFO-07-3]
DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-02, PFO-08, and MISRA2004-19_15
NOTES
If the name of file is filename.h the name in multiple inclusion
mechanism should be converted to the following format FILENAME_H
(capitalized
and with extension preceded by underscoring)
BENEFITS
Rule improves maintainability and optimization of code.
EXAMPLE
// file goo.hh
#ifndef GUARD_GOO // Violation - naming convention not followed
(GUARD_GOO)
#define GUARD_GOO
int i;
#endif /*GUARD_GOO*/
REPAIR
// file goo.hh
#ifndef GOO_HH // OK
#define GOO_HH
int i;
#endif /*GUARD_HH*/
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
Use mechanism that prevents multiple inclusion of the file i.e. include guards or "#pragma
once" preprocessor directive [PFO-08-3]
DESCRIPTION
"Every include file must contain a mechanism that prevents multiple
inclusion
of the file."
The multiple inclusion mechanism should be either:
- #pragma once - preprocessor directive
or
- include guards defined as follows:
#ifndef FILENAME_H
#define FILENAME_H
// code
#endif
or
#if !defined(FILENAME_H)
#define FILENAME_H
// code
#endif
See also: PFO-02, PFO-07, and MISRA2004-19_15
SINCE
v7.1
BENEFITS
Rule improves maintainability and optimization of code.
EXAMPLE
// file foo.hh
// Violation - no multiple inclusion mechanism present
REPAIR
// file foo.hh
// OK
#pragma once
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 7
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Files, AV Rule 35
"#pragma once" preprocessor directive should not be used in source files [PFO-09-3]
DESCRIPTION
#pragma once is a non-standard but widely supported preprocessor directive
designed to cause the current header file to be included only once in a
single
compilation. Using #pragma once in source files is useless because source
files
are not meant to be included by other files. However, if source file with
#pragma once directive is meant to be included by other files one should
reconsider if this file should not be a header file.
BENEFITS
Rule improves maintainability and optimization of code.
EXAMPLE
// file foo.cpp
#pragma once
// Violation
REPAIR
// file foo.h
#pragma once
// OK
REFERENCES
Recommended by ParaSoft
PORT
Portability
RULES
Use capital 'L' instead of lowercase 'l' to indicate long [PORT-01-5]
Assigning result of ints operation to long without casting at least one of
the ints is not allowed [PORT-02-3]
Don't use hard coded value of offset in structures [PORT-03-2]
Don't use hex constant '0xffffffff' as an error marker [PORT-04-2]
A pointer to a long should not be casted to an int pointer [PORT-05-2]
Do not assign a long int to an int [PORT-06-3]
Do not pass long casted to an int in function call [PORT-07-3]
Constant assignment to long should not involve int literals [PORT-08-3]
Do not initialize a long int with int literals [PORT-10-3]
Do not cast an int pointer to a long pointer [PORT-11-2]
Do not assign the value from 32 bit multiplication to long type [PORT-123]
The type int shall always be declared as unsigned int or signed int [PORT13-3]
Avoid conversions from "shorter" type to "longer" type in assignment
[PORT-14-3]
Do not cast from "shorter" type to "longer" type [PORT-15-3]
Avoid conversions from a "shorter" type to a "longer" type in function
calls [PORT-16-3]
Don't use 'i64' or 'L' suffixes directly [PORT-17-3]
Instead of casting a long type operand of an expression to int cast the
result of the expression [PORT-19-3]
Do not declare variables of long type directly [PORT-20-3]
Do not assign a long value to a double [PORT-21-3]
Use arrays of int types instead of large arrays of longs [PORT-22-5]
Use arrays of int types instead of dynamic allocated large arrays of longs
[PORT-23-5]
Don't use large arrays of pointers to bool, char, short, int and float
types [PORT-24-5]
User-specified identifiers (internal and external) will not rely on
significance of more than 64 characters [PORT-25-2]
Algorithms shall not make assumptions concerning the order of allocation
of nonstatic data members separated by an access specifier [PORT-26-2]
Avoid implicit conversions to a type of narrower size [PORT-27-3]
Avoid conversions of constant values to a narrower type [PORT-28-3]
BENEFITS
The rule prevents confusions and improves the readability of code.
EXAMPLE
#define S1 11l
// Violation
void foo1(){
long l;
long long ll;
unsigned long ul;
ul = 11lu;
// Violation
l = 11l;
// Violation
ll = 11111ll; // Violation
}
REPAIR
#define S1 11L
// OK
void foo1(){
long l;
long long ll;
unsigned long ul;
ul = 11LU;
// OK
l = 11L;
// OK
ll = 11111LL; // OK
}
REFERENCES
CERT C Secure Coding Standard, Declarations and Initialization, DCL16-C
Assigning result of ints operation to long without casting at least one of the ints is not allowed
[PORT-02-3]
DESCRIPTION
When assigning result of ints operation to long, you should cast at least
one
of the ints to a long before the operation.
BENEFITS
When operating on ints, you should at least cast one of the ints to along
before the operation. Otherwise, you may have a loss of information.
EXAMPLE
void foo() {
int a = 72;
int b = 55;
long result = 0;
result = (long)(a*b);
}
// Violation
REPAIR
void foo() {
int a = 72;
int b = 55;
long result = 0;
result = (long)((long)a*b);
}
REFERENCES
Recommended by ParaSoft
// OK
BENEFITS
By following this rule, you let the compiler calculate the field of
offset.
EXAMPLE
#include <stddef.h>
#define ARCH32 true
#ifdef ARCH32
#define __int3264 int //32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 //64-bit type on win64
//(warning: long on win64 is 32-bit type)
#else //unix64
#define __int3264 long //64-bit type on unix64 (long on unix64 is 64-bit
type)
#endif
#endif
struct myStruct {
void *ptr;
int i;
};
void foo() {
myStruct s;
myStruct *ps = new myStruct();
int j;
s.i = 22;
ps->i = 22;
j= *(int *)((unsigned __int3264)&s + sizeof(void*));
j= *(int *)((unsigned __int3264)&s + 4 );
// Violation
// Violation
j=
j=
j=
j=
*(int
*(int
*(int
*(int
*)((unsigned
*)((unsigned
*)((unsigned
*)((unsigned
__int3264)&s.i + 0 );
__int3264)ps + sizeof(void*));
__int3264)ps + 4);
__int3264)&ps->i + 0);
//
//
//
//
Violation
Violation
Violation
Violation
REPAIR
#include <stddef.h>
#define ARCH32 true
#ifdef ARCH32
#define __int3264 int //32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 //64-bit type on win64
//(warning: long on win64 is 32-bit type)
#else //unix64
#define __int3264 long //64-bit type on unix64 (long on unix64 is 64-bit
type)
#endif
#endif
struct myStruct {
void *ptr;
int i;
};
void foo() {
myStruct s;
myStruct *ps = new myStruct();
int j;
s.i = 22;
ps->i = 22;
j= *(int *)((unsigned __int3264)&s + offsetof(myStruct,i)); // OK
j= *(int *)((unsigned __int3264)ps + offsetof(myStruct,i)); // OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
The rule prevents writing an error prone code.
EXAMPLE
#ifndef size_t
typedef unsigned int size_t;
#endif
#define INVALID_RESULT (0xFFFFFFFFu)
#define NULL 0
// Violation
REPAIR
#ifndef size_t
typedef unsigned int size_t;
#endif
#define INVALID_RESULT (size_t(-1))
#define NULL 0
size_t MyStrLen(const char *str) {
size_t n;
// OK
if (str == NULL)
return INVALID_RESULT;
// ...
return n;
}
REFERENCES
http://software.intel.com/en-us/articles/lessons-on-development-of-64-bitcc-applications/
Lesson 9.
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo() {
int *intPointer;
long *longPointer;
intPointer = (int *)longPointer; // Violation
}
REPAIR
Do not cast long pointer to int pointer.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo(){
int iVal = 72;
long lVal = 6;
iVal = lVal;// Violation
iVal = (int)lVal; // Violation
}
REPAIR
Do not assign a long int to an int.
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo(int iVal){
long lVal;
foo(lVal);// Violation
foo((int)lVal);// Violation
}
REPAIR
Do not assign a long int to an int.
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo() {
long longValue;
longValue &= ~(0x0000000000000101); // Violation
longValue = 0x0000000000000101; // Violation
}
REPAIR
void foo() {
long longValue;
longValue &= ~(0x0000000000000101L); // OK
longValue = 0x0000000000000101L; // OK
}
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo(){
long lVal = 1;
}
// Violation
REPAIR
void foo(){
long lVal = 1L; // OK
}
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
NOTES
The rule checks only explicit casts.
BENEFITS
The rule prevents misaligned memory accesses on 64-bit platforms.
EXAMPLE
void f2005() {
int *intPointer;
long *longPointer;
longPointer = (long *)intPointer;// Violation
}
REPAIR
Do not cast an int pointer to a long pointer.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
2. http://developers.sun.com/solaris/articles/64_bit_driver.html
3.1.1 Converting Driver Code to Be 64-Bit Clean, Example 3
Do not assign the value from 32 bit multiplication to long type [PORT-12-3]
DESCRIPTION
"Do not assume that int and long have the same size."
32 bit multiplication assigned to long value may result in truncation.
See also: PORT-05, PORT-06, PORT-07, PORT-08, PORT-10, PORT-11
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo() {
long longValue;
longValue = 2000000 * 3000000;
}
// Violation
REPAIR
void foo() {
long longValue;
longValue = 2000000L * 3000000;
}
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.2
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 2
The type int shall always be declared as unsigned int or signed int [PORT-13-3]
DESCRIPTION
"Do not assume that an int is 32 bits long (it may be only 16 bits long)."
BENEFITS
Complying with this rule leads to safer and more readable code.
EXAMPLE
void foo()
{
int a; // Violation
};
int goo();
// Violation
REPAIR
void foo()
{
signed int a;
};
unsigned int goo();
// OK
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 18 Portable Code - 18.2 Sizes of Types - Port. Rec. 3
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo1() {
int intValue;
long longValue = 1L;
longValue = intValue;// Violation
}
void foo2() {
int intValue=1;
float floatValue;
floatValue = intValue;// Violation
}
REPAIR
Do not make conversion from a shorter type to a longer one.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 6
2. ISO/DIS 26262
point 8.4.4
BENEFITS
Rule prevents loss of data.
EXAMPLE
void foo3() {
int longValue = 1L;
(double)longValue;// Violation
}
REPAIR
Do not make conversion from a shorter type to a longer one.
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 6
Avoid conversions from a "shorter" type to a "longer" type in function calls [PORT-16-3]
DESCRIPTION
Under 32 bit platform double can hold all significant bits.
Under 64 bit platform double has 52 significant bits, and bits can be
lost.
See also: PORT-14, PORT-15
BENEFITS
Rule prevents loss of data.
EXAMPLE
void moo (double d) {}
void foo () {
long longValue = 1L;
moo(longValue);// Violation
}
REPAIR
void moo (double d) {}
void foo () {
double longValue = 1;
moo(longValue);// OK
}
REFERENCES
1. Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html#18.3
From: 18 Portable Code - 18.3 Type Conversions - Port. Rec. 6
2. ISO/DIS 26262
point 8.4.4
BENEFITS
Adding a centrally defined macro in the file will make the code generic,
so that it can be compiled for use on both the UNIX(64-bit)
and the Windows(64-bit) operating systems.
EXAMPLE
void foo(){
long l;
unsigned long ul;
l = 123456789l;
l = 123456789L;
ul = 123456789ul;
ul = 123456789uL;
}
//
//
//
//
Violation
Violation
Violation
Violation
REPAIR
#ifdef _WIN64
#define CONST3264(a) (a##i64)
#else
#define CONST3264(a) (a##L)
#endif
void foo(){
long l;
unsigned long ul;
l = CONST3264( 123456789 );
// OK
ul = CONST3264( 123456789u ); // OK
}
REFERENCES
http://software.intel.com/en-us/articles/support-integer-constant-typesuffixes-on-64-bit-architecture/
Instead of casting a long type operand of an expression to int cast the result of the expression
[PORT-19-3]
DESCRIPTION
The rule reports a violation if you use explicit cast to 'int' on operand
of long type. When you cast an operand from a long to an int type, then
some data could be removed and the result of expression could be not
according
to expectations.
BENEFITS
The rule prevents loss of data.
EXAMPLE
void foo()
{
int int1, int2;
long longValue;
int2 = ((int)longValue)/int1; // Violation
}
REPAIR
void foo()
{
int int1, int2;
long longValue;
int2 = (int)(longValue/int1); // OK
}
REFERENCES
Recommended by ParaSoft
BENEFITS
By following this rule, you can prevent data loss.
EXAMPLE
#define ARCH32 true
#ifndef __int3264
#ifdef ARCH32
#define __int3264 int // 32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 // 64-bit type on win64
#else //unix64
#define __int3264 int64_t // 64-bit type on unix64
#endif
#endif
#endif
long lVal;
// Violation
REPAIR
#define ARCH32 true
#ifndef __int3264
#ifdef ARCH32
#define __int3264 int // 32-bit type on win32 and unix32
#else //ARCH64
#ifdef win64
#define __int3264 __int64 // 64-bit type on win64
#else //unix64
#define __int3264 int64_t // 64-bit type on unix64
#endif
#endif
#endif
__int3264 newlVal; // OK
REFERENCES
Recommended by ParaSoft
BENEFITS
This rule checks for possible truncation and prevents data loss.
EXAMPLE
void foo()
{
double doubleValue;
long longValue = 1L;
doubleValue = longValue;
}
// Violation
REPAIR
Do not assign a long value to a double.
REFERENCES
Recommended by ParaSoft
Note: This rule checks for static allocated arrays of longs that consist
over 2^16-1
elements.
SINCE
v7.0
BENEFITS
Reduction of memory consumption and avoiding possible performance
degradation.
EXAMPLE
typedef long LONG;
long tab1[12];
long tab2[65536];
long int tab3[65536];
long tab4[256][32][16];
unsigned long int tab5[65536];
LONG tab6[100000];
REPAIR
//
//
//
//
//
//
OK
Violation
Violation
Violation
Violation
Violation
long tab1[12];
int tab2[65536];
int tab4[256][32][16];
unsigned int tab5[65536];
int tab6[100000];
//
//
//
//
//
OK
OK
OK
OK
OK
REFERENCES
1. Converting 32-bit Applications Into 64-bit Applications: Things to
Consider
http://developers.sun.com/prodtech/cc/articles/ILP32toLP64Issues.html
2. Multiplatform Porting to 64 Bits
http://www.ddj.com/184406427
Use arrays of int types instead of dynamic allocated large arrays of longs [PORT-23-5]
DESCRIPTION
"Large arrays of long or unsigned long types, can cause serious
performance degradation in the LP64 data-type model as compared
to arrays of int or unsigned int types. Large arrays of long types cause
significantly more cache misses and consume more memory.
Therefore, if int works just as well as long for the application purposes,
it's better to use int rather than long."
See also: PORT-22, PORT-24
Note: This rule checks for dynamic allocated arrays of longs that consist
over 2^16-1
elements.
SINCE
v7.0
BENEFITS
Reduction of memory consumption and avoiding possible performance
degradation.
EXAMPLE
long *arr1 = new long[70000];
// Violation
REPAIR
int *arr1 = new int[70000];
// OK
REFERENCES
1. Converting 32-bit Applications Into 64-bit Applications: Things to
Consider
http://developers.sun.com/prodtech/cc/articles/ILP32toLP64Issues.html
2. Multiplatform Porting to 64 Bits
http://www.ddj.com/184406427
Don't use large arrays of pointers to bool, char, short, int and float types [PORT-24-5]
DESCRIPTION
"Large arrays of long or unsigned long types, can cause serious
performance degradation in the LP64 data-type model as compared
to arrays of int or unsigned int types. Large arrays of long types cause
significantly more cache misses and consume more memory(...)
This is also an argument for using arrays of int types instead of arrays
of pointers. Some C applications suffer from serious performance
degradation after conversion to the LP64 data-type model because
they rely on many, large, arrays of pointers"
See also: PORT-22, PORT-23
Note: Rule report violation large (over 2^16 elements) arrays to pointers
to bool, char, short, int and float types.
SINCE
v7.0
BENEFITS
Reduction of memory consumption and avoiding possible performance
degradation.
EXAMPLE
int* arr1[100000];
float* arr2[100000];
// Violation
// Violation
REPAIR
int arr1[100000];
float arr2[100000];
REFERENCES
// OK
// OK
User-specified identifiers (internal and external) will not rely on significance of more than 64
characters [PORT-25-2]
DESCRIPTION
Identifiers names consisting of more than 64 characters should not be
used.
SINCE
v7.1
BENEFITS
Rule ensures that code can be ported between the majority of
compilers/linkers
without requiring modification (shortening) of identifiers names
EXAMPLE
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam) //
Violation 65 chars
{
}
REPAIR
void foo(int
really_long_paaaaaaaaaaaaaaaaraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam)
64 chars
{
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
// OK
Algorithms shall not make assumptions concerning the order of allocation of nonstatic data
members separated by an access specifier [PORT-26-2]
DESCRIPTION
This rule is intended to prohibit an application from making assumptions
concerning the order in which non-static data members, separated by an
access specifier, are ordered.
Rule reports a violation message if static_cast type is pointer to class
with non-static data members separated by an access specifier.
SINCE
v7.1
BENEFITS
The order of allocation of nonstatic data members, separated by an
access-specifier, is unspecified.
EXAMPLE
class A
{
protected: // a could be stored before b, or vice versa
int a;
private:
int b;
};
class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);
// Violation
// application
REPAIR
struct A
{
int a;
int b;
};
class M: A
{
};
void foo(M* message_buffer_ptr)
{
A* a_ptr = static_cast<A*>(message_buffer_ptr);
// OK
// attributes in B
not separated
// by an access
specifier
}
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.28 Portable Code, AV Rule 210.1
SINCE
v9.2
NOTES
The rule does
- conversions
- conversions
- conversions
not check:
of constant expressions.
of bit fields
between integral and floating types
BENEFITS
The rule prevents possible loss of data.
EXAMPLE
enum E1_int{
E1_int = 0xFFFF,
E2_int
}e1;
void foo(unsigned int i){
unsigned char c1 = e1;
unsigned char c2 = i;
}
// Violation
// Violation
REPAIR
enum E1_int{
E1_int = 0xFFFF,
E2_int
}e1;
void foo(){
unsigned int c = e1;
// OK
unsigned char c2 = (unsigned int)i; // OK
}
REFERENCES
Recommended by ParaSoft
SINCE
v9.2
NOTES
The rule does not report violations on complex constant expressions.
BENEFITS
The rule prevents a loss of data.
EXAMPLE
void foo1(){
unsigned char c = 256;
short s = 32768;
int i = 2147483648;
}
// Violation
// Violation
// Violation
REPAIR
void foo1(){
unsigned short c = 256;
int s = 32768;
unsigned int i = 2147483648;
}
REFERENCES
// OK
// OK
// OK
Recommended by ParaSoft
PREPROC
Preprocessor
RULES
Avoid macros [PREPROC-01-3]
Don't use macros in include statement [PREPROC-02-2]
Don't redefine primitive types [PREPROC-03-4]
Don't define part of statement [PREPROC-04-4]
In a macro function, use parentheses before and after multiplication or
division [PREPROC-05-2]
Do not allow relative path names in #include statements [PREPROC-06-2]
Incorrect 'NULL' definition [PREPROC-07-5]
The #include pre-processor directive will only be used to include header
(*.h) files [PREPROC-08-3]
The #include directive shall use the <filename.h> notation to include
header files [PREPROC-09-2]
The #ifndef and #endif pre-processor directives will only be used to
prevent multiple inclusions of the same header file [PREPROC-10-3]
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include [PREPROC-11-2]
C++ macros shall only be used for include guards, type qualifiers, or
storage class specifiers [PREPROC-12-3]
Macro should not contain token pasting, variable argument list nor
recursive macro calls [PREPROC-13-3]
All macros must expand into complete syntactic units [PREPROC-14-3]
Pointer dereference operations may not be hidden in macro definitions
[PREPROC-15-3]
EXCEPTIONS
Macros are almost never necessary in C++. Exceptions to this rule are:
- #ifdef
- #ifndef
- #if
- #if defined
when used as include guards and for conditional compilation.
BENEFITS
Improves code reliability and maintainability.
EXAMPLE
#define PI 3.14
// Violation
REPAIR
const double PI = 3.14; // OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Coding Style", Rule 16
2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
BENEFITS
Readability and clarity.
EXAMPLE
/* Notice:
* You must be sure that your compiler can do that
* and that given header file is available
* Works with gcc
*/
#define A(string) #string
#define HEADER_FILE(nr) A(MacroWithinInclude ## nr)
#include HEADER_FILE(12)
// Violation
#include "MacroWithinInclude12"
// OK
REPAIR
Don't use macros in include statement
REFERENCES
Recommended by ParaSoft
BENEFITS
Readability.
EXAMPLE
#define T30 char
#define T31 unsigned char
// Violation
// Violation
REPAIR
#define T30 char_def
#define T31 unsigned_char_def
REFERENCES
Recommended by ParaSoft
// OK
// OK
BENEFITS
Prevents making code unreadable.
EXAMPLE
#define PARTIAL(a) ((a) * // Violation
REPAIR
#define PARTIAL(a) ((a) * (a)) // OK
REFERENCES
Recommended by ParaSoft
In a macro function, use parentheses before and after multiplication or division [PREPROC-052]
DESCRIPTION
This rule checks whether parentheses are used before and after division
or multiplication in function-like macros.
EXCEPTIONS
The rule does not report violation if as an operand of division
or multiplication is used a number constant or other division
or multiplication.
BENEFITS
Improves the readability of code and ensures operations order.
EXAMPLE
#define
#define
#define
#define
#define
#define
DIVISION_1(x) ( x / (x))
// Violation
DIVISION_2(x) ((x) / 2 + 5) // Violation
DIVISION_3(x) (256 / x)
// Violation
MULTI_1(x) (x * (x))
// Violation
MULTI_2(x) ((x) * 2 + 5)
// Violation
MULTI_3(x) (256 * x)
// Violation
REPAIR
#define
#define
#define
#define
#define
#define
#define
#define
//
//
//
//
//
//
//
//
OK
OK
OK
OK
OK
OK
OK
OK
REFERENCES
Recommended by ParaSoft
BENEFITS
Rule prevents specifying relative file names in #include directives.
EXAMPLE
#include "inc/foo.hh"
#include "inc/../foo.hh"
#include <sys/../time.h>
// OK
// Violation
// Violation
REPAIR
#include "inc/foo.hh"
#include "inc/foo.hh"
#include <sys/time.h>
// OK
// OK
// OK
REFERENCES
Ellemtel Coding Standards
http://www.chris-lott.org/resources/cstyle/Ellemtel-rules-mm.html
From: 4 Source Code in Files - 4.4 Include Files - Rule 10
BENEFITS
Any other usage of NULL is misleading and error prone.
EXAMPLE
#define NULL 0 // Violation
#undef NULL
#define NULL
// Violation
#undef NULL
REPAIR
#define NULL (void*)0
// OK
#undef NULL
#define NULL ((void*)0) // OK
#undef NULL
REFERENCES
Recommended by ParaSoft
The #include pre-processor directive will only be used to include header (*.h) files [PREPROC08-3]
DESCRIPTION
The #include pre-processor directive will only be used to include
header (*.h) files.
SINCE
v7.1
EXCEPTIONS
In the case of template class or function definitions, the code may be
partitioned into separate header and implementation files. In this
case, the implementation file may be included as a part of the header
file. Rule allows for mentioned exception if the implementation file
has the same name as a header file.
BENEFITS
Rule improves the clarity of code.
The only files included in a .cpp file should be the relevant
header (*.h) files.
EXAMPLE
// file.cpp
#include <file2.cpp>
#include <file3.hh>
// Violation
// Violation
// file.h
#include <file2.cpp>
#include <file3.hh>
// Violation
// Violation
REPAIR
// file.cpp
#include <file2.h>
#include <file3.h>
// file.h
#include <file.cpp>
file.cpp
#include <file2.h>
#include <file3.h>
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 32
The #include directive shall use the <filename.h> notation to include header files [PREPROC09-2]
DESCRIPTION
The #include directive shall use the <filename.h> notation to include
header files.
SINCE
v7.1
BENEFITS
The include form "filename.h" is typically used to include local header
files.
However, due to the unfortunate divergence in vendor implementations, only
the <filename.h> form will be used.
EXAMPLE
#include "foo.h" // Violation
REPAIR
#include <foo.h>
// OK
#include <dir1/dir2/foo.h> // OK: relative path used
REFERENCES
JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.7 Header Filess, AV Rule 33
The #ifndef and #endif pre-processor directives will only be used to prevent multiple
inclusions of the same header file [PREPROC-10-3]
DESCRIPTION
The #ifndef and #endif pre-processor directives will only be used
as defined in below example to prevent multiple inclusions of the
same header file.
#ifndef Header_filename
#define Header_filename
// Header declarations...
#endif
SINCE
v7.1
BENEFITS
Conditional code compilation should be kept to a minimum as it can
significantly obscure testing and maintenance efforts.
EXAMPLE
#ifndef MAX
// Violation
// Violation
int a;
REPAIR
#ifndef FOO_H
#define FOO_H
int max = 10;
int a;
// OK
#endif
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 28
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
Only the following pre-processor directives shall be used: #ifndef, #define, #endif, #include
[PREPROC-11-2]
DESCRIPTION
Only the following pre-processor directives shall be used: #ifndef,
#define, #endif, #include
SINCE
v7.1
BENEFITS
Limit the use of the pre-processor to those cases where it is necessary.
EXAMPLE
#pragma once // Violation
REPAIR
#ifndef FOO_H
#define FOO_H
/* ... */
#endif
// OK
REFERENCES
1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS
Chapter 4.6 Pre-Processing Directives, AV Rule 26
2. MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems, Chapter 6, Section 16, Rule 16-2-1
3. The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
C++ macros shall only be used for include guards, type qualifiers, or storage class specifiers
[PREPROC-12-3]
DESCRIPTION
"C++ macros shall only be used for include guards, type qualifiers, or
storage
class specifiers. These are the only permitted uses of macros. C++ offers
const variable and function templates, which provide a type-safe
alternative
to the preprocessor."
SINCE
v7.2
NOTES
List of type qualifiers and storage class specifiers:
// type qualifiers:
const
volatile
// storage class specifiers:
auto
register
static
extern
mutable
BENEFITS
Improves code reliability and maintainability.
EXAMPLE
#define PI 3.14
REPAIR
// Violation
REFERENCES
MISRA C++:2008 - Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 16, Rule 16-2-2
Macro should not contain token pasting, variable argument list nor recursive macro calls
[PREPROC-13-3]
DESCRIPTION
"The use of the preprocessor must be limited to the inclusion of header
files
and simple macro definitions. Token pasting, variable argument lists
(ellipses),
and recursive macro calls are not allowed."
SINCE
v7.3
NOTES
The rule detects only direct recursion and indirect recursion if it is
limited
to two level and macros are defined in the same file.
BENEFITS
"The C preprocessor is a powerful obfuscation tool that can destroy code
clarity and befuddle many text based checkers. The effect of constructs
in unrestricted preprocessor code can be extremely hard to decipher,
even with a formal language definition in hand."
EXAMPLE
#define PASTING(a, b) a ## b
// Violation - ellipsis
// Violation - recursion
REPAIR
Do not use token pasting, variable argument lists (ellipses),
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
SINCE
v7.3
EXCEPTIONS
The rule does not report violations on macros defined as character, string
or
number constants, for example:
#define CONST1 10
// OK
#define CONST2 'A'
// OK
#define CONST3 "foo" // OK
Such cases are simple enough to not require braces.
Note that negative numbers like -10 are still violations of this rule.
BENEFITS
"The C preprocessor is a powerful obfuscation tool that can destroy code
clarity and befuddle many text based checkers. The effect of constructs
in unrestricted preprocessor code can be extremely hard to decipher,
even with a formal language definition in hand."
EXAMPLE
#define MAC1(a, b) a + b
REPAIR
// Violation - no braces
#define MAC1(a, b) (a + b)
// OK
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 8
SINCE
v7.3
BENEFITS
"Pointers are easily misused, even by experienced programmers. They can
make it
hard to follow or analyze the flow of data in a program, especially by
toolbased
static analyzers."
EXAMPLE
#define MAC1(a, b) *a + b
#define MAC2(a, b) (a + *b)
// Violation
// Violation
REPAIR
Do not use pointer dereference operations in macro definitions.
REFERENCES
The Power of Ten - Rules for Developing Safety Critical Code.
Rule 9
QT
Qt Best Practices
RULES
Every QObject subclass should contain a Q_OBJECT macro [QT-01-3]
QObject must not be inherited more than one time [QT-02-3]
It's only possible to connect a signal to a slot or a signal to another
signal [QT-03-3]
The methods inside the SIGNAL and SLOT macros have to exist [QT-04-1]
Mark signal emissions with the keyword "emit" to distinguish a signal
emission from a normal method call [QT-05-3]
Do not set Idle or Critical priority to QThreads. Use High/Low/Med only
[QT-06-3]
Do not force thread termination by calling QThread::terminate() [QT-07-1]
If using lock on a mutex in a function, release the lock in the same
function [QT-08-3]
Do not call new on QMutexLocker [QT-09-1]
Declare a copy constructor and operator= for any Qt - inherited objects
that have pointers [QT-10-3]
Do not use setWindowFlags function on a Widget [QT-11-4]
Do not directly set specific Widget attributes that are set by Qt kernel
[QT-12-1]
Never mix const and non-const iterators in assignment [QT-13-3]
If you use Q_DECLARE_FLAGS, you must also use
Q_DECLARE_OPERATORS_FOR_FLAGS [QT-14-3]
Q_DECLARE_OPERATORS_FOR_FLAGS must be in the global namespace,
Q_DECLARE_FLAGS inside the enum's namespace [QT-15-3]
The getters and setters of a Q_PROPERTY must exist and the types must
match [QT-16-3]
Properties of enum types must use Q_ENUMS [QT-17-3]
Non-const function should not be called on the Qt object [QT-18-3]
BENEFITS
While it is possible to use QObject as a base class without the Q_OBJECT
macro
and without meta-object code, neither signals and slots nor any of the
other
features meta type based features (Properties, class name, inheritance
checking, I18N, dynamic QObject casting) will be available if the Q_OBJECT
macro is not used. From the meta-object system's point of view, a QObject
subclass without meta code is equivalent to its closest ancestor with
meta-object code. This means for example, that QMetaObject::className()
will
not return the actual name of your class, but the class name of this
ancestor.
Also, using the dynamic casting function
T qobject_cast ( QObject * object )
will only be able to cast to the ancestor class type.
EXAMPLE
#include <QtCore/QObject>
class QFigure: public QObject
{
Q_OBJECT
private:
Q_DISABLE_COPY(QFigure)
};
class QCircle: public QFigure
present
{
private:
Q_DISABLE_COPY(QCircle)
};
REPAIR
#include <QtCore/QObject>
class QFigure: public QObject
{
Q_OBJECT
private:
Q_DISABLE_COPY(QFigure)
};
class QCircle: public QFigure
{
Q_OBJECT
// OK
private:
Q_DISABLE_COPY(QCircle)
};
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/metaobjects.html
BENEFITS
The meta-object system cannot properly merge the meta-information from two
QObject derived classes. The resulting meta-object file may or may not
compile,
and you will not be able to access all the signals and slots from both
super
classes. You will also not be able to cast the object to both super
classes.
Multiple inheritance from QObjects would also mean duplication of internal
data structures.
EXAMPLE
#include <QtCore/QObject>
#include <QtGui/QWidget>
class ClipboardInterface : public QObject
{
Q_OBJECT
public slots:
void cut();
void copy() const;
void paste();
private:
Q_DISABLE_COPY(ClipboardInterface)
};
class CustomWidget : public QWidget, public ClipboardInterface //
Violation
{
// inherits from two
QObjects
Q_OBJECT
private:
Q_DISABLE_COPY(CustomWidget)
};
REPAIR
// for workaround detailed description visit:
// http://doc.trolltech.com/qq/qq15-academic.html
#include <QtCore/QObject>
#include <QtGui/QWidget>
class ClipboardInterface
{
public:
virtual void cut() = 0;
virtual void copy() const = 0;
virtual void paste() = 0;
};
class ClipboardWrapper;
class CustomWidget : public QWidget, public ClipboardInterface
{
Q_OBJECT
// OK
public:
CustomWidget(QWidget *parent = 0);
void cut();
void copy() const;
void paste();
private:
ClipboardWrapper *wrapper;
Q_DISABLE_COPY(CustomWidget)
};
class ClipboardWrapper : public QObject, public ClipboardInterface
{
Q_OBJECT
public:
ClipboardWrapper(QObject *parent): QObject(parent)
{
Q_ASSERT(parent);
wrappedObject = qobject_cast<CustomWidget *>(parent);
Q_ASSERT(wrappedObject);
}
public slots:
void cut() { wrappedObject->cut(); }
void copy() const { wrappedObject->copy(); }
void paste() { wrappedObject->paste(); }
private:
ClipboardInterface *wrappedObject;
Q_DISABLE_COPY(ClipboardWrapper)
};
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/qq/qq15-academic.html#multipleinheritance
It's only possible to connect a signal to a slot or a signal to another signal [QT-03-3]
DESCRIPTION
Connecting a signal and a slot can be done by calling QObject::connect.
It's only possible to connect a signal to a slot or a signal to another
signal.
BENEFITS
Slots are to be considered observers, and are not possible to connect
together
as there would be no source of signal to trigger the slots. However, you
may
connect several slots to one signal. A slot cannot have a signal connected
to
it, but a signal can have a slot connected to it; the direction of the
connection is important. You can connect as many signals as you want to a
single
slot, and a signal can be connected to as many slots as you need. It is
even
possible to connect a signal directly to another signal.
(This will emit the second signal immediately whenever the first is
emitted.)
EXAMPLE
#include <QtCore/QObject>
class MyQObject: public QObject
{
Q_OBJECT
public:
MyQObject();
public slots:
int sampleSlot(QString qStr, const MyQObject& myQObjRef, int* i);
signals:
void someSignal(QString qStr);
private:
Q_DISABLE_COPY(MyQObject)
};
void myFunction(QString qStr)
{
MyQObject obj1, obj2;
QObject::connect(&obj1,
//
Violation
SLOT(sampleSlot(QString, const MyQObject&, int*)),
&obj2, SIGNAL(someSignal(QString)));
QObject::connect(&obj1,
//
Violation
SLOT(sampleSlot(QString, const MyQObject&, int*)),
&obj2, SLOT(sampleSlot(QString, const MyQObject&,
int*)));
}
REPAIR
#include <QtCore/QObject>
class MyQObject: public QObject
{
Q_OBJECT
public:
MyQObject();
public slots:
int sampleSlot(QString qStr, const MyQObject& myQObjRef, int* i);
signals:
void someSignal(QString qStr);
private:
Q_DISABLE_COPY(MyQObject)
};
void myFunction(QString qStr)
{
MyQObject obj1, obj2;
QObject::connect(&obj1, SIGNAL(someSignal(QString)),
// OK
&obj2, SIGNAL(someSignal(QString)));
QObject::connect(&obj1, SIGNAL(someSignal(QString)),
// OK
&obj2, SLOT(sampleSlot(QString, const MyQObject&,
int*)));
}
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/signalsandslots.html
The methods inside the SIGNAL and SLOT macros have to exist [QT-04-1]
DESCRIPTION
The methods inside the SIGNAL and SLOT macros have to exist (the arguments
have to match) and they have to be tagged as Q_SLOTS or Q_SIGNALS.
Here we have a simple example where we try to output a goodbye message,
note
that the name of the slot in the connection doesn't match the declaration.
The example will compile and run, but not produce the expected result.
NOTES
"Q_SLOTS" and "Q_SIGNALS" is equivalent to "slots" and "signals".
BENEFITS
Qt's signal & slot mechanism is very powerful since it offers dynamic
connections between signals and slots at runtime. This supports
development
of flexible scriptable and dynamic user interfaces, but comes with a
price:
The compiler won't warn you if a signal and slot connection is invalid at
compile time. You will get a warning at run time, which is usually too
late.
This rule enforces validity of signal and slot connection at code analysis
time.
EXAMPLE
#include <QtGui/QtGui>
class MyWidget: public QWidget
{
Q_OBJECT
public:
MyWidget( char* initText ) { qDebug() << initText; }
public slots:
void showGoodByeMessage() { qDebug() << "GoodBye"; }
private:
Q_DISABLE_COPY(MyWidget)
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWidget w1( "New MyWidget" );
MyWidget w2( "New MyWidget" );
w1.show();
w2.show();
// Violation showGoodBye() is not slot method
QObject::connect(&app, SIGNAL(lastWindowClosed()),
&w1, SLOT(showGoodBye()));
return app.exec();
}
REPAIR
#include <QtGui/QtGui>
class MyWidget: public QWidget
{
Q_OBJECT
public:
MyWidget( char* initText ) { qDebug() << initText; }
public slots:
void showGoodByeMessage() { qDebug() << "GoodBye"; }
private:
Q_DISABLE_COPY(MyWidget)
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWidget w1( "New MyWidget" );
MyWidget w2( "New MyWidget" );
w1.show();
w2.show();
// OK
QObject::connect(&app, SIGNAL(lastWindowClosed()),
&w1, SLOT(showGoodByeMessage()));
return app.exec();
}
REFERENCES
Recommended by Parasoft and Trolltech
Mark signal emissions with the keyword "emit" to distinguish a signal emission from a normal
method call [QT-05-3]
DESCRIPTION
Signal emissions should be marked with the keyword "emit",
to distinguish a signal emission from a normal method call.
BENEFITS
"emit" expands to nothing, so it's not necessary, but considered good
style.
EXAMPLE
#include <QtCore/QObject>
class QFigure : public QObject
{
Q_OBJECT
public:
void someSignal(double);
void test();
signals:
void someSignal(int);
private:
Q_DISABLE_COPY(QFigure)
};
void QFigure::test()
{
emit someSignal(1);
emit someSignal(1.5); // Violation - someSignal(double) is not a signal
someSignal(1);
// Violation - emit keyword omitted
someSignal(1.5);
}
REPAIR
#include <QtCore/QObject>
class QFigure : public QObject
{
Q_OBJECT
public:
void someSignal(double);
void test();
signals:
void someSignal(int);
private:
Q_DISABLE_COPY(QFigure)
};
void QFigure::test()
{
emit someSignal(1);
someSignal(1.5);
emit someSignal(1);
someSignal(1.5);
}
// OK
// OK
REFERENCES
Recommended by Parasoft and Trolltech
Do not set Idle or Critical priority to QThreads. Use High/Low/Med only [QT-06-3]
DESCRIPTION
Do not set Idle or Critical priority to QThreads. Use High/Low/Med only.
BENEFITS
Idle and Critical settings can cause live-lock or starvation.
Some Operating Systems will not allow escalating the priorities of
threads,
so the results are platform specific.
EXAMPLE
#include <QtGui/QtGui>
void myFunction( QThread* qt1, QThread* qt2 ) {
qt1->start( QThread::IdlePriority );
qt2->setPriority( QThread::IdlePriority );
}
// Violation
// Violation
REPAIR
#include <QtGui/QtGui>
void myFunction( QThread* qt1, QThread* qt2 ) {
qt1->start( QThread::NormalPriority );
qt2->setPriority( QThread::InheritPriority );
}
REFERENCES
Recommended by Parasoft and Trolltech
// OK
// OK
BENEFITS
This function is dangerous and its use is discouraged. The thread may or
may
not be terminated immediately, depending on the operating systems
scheduling
policies. The thread can be terminate at any point in its code path.
Threads
can be terminated while modifying data. There is no chance for the thread
to
cleanup after itself, unlock any held mutexes, etc.
EXAMPLE
#include <QtGui/QtGui>
class MyQThread : public QThread
{
Q_OBJECT
public:
void terminate();
void run();
MyQThread();
private:
Q_DISABLE_COPY(MyQThread)
};
void MyQThread::terminate()
{
QThread::terminate(); // Violation
}
void foo(){
MyQThread qt;
qt.terminate();
}
REPAIR
Do not use QThread::terminate(). Return from the thread's run() function
instead, or throw an exception and catch it at the end of run().
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qthread.html#terminate
If using lock on a mutex in a function, release the lock in the same function [QT-08-3]
DESCRIPTION
If using lock on a mutex in a function, release the lock in the same
function.
BENEFITS
Not unlocking a locked mutex in the same function may lead to inconsistent
locks and unlocks, which will in turn lead to potential deadlocks in your
code.
To ensure that a locked mutex is always unlocked when the function ends,
both
by normal and exception code paths, consider using the QMutexLocker
convenience
class.
EXAMPLE
#include<QtGui/QtGui>
void myExample(bool isBlue, bool isFigure)
{
QMutex m;
QMutex n;
m.lock();
if (isBlue && isFigure)
return;
// Violation
m.unlock();
/* code */
m.lock();
n.lock();
}
REPAIR
// Violation
// Violation
#include<QtGui/QtGui>
void myExample(bool isBlue, bool isFigure)
{
QMutex m;
QMutex n;
m.lock();
// OK
// OK
// OK
/* code */
m.unlock();
n.unlock();
// OK
// OK
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qmutex.html#details
BENEFITS
QMutexLocker is only a convenience class for locking and unlocking a
mutex.
The whole point is to keep the class on the stack, so an exception in your
code
will also release the mutex, should something fail.
EXAMPLE
#include <QtCore/QMutex>
#include <limits.h>
QMutex mutex;
int i = 0;
void increaseCounter()
{
QMutexLocker *locker = new QMutexLocker(&mutex);
if (i == INT_MAX) {
qDebug("WARNING: Maximum count reached!!");
return;
}
++i;
delete locker;
}
REPAIR
#include <QtCore/QMutex>
#include <limits.h>
// Violation
QMutex mutex;
int i = 0;
void increaseCounter()
{
QMutexLocker locker(&mutex);
// OK
if (i == INT_MAX) {
qDebug("WARNING: Maximum count reached!!");
return;
}
++i;
}
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qmutexlocker.html
Declare a copy constructor and operator= for any Qt - inherited objects that have pointers [QT10-3]
DESCRIPTION
The assignment operator and copy constructor should be private without
an implementation for all QObject subclasses.
BENEFITS
Classes which have pointers as members cannot be copied around with the
compiler implemented copy constructors or assignment operator, as that
will
break implicit sharing and may lead to unexpected crashes.
EXAMPLE
#include <QtGui/QtGui>
class MyQObject : public QObject
{
Q_OBJECT
};
// Violation
// Violation
public:
MyQWidget( MyQWidget& );
MyQWidget& operator=( MyQWidget& );
};
REPAIR
#include <QtGui/QtGui>
class MyQObject : public QObject
{
Q_OBJECT
// OK
private:
MyQObject( MyQObject& );
MyQObject& operator=( MyQObject& );
};
class MyQWidget : public QWidget
{
Q_OBJECT
private:
Q_DISABLE_COPY(MyQWidget)
};
REFERENCES
Recommended by Parasoft and Trolltech
// OK
BENEFITS
Using setWindowFlags in your code can result in widgets which disappear
and
reappear, and change their looks. The widget is destroyed and recreated
for
each call. The setWindowFlags function should only be used on a widget is
not
yet shown.
EXAMPLE
#include <QtGui/QWidget>
class PreviewWindow : public QWidget
{
Q_OBJECT
public:
PreviewWindow( QWidget *parent = 0, Qt::WindowFlags flags = 0 );
void setWindowFlags( Qt::WindowFlags flags );
void setProperty( Qt::WindowFlags flags )
{
setWindowFlags( flags );
//
Violation
}
private:
Q_DISABLE_COPY(PreviewWindow)
};
void updatePreview( )
{
Qt::WindowFlags flags = 0;
PreviewWindow *previewWindow = new PreviewWindow( 0, flags );
PreviewWindow previewWindowObj( 0, flags );
previewWindow->setWindowFlags( flags );
Violation
previewWindowObj.setWindowFlags( flags );
Violation
}
//
//
REPAIR
#include <QtGui/QWidget>
class PreviewWindow : public QWidget
{
Q_OBJECT
public:
PreviewWindow( QWidget *parent = 0, Qt::WindowFlags flags = 0 );
void setWindowFlags( Qt::WindowFlags flags );
void setProperty( Qt::WindowFlags flags )
{
// OK
}
private:
Q_DISABLE_COPY(PreviewWindow)
};
void updatePreview( )
{
Qt::WindowFlags flags = 0;
PreviewWindow *previewWindow = new PreviewWindow( 0, flags );
PreviewWindow previewWindowObj( 0, flags );
}
REFERENCES
Recommended by Parasoft and Trolltech
// OK
// OK
Do not directly set specific Widget attributes that are set by Qt kernel [QT-12-1]
DESCRIPTION
Do not directly set specific Widget attributes that are set by Qt kernel.
BENEFITS
Qt uses the widget attributes to signal states to the rest of the
framework.
Altering the attributes which are set by the Qt kernel may have adverse
effects,
and in worst case make your application crash.
EXAMPLE
#include <QtGui/QWidget>
class PreviewWindow : public QWidget
{
Q_OBJECT
public:
PreviewWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0);
private:
Q_DISABLE_COPY(PreviewWindow)
};
void updatePreview( Qt::WindowFlags flags )
{
PreviewWindow *previewWindow = new PreviewWindow( 0, flags );
previewWindow->setAttribute(Qt::WA_UnderMouse, true);
previewWindow->setAttribute(Qt::WA_Disabled, true);
previewWindow->setAttribute(Qt::WA_SetPalette, true);
previewWindow->setAttribute(Qt::WA_SetCursor, true);
previewWindow->setAttribute(Qt::WA_SetFont, true);
previewWindow->setAttribute(Qt::WA_Disabled, true);
}
//
//
//
//
//
//
Violation
Violation
Violation
Violation
Violation
Violation
REPAIR
Do not directly set specific Widget attributes that are set by Qt kernel.
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/qt.html#WidgetAttribute-enum
BENEFITS
When mixing const and non-const iterators you loose the benefits of using
const iterators, as the non-const iterator may detach the data it iterates
on.
Also, using non-const iterators on a const data set will not work, and
will
result in a compile error.
EXAMPLE
#include <QtGui/QWidget>
void myFunction()
{
QList<int> nonConstList;
for (QList<int>::ConstIterator it = nonConstList.begin(); ; ) //
Violation
{
}
}
REPAIR
#include <QtGui/QWidget>
void myFunction()
{
QList<int> nonConstList;
const QList<int> constList;
for (QList<int>::ConstIterator it = nonConstList.constBegin(); ; )
OK
{
}
//
REFERENCES
Recommended by Parasoft and Trolltech
//
BENEFITS
Q_DECLARE_FLAGS creates a type-safe way of storing OR-combinations of enum
values. Q_DECLARE_OPERATORS_FOR_FLAGS declares a global operator|() for
these
type-safe flags, so they may be used outside the scope of where the flags
are declared.
EXAMPLE
#include <QtGui/QtGui>
enum Value { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Values,Value)
// Violation
REPAIR
#include <QtGui/QtGui>
enum Value { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Values,Value)
Q_DECLARE_OPERATORS_FOR_FLAGS(Values)
REFERENCES
Recommended by Parasoft and Trolltech
// OK
BENEFITS
By declaring the flags in the enums scope and the operators in the global
scope, you may type-safely OR together scoped flags. If either
Q_DECLARE_FLAGS
or Q_DECLARE_OPERATORS_FOR_FLAGS is in the wrong scope, you will not be
able
to OR together the flags anywhere in your code, even if you use the
correct
scopes on the flags.
EXAMPLE
#include <QtGui/QtGui>
namespace N
{
enum Value { FirstVal, SecondVal, ThirdVal };
namespace M
{
Q_DECLARE_FLAGS(Values, Value)
Q_DECLARE_OPERATORS_FOR_FLAGS(Values)
}
}
namespace S
{
enum Item { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Items, Item)
Q_DECLARE_OPERATORS_FOR_FLAGS(Items)
}
// Violation
// Violation
// Violation
REPAIR
#include <QtGui/QtGui>
namespace N
{
enum Value { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Values, Value)
}
Q_DECLARE_OPERATORS_FOR_FLAGS(N::Values)
namespace S
{
enum Item { FirstVal, SecondVal, ThirdVal };
Q_DECLARE_FLAGS(Items, Item)
}
Q_DECLARE_OPERATORS_FOR_FLAGS(S::Items)
REFERENCES
Recommended by Parasoft and Trolltech
// OK
// OK
// OK
// OK
The getters and setters of a Q_PROPERTY must exist and the types must match [QT-16-3]
DESCRIPTION
The getters and setters of a Q_PROPERTY must exist and the types must
match.
BENEFITS
The Q_PROPERTY macro tells the Qt meta type system how to get and set
a property. The property has a type, a name and getter and setter
methods. The getter should return the type of the property and have no
arguments, the setter should have exactly one argument that is either the
property's type or a const reference to the type.
EXAMPLE
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };
class MyQObject: public QObject
{
Q_OBJECT
Q_ENUMS(MyEnum)
Q_PROPERTY(MyEnum id READ id WRITE setId)
public:
void id();
void setId(MyEnum, int);
private:
Q_DISABLE_COPY(MyQObject)
};
REPAIR
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };
REFERENCES
Recommended by Parasoft and Trolltech
BENEFITS
Q_ENUM registers an enum with the Qt meta-object system, so that a
property
of this type can be properly introspected. This lets Designer modify the
value
if it's a widget member, and QSA to alter the property value.
EXAMPLE
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };
class MyQObject: public QObject // Violation
{
Q_OBJECT
Q_PROPERTY(MyEnum id READ id WRITE setId)
public:
MyEnum id();
void setId(MyEnum);
private:
Q_DISABLE_COPY(MyQObject)
};
REPAIR
#include <QtCore/QObject>
enum MyEnum { FirstVal, SecondVal, ThirdVal };
REFERENCES
Recommended by Parasoft and Trolltech
http://doc.trolltech.com/4.2/properties.html
SINCE
v7.0
BENEFITS
Qt has many implicitly shared classes. These classes share their data
(very little overhead), but will detach from one another, and do a deep
copy
(heavy, a "normal" copy and update of internal structures) when a nonconst
EXAMPLE
#include <QtCore/QList>
// Using the non-const operator[](int) function
int main(int argc, char **argv)
{
QList<int> list_obj;
list_obj << 10 << 100 << 1000;
QList<int> copy = list_obj; // Create a shared copy
for (int i = 0; i < list_obj.size(); ++i)
printf("Index %d: %d\n", i, list_obj[i]); // Violation, detaches
return 0;
}
REPAIR
#include <QtCore/QList>
// Using the const at(int) function
int main(int argc, char **argv)
{
QList<int> list_obj;
list_obj << 10 << 100 << 1000;
list_obj[1] = 20;
// OK
// OK
REFERENCES
Recommended by Parasoft and Trolltech
SECURITY
Security
RULES
Avoid functions which use time from standard C library [SECURITY-01-2]
Avoid functions which use random numbers from standard C library
[SECURITY-02-2]
Usage of system properties should be restricted [SECURITY-03-2]
Use care to ensure that LoadLibrary() will load the correct library
[SECURITY-04-2]
Avoid using functions printf/wprintf with only one variable parameter
[SECURITY-05-2]
Avoid functions which use time from MFC library [SECURITY-06-3]
Don't use unsafe C functions that do write to range-unchecked buffers
[SECURITY-07-3]
Avoid using functions fprintf/fwprintf with only two parameters, when
second parameter is a variable [SECURITY-08-2]
Avoid using data() function from 'string' class of standard library
[SECURITY-09-2]
Avoid using vfork() function [SECURITY-10-2]
Avoid using unsecured shell functions that may be affected by shell
metacharacters [SECURITY-11-2]
Avoid using unsafe string functions which may cause buffer overflows
[SECURITY-12-2]
Avoid using unsafe string functions that do not check bounds [SECURITY-132]
Do not use scanf and fscanf functions without specifying variable size in
format string [SECURITY-14-2]
Do not print potentially sensitive information, resulting from an
application error into exception messages [SECURITY-15-2]
Never use gets() [SECURITY-16-1]
Avoid passing non-const parameters or variables into exec [SECURITY-17-2]
Avoid passing dynamically created strings into exec [SECURITY-18-2]
Usage of functions prone to race is not allowed [SECURITY-19-2]
Avoid passing user input into methods as parameters [SECURITY-20-2]
Do not use 'syslog' function for logging purposes [SECURITY-21-2]
Do not use mbstowcs() function [SECURITY-22-2]
Beware of functions which may return the current directory or the windows
directory [SECURITY-23-2]
Avoid using InitializeCriticalSection [SECURITY-24-2]
Avoid using thread-unsafe functions [SECURITY-25-2]
Do not use 'setuid' in source code [SECURITY-26-2]
Don't use chmod(), chown(), chgrp() [SECURITY-27-2]
Standard random number generators should not be used to generate
randomness for security reasons [SECURITY-28-2]
BENEFITS
Prevents the use of functions from standard C library,
which may open security holes.
Getting the current system time might be suspicious
and could lead to security problems
if used as a key for accessing sensitive information
or allow access to specific functions.
Do not use the following functions:
time, clock, ctime, gmtime, localtime, mktime, strftime.
EXAMPLE
#include <time.h>
void dangerFunction(time_t time);
int main ()
{
time_t rawtime;
tm * ptm;
time ( &rawtime );
// Violation
ptm = gmtime ( &rawtime ); // Violation
dangerFunction(rawtime);
return 0;
}
REPAIR
Remove usage of time-related functions from the standard C library
REFERENCES
Avoid functions which use random numbers from standard C library [SECURITY-02-2]
DESCRIPTION
This rule detects the use of the following functions from standard C
library,
which generate random numbers:
-rand
-random
-randomize
-srand
BENEFITS
Prevents the use of functions that use random numbers from standard C
library.
Since rand() and similar functions use the last generated number
as the seed to create the next number,
it is possible to guess or calculate the next number.
Quite frequently, random session IDs for Web sessions
are generated with random number generator.
Since the random number generators from Standard C library
are not sufficiently strong,
hackers can guess the next number and spoof the sessions,
gaining access to privileged data.
EXAMPLE
#include <stdlib.h>
#include <time.h>
void main( void )
{
srand((unsigned)time( NULL ));
int y = rand();
}
// Violation
// Violation
REPAIR
Remove usage of rand(), random(), randomize(), srand() functions.
REFERENCES
1. http://www.dwheeler.com/flawfinder/
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
4. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-327
http://cwe.mitre.org/top25/#CWE-327
BENEFITS
By controlling use of environment variables in the applications, they are
made
more secure. Environment variables can be used as security holes.
If a malicious user passes a specifically crafted string into a running
program
via an environment variable, a buffer overflow attack can be launched.
On the other hand, if a program writes sensitive information
(such as a password) into an environment variable with putenv, it can be
captured and used to gain unauthorized privileges or access to sensitive
data.
EXAMPLE
#include <stdlib.h>
void foo( void ) {
char *envvar;
envvar = getenv( "LIB" );
putenv( "LIB=c:\\mylib;c:\\yourlib" );
}
// Violation
// Violation
REPAIR
Do not use system properties and environment variables in source code.
REFERENCES
1. https://buildsecurityin.uscert.gov/portal/article/knowledge/coding_rules/RULE_0051.xml
2. PCI Data Security Standard (PCI DSS) Version 1.2
Use care to ensure that LoadLibrary() will load the correct library [SECURITY-04-2]
DESCRIPTION
"Ensure that you specify a fully-qualified filename for the library to
ensure
that the correct library is always loaded.
When a library needs to be loaded you should consider using LoadLibraryEx
with
the LOAD_WITH_ALTERED_SEARCH_PATH parameter to ensure that the correct
library
is loaded."
The rule reports a violation if in code is used the function LoadLibrary
or the function LoadLibraryEx without LOAD_WITH_ALTERED_SEARCH_PATH
argument.
NOTES
"If you cannot use LoadLibraryEx, ensure that the lpszFileName parameter
is a fully qualified filename, including the file extension. If it is not
fully
qualified, then the intended module can be substituted by an attacker.
Also, the system will use '.dll' for the file extension if it is not
specified,
so '.' should be appended to the end if the intended library file does not
have
an extension."
BENEFITS
The use of this rule prevents than an attacker could inject a Trojan horse
DLL
within your process by placing a 'tainted' DLL in a location in the DLL
search
path that is found before the intended DLL.
EXAMPLE
#include <windows.h>
void foo()
{
HMODULE hModule1 = LoadLibrary(TEXT("someapp.dll"));
// Violation
// Violation
REPAIR
#include <windows.h>
void foo()
{
HMODULE hModule = LoadLibraryEx(
TEXT("C:\\The\\Right\\Directory\\someapp.dll"),
NULL,
LOAD_WITH_ALTERED_SEARCH_PATH
);
}
// OK
REFERENCES
1. https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/766BSI.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
Avoid using functions printf/wprintf with only one variable parameter [SECURITY-05-2]
DESCRIPTION
This rule detects the use of the functions printf/wprintf with only one
variable parameter and no format specifiers.
BENEFITS
This rule prevents security attack using format strings. If a printf
functions
is passed a variable without format specifiers, the variable can contain
a cleverly formatted string (including format characters %n, %x, and %s)
that can be used to execute malicious instructions or crash the
application.
EXAMPLE
#include <wchar.h>
#include <stdio.h>
void foo( ) {
char* caption = "caption";
wchar_t widechar = L'x';
printf( caption );
wprintf( &widechar );
// Violation
// Violation
REPAIR
#include <wchar.h>
#include <stdio.h>
void foo( ) {
char* caption = "caption";
wchar_t wch = L'x';
int k = 7;
printf( "char: %s", caption );
printf( "int: %s", k );
// OK
// OK
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/controlformatting.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-134
http://cwe.mitre.org/top25/#CWE-134
BENEFITS
Prevents the use of functions from MFC library, which may open security
holes.
Getting the current system time might be suspicious and could lead to
security
problems if used as a key for accessing sensitive information or allow
access
to specific functions. Do not use the following functions:
- GetTime
- GetYear
- GetMonth
- GetDay
- GetHour
- GetMinute
- GetSecond
- GetDayOfWeek
EXAMPLE
#include <afx.h>
void dangerFunction(time_t t);
int main () {
CTime t(NULL);
time_t Time = t.GetTime(); // Violation
t.GetHour();
// Violation
t.GetMinute();
// Violation
dangerFunction(Time);
return 0;
}
REPAIR
Remove usage of functions from MFC library, which may open security hole.
REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents using functions which may cause overflow.
EXAMPLE
#include <string.h>
void foo( void ) {
char* str1 = "testcase";
char* str2 = "testcase";
char* str3 = 0;
str3 = strcat( str1, str2 );
}
// Violation
REPAIR
Don't use the unsafe C legacy.
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Type Safety", Rule 99
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
Avoid using functions fprintf/fwprintf with only two parameters, when second parameter is a
variable [SECURITY-08-2]
DESCRIPTION
This rule detects the use of the functions fprintf/wfprintf with two
parameters
and no format specifiers, when second parameter is a variable parameter.
BENEFITS
This rule prevents security attack using format strings.
If a fprintf functions is passed a variable without format specifiers,
the variable can contain a cleverly formatted string
(including format characters %n, %x, and %s) that can be used to execute
malicious instructions or crash the application.
EXAMPLE
#include <stdio.h>
#include <wchar.h>
void foo( ) {
FILE *stream;
char
c = '\n';
wchar_t d=8;
stream = fopen( "fprintf.out", "w" );
fprintf( stream, &c );
fwprintf( stream, &d );
fclose( stream );
}
REPAIR
#include <stdio.h>
#include <wchar.h>
void foo( ) {
FILE *stream;
// Violation
// Violation
int
i = 10;
char
s[] = "example string";
char
c = '\n';
unsigned short d=8;
stream = fopen( "fprintf.out", "w" );
fprintf( stream,"abcd");
// OK
fprintf( stream, "%s%c", s, c );// OK
fprintf( stream, "%d\n", i );
// OK
fwprintf(stream,L"abc:%d",i);
fwprintf(stream,L"abcd");
// OK
// OK
fclose( stream );
}
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/controlformatting.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-134
http://cwe.mitre.org/top25/#CWE-134
Avoid using data() function from 'string' class of standard library [SECURITY-09-2]
DESCRIPTION
This rule detects code that uses the data() member function from string
class
of standard library.
BENEFITS
String::data() returns the character string contained in the string object
without a terminating character. In certain contexts, especially when
interfacing with C-style legacy code, this may lead to buffer overflows
and other string-related security vulnerabilities.
Instead of using the data() function, use c_str(),
which always returns a terminated string.
EXAMPLE
#include <string>
void bar(const char* param);
void foo()
{
using namespace std;
string str1 ( "example string" );
bar(str1.data());
// Violation
string *ptr;
ptr=&str1;
const char *ptr2 =
ptr->data();
REPAIR
#include <string>
void bar(const char* param);
// Violation
void foo()
{
using namespace std;
string str1 ( "example string" );
bar(str1.c_str());
string *ptr;
ptr=&str1;
const char *ptr2 =
ptr->c_str();
// OK
// OK
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/libraryc.html#STD-STRING
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Prevents the use of the vfork() function,
which can easily fail when the code changes
or even when the compiler version changes.
There are a number of problems with vfork().
From a portability point-of-view,
the problem with vfork() is that it's actually fairly tricky
for a process to not interfere with its parent,
especially in high-level languages.
The "not interfering" requirement applies to the actual machine code
generated,
and many compilers generate hidden temporaries
and other code structures that cause unintended interference.
Use the fork() function instead of the vfork() function.
EXAMPLE
#include <unistd.h>
void main( void )
{
vfork( ); // Violation
}
REPAIR
#include <unistd.h>
void main( void )
{
fork( ); // OK
}
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoidvfork.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
Avoid using unsecured shell functions that may be affected by shell metacharacters
[SECURITY-11-2]
DESCRIPTION
This rule detects code that uses environment functions:
popen, system, execlp, execvp, _exec, exec
According to David A. Wheeler (see reference below):
"Many systems, such as the command line shell and SQL interpreters,
have "metacharacters" - characters that are not interpreted as data.
Those characters are: { & ; ` ' \ " | * ? ~ < > ^ ( ) [ ] { } $ \n \r }.
Such characters might commands, or delimit data from commands or other
data.
If your program invokes those other systems and allows attackers to insert
such metacharacters, the usual result is that an attacker can completely
control your program.
What makes the shell metacharacters particularly pervasive is that several
important library calls, such as popen() and system() are implemented
by calling the command shell, meaning that they will be affected by shell
metacharacters too.
Similarly, execlp() and execvp() may cause the shell to be called.
Many guidelines suggest avoiding popen(), system(), execlp(), execvp()
entirely and use execve() directly in C when trying to spawn a process."
BENEFITS
Prevents the use of unsecured shell functions.
EXAMPLE
#ifdef __GNUC__
#include <unistd.h>
#else
#include <process.h>
#endif
void main( void ) {
execl( "c:\\command.com", "", "_execl", "", "" );
}
// Violation
REPAIR
Do not use unsecured system functions in your program.
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/handlemetacharacters.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
Avoid using unsafe string functions which may cause buffer overflows [SECURITY-12-2]
DESCRIPTION
This rule detects code that uses unsafe string functions from C library:
strcpy, strcat, sprintf, vsprintf, gets
According to David A. Wheeler (see reference below),
"C functions users must avoid using dangerous functions
that do not check bounds unless they've ensured
that the bounds will never get exceed.
Functions to avoid in most cases (or ensure protection) include the
functions
strcpy(), strcat(), sprintf() (with cousin vsprintf()), and gets().
These should be replaced with functions such as
strncpy(), strncat(), snprintf(), fgets(), respectively."
See also; SECURITY-12,SECURITY-13, SECURITY-16
BENEFITS
Prevents the use of functions which may cause buffer overflows.
EXAMPLE
#include <string.h>
void test()
{
char buffer[16];
strcpy(buffer, "To be ");
strcat(buffer, "or not to be");
}
// Violation
// Violation
REPAIR
#include <string.h>
void test()
{
char buffer[16];
strncpy(buffer, "To be ", 7);
strncat(buffer, "or not to be", 6);
// OK
// OK
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dangersc.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
Avoid using unsafe string functions that do not check bounds [SECURITY-13-2]
DESCRIPTION
This rule detects code that uses unsafe string functions:
scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf, realpath,
getopt, getpass, streadd, strecpy, strtrns, getwd, snprintf
According to David A. Wheeler (see reference below),
"C functions users must avoid using dangerous functions
that do not check bounds unless they've ensured
that the bounds will never get exceeded.
The function strlen() should be avoided
unless you can ensure that there will be a terminating NIL character to
find.
The scanf() family (scanf(), fscanf(), sscanf(), vscanf(), vsscanf(),
and vfscanf()) is often dangerous to use;
do not use it to send data to a string without controlling the maximum
length
(the format %s is a particularly common problem).
Other dangerous functions that may permit buffer overruns
(depending on their use) include realpath(), getopt(), getpass(),
streadd(),
strncpy(), and strtrns().
You must be careful with getwd();
the buffer sent to getwd() must be at least PATH_MAX bytes long.
The select() helper macros FD_SET(), FD_CLR(), and FD_ISSET()
do not check that the index fd is within bounds;
make sure that fd >= 0 and fd <= FD_SETSIZE
(this particular one has been exploited in pppd).
Unfortunately, snprintf()'s variants have additional problems.
Officially, snprintf() is not a standard C function
in the ISO 1990 (ANSI 1989) standard,
though sprintf() is, so not all systems include snprintf()
others call sprintf directly what could make horrible thing."
See also: SECURITY-07,SECURITY-12, SECURITY-16
BENEFITS
Prevents the use of functions which may cause overflows.
EXAMPLE
#include <stdio.h>
void main( void ) {
char* str = 0;
scanf( "%s", str );
}
// Violation
REPAIR
Remove usage of unsafe string functions.
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dangersc.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
Do not use scanf and fscanf functions without specifying variable size in format string
[SECURITY-14-2]
DESCRIPTION
This rule detects code that uses 'scanf' and 'fscanf' functions
without specifying variable size in format string.
BENEFITS
Typically, scanf functions are used to read user-specified parameters
into arrays of variables.
Unless the size of variables in format strings is specified,
an attacker may use crafted strings to exploit buffer overflows
with fixed size arrays.
By requiring to constrain the format specification using variable sizes,
the rule prevents this security vulnerability.
EXAMPLE
#include <stdio.h>
void main( ) {
char tcChar[10];
char cChar;
float fFloat;
FILE *stream;
stream = fopen( "fprintf.out", "w" );
scanf("%s",&tcChar);
scanf("%f",&fFloat);
// Violation
// Violation
fscanf(stream,"%s",&tcChar);
// Violation
fscanf(stream,"%c%f",&cChar,&fFloat); // Violation
}
REPAIR
#include <stdio.h>
void
main( ) {
char tcChar[10];
char cChar;
float fFloat;
FILE *stream;
stream = fopen( "fprintf.out", "w" );
scanf("%c",&cChar);
scanf("%10s",&tcChar);
scanf("%5f",&fFloat);
// OK
// OK
// OK
fscanf(stream,"%c",&cChar);
fscanf(stream,"%10s",&tcChar);
fscanf(stream,"%5f",&fFloat);
// OK
// OK
// OK
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/ccpp.html
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO
/control-formatting.html
https://buildsecurityin.us-cert.gov/portal/article/knowledge
/coding_rules/RULE_0119.xml
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
Do not print potentially sensitive information, resulting from an application error into
exception messages [SECURITY-15-2]
DESCRIPTION
Do not print potentially sensitive information,
resulting from an application error into exception messages.
Rule disallows printing messages in catch block.
BENEFITS
Prevents the application from leaking potentially sensitive information,
resulting from an application error.
EXAMPLE
#include <stdlib.h>
#include <stdio.h>
class LoginException{
public:
int tmp;
char* getMessage();
};
class CLogin {
public:
void login(){};
};
void log( char *text){};
void foo( int i ) {
CLogin lc;
try {
lc.login();
} catch (LoginException le1) {
// login failed
::printf( le1.getMessage() ); // Violation
exit( 1 );
}
}
REPAIR
#include <stdlib.h>
#include <stdio.h>
class LoginException{
public:
int tmp;
char* getMessage();
};
class CLogin {
public:
void login(){};
};
void log( char *text){};
void foo( int i ) {
CLogin lc;
try {
lc.login();
} catch (LoginException le2) {
exit( 1 );
}
}
// OK
REFERENCES
1. http://www.atsec.com/downloads/pdf/secure-coding-guidelines.pdf
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Prevents the use of function which may cause buffer overflows.
EXAMPLE
#include <stdio.h>
void main( ) {
char line[100];
printf( "Input a string: " );
gets( line );
printf( "The line entered was: %s\n", line );
// Violation
REPAIR
#include <stdio.h>
void main( ) {
char line[100];
printf( "Input a string: " );
fgets( line, 100, stdin );
printf( "The line entered was: %s\n", line );
}
// OK
REFERENCES
1. Linux Programmer's Manual (3),
http://trajano.us.es/clases/lcd/man/man3/ungetc.3.html
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
3. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
4. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
BENEFITS
An attacker can potentially insert a malicious string fragment
into a dynamically created string.
Such fragment may allow the attacker to execute a specified command,
resulting in a security breach.
EXAMPLE
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#define _execl execl
#else
#include <process.h>
#endif
void foo( ) {
char *param = "C:\\command.com";
_execl( param, "", "_execl", "", NULL );
}
REPAIR
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#define _execl execl
#else
#include <process.h>
#endif
void foo( ) {
// Violation
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Prevents running native applications. Having string variables passed into
an exec() method could provide system access to an outside program.
Server applications should never access native applications.
EXAMPLE
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#include <string.h>
#define _execl execl
#else
#include <process.h>
#endif
class MyClass {
public:
char* text( );
};
void foo( char* prog ) {
MyClass *v1 = 0;
char * v4=v1->text();
prog = strcat( "c:\\", "command.com" );
_execl( prog, "", "_execl", "", NULL );
// Violation
_execl( v1->text(), "", "_execl", "", NULL );// Violation
_execl( v4, "", "_execl", "", NULL );
// Violation
}
REPAIR
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#define _execl execl
#else
#include <process.h>
#endif
void foo( char* prog ) {
_execl( "C:\\command.com", "", "_execl", "", NULL );
}
// OK
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents anomalous behavior of race conditions functions.
EXAMPLE
#ifdef __GNUC__
#include <unistd.h>
#include <stdlib.h>
#else
#include <io.h>
#endif
void foo( ) {
access( "path", 0 );
unlink( "/pathname" );
mktemp( "template" );
}
// Violation
// Violation
// Violation
REPAIR
Remove usage of prone to race functions.
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoidrace.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Using direct user input in the application can open doors
to buffer overflow and SQL injection attacks.
User input must be validated before being processed by the application.
EXAMPLE
#include <iostream>
#include <stdio.h>
using namespace std;
void function( int param );
void foo( int param ) {
int var1;
int var2=0;
cin >> var1;
function( var1 );// Violation
scanf( "%d", &var2 );
function( var2 );// Violation
}
REPAIR
#include <iostream>
#include <stdio.h>
using namespace std;
void function( int param );
void foo( ) {
int var1 = 0;
int var2 = 0;
cin >> var1;
// part of code manipulating var1 without using function with var1 as
parameter
REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents using insecure 'syslog' function.
EXAMPLE
#include <syslog.h>
int main()
{
syslog(LOG_INFO, "Some info"); // Violation
}
REPAIR
Do not use 'syslog' function in your code.
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents using unsafe mbstowcs() function.
EXAMPLE
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
int i;
char
*pmbhello = (char *)malloc( MB_CUR_MAX );
wchar_t *pwc
= (wchar_t *)malloc( sizeof( wchar_t ));
i = mbstowcs( pwc, pmbhello, MB_CUR_MAX );
// Violation
REPAIR
Do not use mbstowcs().
REFERENCES
1. https://buildsecurityin.uscert.gov/portal/article/knowledge/coding_rules/RULE_0072.xml
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
Beware of functions which may return the current directory or the windows directory
[SECURITY-23-2]
DESCRIPTION
The rule reports a violation if in code is used the function
GetTempPath().
"GetTempPath() returns the file path to the temporary directory.
GetTempPath() raises two concerns. First, a buffer overflow condition
could
exist if the path to the temporary directory is longer than the buffer
allocated to store this information. Second, a path to an insecure
directory
could be returned. Also, Windows does not guarantee that the returned
paths
are valid or useable (e.g. writable) for temporary files."
BENEFITS
"An attacker could take advantage of either weakness in the functionality
of GetTempPath(). First, if Windows returns a path to which the attacker
can read or write (e.g. c:\temp), he or she will be able to read or alter
any data in the temporary files. This would result in a breach
of confidentiality and integrity, respectively.
The second attack vector is to implement a buffer overflow attack.
There is no indication that the value in any of the environment
variables (TMP, TEMP) is truncated to MAX_PATH. Therefore, an attacker
could specify an environment variable whose length is longer than that
of the path buffer if the buffer's length is not set properly. When the
program was run in this environment, the path buffer would be overflowed."
The rule prevents such attacks.
EXAMPLE
#include <afx.h>
const char * virus_temp_sig = "XXX";
char * get_temp_file()
{
char wintemp_path[1024];
REPAIR
Do not use the GetTempPath() functions or at least be careful what you
place
in locations returned by them.
REFERENCES
1. https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/758BSI.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule improve the performance by choosing a small spin count for a critical
section of short duration.
EXAMPLE
#define _WIN32_WINNT 0x0501
#include <afx.h>
class Queue {
public:
Queue(int limit)
{
InitializeCriticalSection(&lock);
}
~Queue()
{
::DeleteCriticalSection(&lock);
}
void AddTail()
{
::EnterCriticalSection(&lock);
::LeaveCriticalSection(&lock);
}
protected:
// Violation
CRITICAL_SECTION lock;
};
REPAIR
#define _WIN32_WINNT 0x0501
#include <afx.h>
class Queue1 {
public:
Queue1(int limit)
{
if (!InitializeCriticalSectionAndSpinCount(&lock, 0x80000400) )
OK
{
exit(0);
}
}
~Queue1()
{
::DeleteCriticalSection(&lock);
}
void AddTail()
{
::EnterCriticalSection(&lock);
::LeaveCriticalSection(&lock);
}
protected:
CRITICAL_SECTION lock;
};
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
//
NOTES
This rule is dedicated to the UNIX-like systems.
BENEFITS
Rule prevents using thread-unsafe functions which may
behave incorrectly when used in multi-threading programs.
EXAMPLE
#include <unistd.h>
void foo()
{
char *name = ttyname(1);
}
// Violation
REPAIR
#include <unistd.h>
void foo1()
{
char name[100];
int status = ttyname_r(1,name,100);
}
// OK
REFERENCES
1. http://docs.sun.com/app/docs/doc/816-5137/6mba5vpk6?a=view
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents using insecure 'setuid' function.
EXAMPLE
#include <sys/types.h>
#include <unistd.h>
int main()
{
setuid(34);
}
// Violation
REPAIR
#include <sys/types.h>
#include <unistd.h>
int main()
{
seteuid(34);
}
// OK
REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoidsetuid.html
BENEFITS
Rule prevents using unsafe chmod(), chown(), chgrp() functions.
EXAMPLE
#include <sys/stat.h>
#include <sys/types.h>
void foo(const char* path)
{
chmod(path, S_IRWXU);
// Violation
}
REPAIR
#include <sys/stat.h>
#include <sys/types.h>
void goo(int fildes)
{
fchmod(fildes, S_IRWXU);
}
// OK
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
Standard random number generators should not be used to generate randomness for security
reasons [SECURITY-28-2]
DESCRIPTION
Standard random number generators should not be used to
generate randomness for security reasons.
For security sensitive randomness a cryptographic randomness generator
that provides sufficient entropy should be used.
Rule detects usage of the following functions:
drand48, erand48, initstate, jrand48, cong48, lrand48, mrand48,
nrand48, seed48, setstate, srand48, strfry, memfrob, crypt, srandom
BENEFITS
Rule prevents using unsecured random number generators.
EXAMPLE
#include <stdlib.h>
void goo()
{
double rnumber = drand48(); // Violation
}
REPAIR
Do not use standard random number generators.
REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-327
http://cwe.mitre.org/top25/#CWE-327
BENEFITS
Rule prevents using unsafe, obsolete C routine.
EXAMPLE
#include <ulimit.h>
void foo(int cmd, long newlimit)
{
ulimit(cmd, newlimit); // Violation
}
REPAIR
#include <sys/types.h>
#include <sys/resource.h>
#include <unistd.h>
void foo(int who, struct rlimit *rlim)
{
getrlimit(who, rlim); // OK
}
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents using insecure function 'getpw'.
EXAMPLE
#include <pwd.h>
#include <sys/types.h>
int main()
{
char* buf;
getpw(0,buf);
return 0;
}
// Violation
REPAIR
#include <pwd.h>
#include <sys/types.h>
int main()
{
char* buf;
struct passwd * ps = getpwuid(0); // OK
return 0;
}
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents using insecure 'cuserid' function.
EXAMPLE
#include <unistd.h>
#include <stdio.h>
void foo( ) {
char * w = cuserid( "userName" );
}
// Violation
REPAIR
#include <sys/types.h>
#include <pwd.h>
void foo( ) {
struct passwd * t =
}
getpwuid( 12 );
// OK
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
2. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-676
http://cwe.mitre.org/top25/#CWE-676
BENEFITS
Rule prevents unspecified behaviour of obsolete 'usleep()' C routine.
EXAMPLE
#include <unistd.h>
int main()
{
usleep(7);
return 0;
}
// Violation
REPAIR
#include <time.h>
void foo(timespec *req, timespec *rem)
{
nanosleep(req, rem);
// OK
}
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
Usage of functions which do not properly handle non-NULL terminated strings is not allowed
[SECURITY-33-2]
DESCRIPTION
"The strlen() function can be associated with problems if a string is not
null
terminated or if it is used in a way that causes a null terminator to be
lost.
The use of strlen() can easily cause off-by-one errors, since copying a
string
of length strlen(buf) actually requires copying strlen(buf)+1 characters
(including the null terminator). The resulting unterminated strings can
cause
subsequent problems when functions such as strlen() are run on them."
The rule reports violations if the following functions are used:
strlen, lstrlen, _tcslen, _mbslen, and wcslen.
BENEFITS
The rule prevents using functions that can cause buffer overflows
and security problems.
EXAMPLE
#include <string.h>
void foo()
{
char buffer[61] = "string example";
unsigned int len;
len = strlen(buffer);
// Violation
}
REPAIR
Do not use strlen, lstrlen, _tcslen, _mbslen, and wcslen functions.
REFERENCES
1. https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/852BSI.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
BENEFITS
Rule prevents using NLSPATH, LC_ALL, LC_MESSAGES,
and IFS environment variables.
EXAMPLE
#include <locale.h>
void foo()
{
setlocale(LC_ALL,""); // Violation
}
REPAIR
Do not use described environment variables.
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
Don't trust any value of command line if attacker can set them [SECURITY-35-2]
DESCRIPTION
Don't trust any value of command line if attacker can set them.
BENEFITS
Rule prevents using command line values which may be set by an attacker.
EXAMPLE
int main(int argc, char **argv)
{
int local = 0;
local += argc;
// Violation
return 1;
}
REPAIR
int main()
{
}
// OK
REFERENCES
1. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/commandline.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
Never use unfiltered data from an untrusted user as the format parameter [SECURITY-36-2]
DESCRIPTION
Never use unfiltered data from an untrusted user as
a format parameter. Failing this guideline usually results
in a format string vulnerability. A particularly nasty case
is printf's %n conversion specification, which writes
the number of characters written so far into the pointer
argument; using this, an attacker can overwrite a value
that was intended for printing.
Rule checks if format parameter is used.
BENEFITS
Rule prevents attempts of overwriting a value that
was intended for printing.
EXAMPLE
#include <stdio.h>
void foo( char* stringFromUntrustedUser ) {
printf( stringFromUntrustedUser );
printf( "stringFromUntrustedUser" );
}
// Violation
// Violation
REPAIR
#include <stdio.h>
void foo( char* stringFromUntrustedUser ) {
const char *format = "%s";
printf( "%s",stringFromUntrustedUser );
printf( format, stringFromUntrustedUser );
// OK
// OK
REFERENCES
1. David A. Wheeler, Programming Secure Applications for Unix-like Systems
(pdf),
http://www.dwheeler.com/secure-programs
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
SINCE
v7.2
BENEFITS
Rule detects weak encryption functions.
EXAMPLE
#include <unistd.h>
void myCrypt(const char* key, const char *salt)
{
char *hash = crypt(key, salt);
// Violation
/* ... */
}
REPAIR
Calls to crypt() and encrypt() should be replaced with a more secure
version.
The following libraries provide good choices:
*
*
*
*
REFERENCES
1. https://buildsecurityin.us-cert.gov/daisy/bsi-rules/home/g1/728.html
2. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
3. CWE/SANS Top 25 Most Dangerous Software Errors: CWE-327
http://cwe.mitre.org/top25/#CWE-327
}
* the user input is passed to function as pointer or reference
or it's value is changed in assignment statement
// user input
// 'name' passed to
// OK
// Violation 'i'
x = 10;
while(name[x]);
value
}
See also: SECURITY-20.
SINCE
v7.2
BENEFITS
Rule prevents potential buffer overflow and SQL injection attacks.
EXAMPLE
#include <stdio.h>
void foo();
void iterateFoo()
{
unsigned num;
int i;
scanf("%u",&num);
for (i = 0; i < num; i++){
foo();
}
}
REPAIR
#include <stdio.h>
void foo();
// Violation
// OK
REFERENCES
1. PCI Data Security Standard (PCI DSS) Version 1.2
Requirement 6: Develop and maintain secure systems and applications
STL
STL Best Practices
RULES
Instead of trying to write the container-independent code use class
encapsulation [STL-01-5]
To make copying efficient, correct, and immune to the slicing problem
create containers of pointers instead of containers of objects [STL-02-3]
Call empty instead of checking size() against zero [STL-03-3]
Avoid using iterative calls to insert in an explicit loop [STL-04-3]
Almost all uses of copy where the destination range is specified using an
insert iterator should be replaced with calls to range member functions
[STL-05-3]
Instead of anonymous istream_iterator objects use istream_iterator names
when used as function parameters [STL-06-3]
When using containers of newed pointers, remember to delete the pointers
before the container is destroyed [STL-07-3]
Never create containers of auto_ptrs [STL-08-3]
Avoid using remove algorithm with list and standard associative containers
[STL-09-3]
Prefer vector and string to dynamically allocated arrays [STL-10-3]
Consider using vector<char> instead of string [STL-11-4]
Use reserve to avoid unnecessary reallocations [STL-12-3]
Each vector and string should be checked if it is not empty before it is
passed to C function [STL-13-3]
Avoid using vector<bool> [STL-14-3]
Specify comparison types for associative containers of pointers [STL-15-3]
For associative containers never use comparison function returning true
for equal values [STL-16-3]
For associative containers never use comparison function returning true
for equal values [STL-17-3]
Prefer iterator to const iterator, reverse_iterator, and
const_reverse_iterator [STL-18-3]
Use distance and advance to convert a container's const_iterators to
iterators [STL-19-3]
It is necessary to be careful when using reverse_iterator's base iterator
for erasure purposes [STL-20-4]
Consider istreambuf_iterators for character-by-character input [STL-21-4]
Make sure destination ranges are big enough [STL-22-3]
Follow remove-like algorithms by erase if you really want to remove
something [STL-23-3]
Avoid using remove and similar algorithms (i.e., remove_if and unique) on
containers of dynamically allocated pointers [STL-24-3]
If you pass a sorted range to an algorithm that also takes a comparison
function, be sure that the comparison function you pass behaves the same
Instead of trying to write the container-independent code use class encapsulation [STL-01-5]
DESCRIPTION
"Given the inevitability of having to change container types from time to
time,
you can facilitate such changes in the usual manner: by encapsulating,
encapsulating, encapsulating. One of the easiest ways to do this is
through the
liberal use of typedefs for container and iterator types.(...) A typedef
is
just a synonym for some other type, so the encapsulation it affords is
purely
lexical. A typedef doesn't prevent a client from doing (or depending on)
anything they couldn't already do (or depend on). You need bigger
ammunition
if you want to limit client exposure to the container choices you've made.
You need classes. To limit the code that may require modification if you
replace one container type with another, hide the container in a class,
and
limit the amount of container-specific information visible through the
class
interface. For example, if you need to create a customer list, don't use a
list directly. Instead, create a CustomerList class, and hide a list in
its
private section"
SINCE
v7.0
BENEFITS
"When you consider this kind of change, you still have to check every
CustomerList member function and every friend to see how they'll be
affected
(in terms of performance and iterator/pointer/reference invalidation,
etc.),
but if you've done a good job of encapsulating CustomerList's
implementation
details, the impact on CustomerList clients should be small. You can't
write
container-independent code, but they might be able to."
EXAMPLE
#include <list>
using namespace std;
class Customer{};
list<Customer> customers1;
typedef list<int> CustomersContainer;
CustomersContainer customers2;
// Violation
// Violation
REPAIR
#include <list>
using namespace std;
class Customer{};
class CustomerList {
private:
typedef list<Customer> CustomerContainer;
typedef CustomerContainer::iterator CCIterator;
CustomerContainer customers;
public:
// limit the amount
// information visible
};
// in this interface
// OK
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 1, item 2
To make copying efficient, correct, and immune to the slicing problem create containers of
pointers instead of containers of objects [STL-02-3]
DESCRIPTION
"Containers hold objects, but not the ones you give them. Furthermore,
when you
get an object from a container, the object you get is not the one that was
in
the container. Instead, when you add an object to a container (via. e.g..
insert or push_back. etc.), what goes into the container is a copy of the
object you specify. When you get an object from a container (via. e.g..
front
or back), what you set is a copy of what was contained. Copy in, copy out.
That's the STL way.
An easy way to make copying efficient, correct, and immune to the slicing
problem is to create containers of pointers or smart pointers instead of
containers of objects."
SINCE
v7.0
BENEFITS
"Copying pointers is fast, it always does exactly what you expect (it
copies
the bits making up the pointer), and nothing gets sliced when a pointer is
copied."
EXAMPLE
#include <list>
#include <map>
using namespace std;
class example {
};
void foo()
{
list<example> cont1;
map<int,example> cont2;
};
// Violation
// Violation
REPAIR
#include <list>
#include <map>
using namespace std;
class example {
};
void foo() {
list<example*> cont1;
map<int,example*> cont2;
};
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule improves efficiency of code.
EXAMPLE
#include <vector>
int foo()
{
std::vector<char> vVector;
if(vVector.size() == 0) // Violation
return 1;
if(vVector.size())
return 1;
return 0;
}
REPAIR
#include <vector>
int foo()
// Violation
{
std::vector<char> vVector;
if(vVector.empty() == 0) // OK
return 1;
if(vVector.empty())
return 1;
// OK
return 0;
}
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 4
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule improves performance and protects from undefined behavior in case of
improper updating of insert location.
EXAMPLE
#include <vector>
#include <iostream>
using namespace std;
void foo()
{
vector<int> v;
const int numValues = 10;
int data[numValues]={0,1,2,3,4,5,6,7,8,9};
vector<int>::iterator insertLoc(v.begin());
for (int i = 0; i < numValues; i++)
{
insertLoc = v.insert(insertLoc, data[i]);
}
}
REPAIR
#include <vector>
#include <iostream>
using namespace std;
void foo()
{
// Violation
vector<int> v;
const int numValues = 10;
int data[numValues]={0,1,2,3,4,5,6,7,8,9};
v.insert(v.begin(),data,data+numValues);
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Almost all uses of copy where the destination range is specified using an insert iterator
should be replaced with calls to range member functions [STL-05-3]
DESCRIPTION
"(...) almost all uses of copy where the destination range is specified
using
an insert iterator (i.e.. via inserter, back_inserter. or front_inserter)
can
be should be replaced with calls to range member functions. Too many
STL
programmers overuse copy, so the advice I just gave bears repeating:
Almost all
uses of copy where the destination range is specified using an insert
iterator
should be replaced with calls to range member functions."
See also: STL-04
SINCE
v7.0
BENEFITS
"In short, range member functions yield code that is easier to write and
easier to understand. (...) It would be helpful to have a more universally
agreed-upon criterion for establishing the superiority of range member
functions to their single-element counterparts. For the standard sequence
containers, we have one: efficiency. When dealing with the standard
sequence
containers, application of single-element member functions makes more
demands
on memory allocators, copies objects more frequently, and/or performs
redundant
operations compared to range member functions that achieve the same end."
EXAMPLE
#include <vector>
#include <algorithm>
using namespace std;
class Widget{};
void myFunction()
{
vector<Widget> v1, v2;
v1.clear();
copy(v2.begin() + v2.size() / 2, v2.end(), back_inserter(v1 )); //
Violation
}
REPAIR
#include <vector>
#include <algorithm>
using namespace std;
class Widget{};
void myFunction()
{
vector<Widget> v1, v2;
v1.clear();
v1 .insert(v1 .end(), v2.begin() + v2.size() / 2, v2.end());
}
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 5
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule improves maintainability and prevents writing ambiguous code.
EXAMPLE
#include <list>
#include <iterator>
#include <fstream>
using namespace std;
void foo()
{
ifstream dataFile("ints.dat");
list<int> data2(istream_iterator<int>(dataFile),
istream_iterator<int>());
}
REPAIR
#include <list>
// Violation
#include <iterator>
#include <fstream>
using namespace std;
void foo()
{
ifstream dataFile(" ints.dat");
istream_iterator<int> dataBegin(dataFile);
istream_iterator<int> dataEnd;
list<int> data(dataBegin,dataEnd);
// OK
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 1, item 6
When using containers of newed pointers, remember to delete the pointers before the
container is destroyed [STL-07-3]
DESCRIPTION
"All you really need to remember is that STL containers are smart, but
they're
not smart enough to know whether to delete the pointers they contain. To
avoid
resource leaks when you have containers of pointers that should be
deleted,
you must either replace the pointers with smart reference-counting pointer
objects (such as Boost's shared_ptr) or you must manually delete each
pointer
in the container before the container is destroyed."
Rule enforces replacing the pointers with smart reference-counting pointer
objects (such as Boost's shared_ptr) as it is exception-safe solution.
SINCE
v7.0
BENEFITS
Rule helps writing exception-safe code and prevents resource leaks.
EXAMPLE
#include <vector>
#include <boost/shared_ptr.hpp>
#define NUMBER 10
using namespace std;
class Widget
{
public:
Widget(){}
~Widget(){}
};
void foo()
{
vector<Widget*> vwp;
for (int i = 0; i < NUMBER; ++i)
vwp.push_back(new Widget);
}
// Violation
REPAIR
#include <vector>
#include <boost/shared_ptr.hpp>
#define NUMBER 10
using namespace std;
class Widget
{
public:
Widget(){}
~Widget(){}
};
void foo()
{
typedef boost::shared_ptr<Widget> WidgetPtr;
vector<WidgetPtr> vwp;
for (int i = 0; i < NUMBER; ++i)
vwp.push_back(WidgetPtr(new Widget));
}
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 7
2. General Principles of Software Validation;
SINCE
v7.0
BENEFITS
Rule improves efficiency, correctness and maintainability of code.
EXAMPLE
#include <vector>
#include <boost/shared_ptr.hpp>
using namespace std;
void foo( ) {
typedef auto_ptr<int> q;
vector<q> v;
}
REPAIR
// Violation
#include <vector>
#include <boost/shared_ptr.hpp>
using namespace std;
void foo( ) {
typedef boost::shared_ptr<int> w;
vector<w> v;
// OK
}
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 8
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Avoid using remove algorithm with list and standard associative containers [STL-09-3]
DESCRIPTION
"Choose carefully among erasing options.
If you have a contiguous-memory container (vector, deque, or string),
the best approach is the erase-remove idiom:
c.erase( remove(c.begin(), c.end(), 1963), c.end());
This approach works for lists, too, but the list member function remove is
more
efficient:
c. remove(1963);
When c is a standard associative container (i.e.. a set. multiset, map.
or multimap), the use of anything named remove is completely wrong.
Such containers have no member function named remove, and using the remove
algorithm might overwrite container values, potentially corrupting the
container." Rule disallows usage of remove algorithm with list and
standard
associative containers.
SINCE
v7.0
BENEFITS
Rule improves efficiency of code amd prevents possibility of data
corruption.
EXAMPLE
#include <algorithm>
#include <list>
using namespace std;
bool goo( int x );
void foo( ) {
list<int> list_int;
list_int.erase( remove( list_int.begin( ),
//
Violation
list_int.end( ), 1963 ), list_int.end( ) );
list_int.erase( remove_if( list_int.begin( ),
//
Violation
list_int.end( ), goo ), list_int.end( ) );
}
REPAIR
#include <algorithm>
#include <list>
using namespace std;
bool goo( int x );
void foo( ) {
list<int> list_int;
list_int.remove( 1963 );
list_int.remove_if( goo );
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 1, item 09
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule helps writing safer and more scalable code.
EXAMPLE
#include <vector>
using namespace std;
class A{};
void foo()
{
A *p;
p = new A[10]; // Violation
}
REPAIR
#include <vector>
using namespace std;
class A{};
void foo()
{
A obj;
vector <A> vectorA; // OK
vectorA.push_back(obj);
}
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 2, item 13
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule helps writing safer and more scalable code.
EXAMPLE
#include <string>
using namespace std;
void foo( ) {
string sName;
}
// Violation
REPAIR
#include <vector>
using namespace std;
void foo( ) {
vector <char> sName; // OK
}
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 2, item 13
SINCE
v7.0
BENEFITS
Rule improves efficiency, correctness and maintainability of code.
EXAMPLE
#include <vector>
using namespace std;
void foo()
{
vector<int> v;
for (int i = 1; i <= 1000; ++i) v.push_back(i); // Violation
}
REPAIR
#include <vector>
using namespace std;
void foo()
{
vector<int> v;
v.reserve(1000);
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 2, item 14
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Each vector and string should be checked if it is not empty before it is passed to C function
[STL-13-3]
DESCRIPTION
"(...) Still, obstacles remain, and one of the most common is the
existence of
legacy C APIs that traffic in arrays and char* pointers instead of vector
and
string objects. Such APIs will exist for a long time, so we must make
peace
with them if we are to use the STL effectively. Fortunately, it's easy. If
you have a vector v and you need to get a pointer to the data in v that
can be
viewed as an array, just use &v[0]. The only sticking point is if v is
empty.
If it is, v.size() is zero, and &v[0] attempts to produce a pointer to
something that does not exist."
Rule enforces checking if vector/string is not empty before it is passed
to C
function.
SINCE
v7.0
BENEFITS
Rule prevents undefined results.
EXAMPLE
// file.c
#include <stddef.h>
void doSomething( const int* pInts, size_t numlnts ) {
/*...*/
}
// file.cpp
#include "file.c"
#include <vector>
REPAIR
// file.c
#include <stddef.h>
void doSomething( const int* pInts, size_t numlnts ) {
/*...*/
}
// file.cpp
#include "file.c"
#include <vector>
using namespace std;
void foo( ) {
vector<int> v;
if (!v.empty( )) {
doSomething( &v[ 0 ], v.size( ) ); // OK
}
}
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 2, item 16
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule helps writing safer and more scalable code.
EXAMPLE
#include <vector>
using namespace std;
void foo(vector<bool> bParam)
// Violation
{
vector<bool> sName;
// Violation
vector<bool> *psName;
// Violation
}
vector<bool> vec_fun();
// Violation
REPAIR
#include <vector>
using namespace std;
void foo(vector<int> bParam)
{
vector<int> sName;
// OK
vector<int> *psName;
// OK
}
// OK
vector<int> vec_fun();
// OK
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 2, item 18
SINCE
v7.0
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
#include <set>
#include <string>
#include <iostream>
using namespace std;
void myFunction()
{
set<string*> ssp;
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));
// Violation
set<string*>::const_iterator i;
for (i = ssp.begin(); i != ssp.end();++i)
cout << *i << endl;
REPAIR
#include <set>
#include <string>
#include <iostream>
using namespace std;
struct StringPtrLess:
public binary_function<const string*, const string*,bool>
{
bool operator()(const string *ps1, const string *ps2) const
{
return *ps1 < *ps2;
}
};
void myFunction2()
{
set<string*, StringPtrLess> ssp;
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));
// OK
set<string*, StringPtrLess>::const_iterator i;
for (i = ssp.begin(); i != ssp.end();++i)
cout << **i << endl;
}
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 3, item 20
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
For associative containers never use comparison function returning true for equal values
[STL-16-3]
DESCRIPTION
"Create a set where less_equal is the comparison type, then insert 10 into
the
set:
set<int, less_equal<int> > s;
s.insert(10);
s.insert(10); // Now try inserting 10 again:
For this call to insert, the set has to figure out whether 10 is already
present. To make it easier to understand what happens when the set does
this,
we'll call the 10 that was initially inserted 10A and the 10 that we're
trying
to insert 10B. The set runs through its internal data structures looking
for
the place to insert 10B. It ultimately has to check 10B to see if it's the
same
as 10A. The definition of "the same" for associative containers is
equivalence,
so the set tests to see whether 10B is equivalent to 10A. When performing
this
test, it naturally uses the set's comparison function. In this example,
that's
operator<=, because we specified less_equal as the set's comparison
function,
and less_equal means operators. The set thus checks to see whether this
expression is true:
!(10A<= 10B)&&!(10B<= 10A) // test 10A and 10B for equivalence
Well, 10A and 10B are both 10, so it's clearly true that 10A <= 10B.
Equally
clearly, 10B <= 10A. The above expression thus simplifies to
!(true)&&!(true)
and that simplifies to false && false which is simply false. That is, the
set
concludes that 10A and 10B are not equivalent, hence not the same, and it
thus
goes about inserting 10B into the container alongside 10A. Technically,
this
action yields undefined behavior, but the nearly universal outcome is that
the
set ends up with two copies of the value 10, and that means it's not a set
any
longer."
See also: STL-17
SINCE
v7.0
BENEFITS
"By using less_equal as our comparison type, we've corrupted the
container!
Furthermore, any comparison function where equal values return true will
do
the same thing. Equal values are, by definition, not equivalent!"
EXAMPLE
#include <set>
#include <functional>
using namespace std;
void myFunction()
{
set< int, less_equal<int> > setInt;
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);
}
REPAIR
#include <set>
#include <functional>
using namespace std;
void myFunction()
// Violation
{
set< int, less<int> > setInt;
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);
// OK
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 3, item 21
For associative containers never use comparison function returning true for equal values
[STL-17-3]
DESCRIPTION
"(...) suppose you're in need of a comparison function for a container of
string* pointers that sorts in descending order. The natural thing to do
is to
grab the existing code and modify it. If you're not careful, you might
come up
with this (...):
struct StringPtrGreater:
// this code is
flawed!
public binary_function<const string*, const string*, bool>
{
bool operator()(const string *ps1, const string *ps2) const
{
return !(*ps1 <*ps2); //just negate the old test;
}
// this is incorrect!
};
The idea here is to reverse the sort order by negating the test inside the
comparison function. Unfortunately, negating "<" doesn't give you ">"
(which
is what you want), it gives you ">=". And you now understand that ">=",
because
it will return true for equal values, is an invalid comparison function
for
associative containers. To avoid falling into this trap, all you need to
remember is that the return value of a comparison function indicates
whether
one value precedes another in the sort order defined by that function.
Equal
values never precede one another, so comparison functions should always
return
false for equal values."
See also: STL-16
SINCE
v7.0
BENEFITS
"Unless your comparison functions always return false for equal values,
you
break all standard associative containers, regardless of whether they are
allowed to store duplicates."
EXAMPLE
#include <set>
using namespace std;
struct IntGreater:
public binary_function<const int,const int, bool> {
bool operator()(const int ps1, const int ps2) const
{
return !(ps1 < ps2);
}
};
void myFunction()
{
set< int, IntGreater> setInt; // Violation
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);
}
REPAIR
#include <set>
using namespace std;
struct IntGreater:
public binary_function<const int,const int, bool> {
bool operator()(const int ps1, const int ps2) const
{
return (ps1 > ps2);
}
};
void myFunction()
{
set< int, IntGreater> setInt; // OK
setInt.insert(1);
setInt.insert(10);
setInt.insert(10);
}
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 3, item 21
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
EXCEPTIONS
Const containers.
BENEFITS
Rule improves efficiency and portability of code.
EXAMPLE
#include <vector>
using namespace std;
void sampleFunction(const std::vector<int> &o)
{
vector<int> v;
typedef vector<int>::const_iterator ConstIter;
typedef vector<int>::iterator Iter;
ConstIter c_it;
c_it= v.begin();
c_it = o.begin();
// Violation
REPAIR
#include <vector>
using namespace std;
void sampleFunction(const std::vector<int> &o)
{
vector<int> v;
typedef vector<int>::const_iterator ConstIter;
typedef vector<int>::iterator Iter;
ConstIter c_it;
Iter it = v.begin();
c_it = o.begin();
}
// OK
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 4, item 26
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule improves portability of code.
EXAMPLE
// Compiles with vc++ 6.0
#include <algorithm>
#include <vector>
using namespace std;
void foo( ) {
typedef vector<int> IntVector;
typedef vector<int>::iterator Iter;
typedef vector<int>::const_iterator ConstIter;
ConstIter citer;
Iter iter = const_cast<Iter>( citer );
}
REPAIR
#include <algorithm>
#include <vector>
// Violation
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 4, item 27
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
It is necessary to be careful when using reverse_iterator's base iterator for erasure purposes
[STL-20-4]
DESCRIPTION
"Understand how to use a reverse_iterator's base iterator.
(...) it's not accurate to say that a reverse_iterator's base member
function returns the "corresponding" iterator. For insertion purposes, it
does, but for erasure purposes, it does not. When converting
reverse_iterators
to iterators, it's important that you know what you plan to do with the
resulting iterator, because only then can you determine whether the
iterator
you have is the one you need.
To emulate erasure at a position specified by a reverse_iterator ri, erase
at
the position preceding ri.base() instead. For purposes of erasure, ri
and ri.base() are nor equivalent, and ri.base() is nor the iterator
corresponding to ri."
Rule reports warning message when the usage of base iterator within
erase call is found and no increment/decrement operators are performed for
base
iterator.
SINCE
v7.0
BENEFITS
Rule prevents undefined results.
EXAMPLE
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
void foo()
{
vector<int> v;
list<int> li;
vector<int>::reverse_iterator ri = find(v.rbegin(), v.rend(), 3);
list<int>::reverse_iterator ri2 = find(li.rbegin(), li.rend(), 3);
v.reserve(5);
for(int i = 1;i <= 5;++i){
v.push_back(i);
li.push_back(i);
}
v.erase(ri.base());
li.erase(ri2.base());
}
// Violation
// Violation
REPAIR
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
void foo()
{
vector<int> v;
list<int> li;
vector<int>::reverse_iterator ri = find(v.rbegin(), v.rend(), 3);
list<int>::reverse_iterator ri2 = find(li.rbegin(), li.rend(), 3);
v.reserve(5);
for(int i = 1;i <= 5;++i){
v.push_back(i);
li.push_back(i);
}
v.erase((--ri).base()); // OK
li.erase(--ri2.base()); // OK
}
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 4, item 28
SINCE
v7.0
BENEFITS
Rule improves performance and efficiency of code.
EXAMPLE
#include <list>
#include <fstream>
#include <iterator>
using namespace std;
void myFunction()
{
ifstream dataFile("some_file.dat");
istream_iterator<char> dataBegin(dataFile); // Violation
istream_iterator<char> dataEnd;
// Violation
list<char> data(dataBegin, dataEnd);
}
REPAIR
#include <list>
#include <fstream>
#include <iterator>
using namespace std;
void myFunction()
{
ifstream dataFile("some_file.dat");
istreambuf_iterator<char> dataBegin(dataFile); // OK
istreambuf_iterator<char> dataEnd;
// OK
list<char> data(dataBegin, dataEnd);
}
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 4, item 29
SINCE
v7.0
BENEFITS
"This can lead only to disaster, because there is no object at
*results.end(),
much less at *(results.end()+1)! The call to transform is wrong, because
it's
asking for assignments to be made to objects that don't exist."
EXAMPLE
#include <vector>
#include <algorithm>
using namespace std;
int transmogrify(int x);
void myFunction()
{
vector<int> values;
vector<int> results;
// put values to vector
transform(values.begin(), values.end(),
results.end(), transmogrify);
}
// Violation
REPAIR
#include <vector>
#include <algorithm>
using namespace std;
int transmogrify(int x);
void myFunction()
{
vector<int> values;
vector<int> results;
// put values to vector
transform(values.begin(), values.end(),
back_inserter(results), transmogrify);
}
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 30
Follow remove-like algorithms by erase if you really want to remove something [STL-23-3]
DESCRIPTION
"Follow remove-like algorithms by erase if you really want to remove
something.
The only way to eliminate an element from a container is to invoke a
member
function on that container, and because remove cannot know the container
holding the elements on which it is operating, it is not possible for
remove to
eliminate elements from a container."
EXCEPTIONS
"In fact, remove and erase are so closely allied, the two are merged in
the
list member function remove. This is the only function in the STL named
remove
that eliminates elements from a container"
BENEFITS
Rule improves efficiency and prevents memory leaks.
EXAMPLE
#include <vector>
#include <algorithm>
using namespace std;
void foo( ) {
vector<int> coll;
for ( int i=0; i < 10; i++ ) {
coll.push_back( i + 65 );
}
vector<int>::iterator pos;
pos = remove( coll.begin( ), coll.end( ), 5 ); // Violation no erase
call
}
REPAIR
#include <vector>
#include <algorithm>
using namespace std;
void foo( ) {
vector<int> coll;
for ( int i=0; i < 10; i++ ) {
coll.push_back( i + 65 );
}
vector<int>::iterator pos;
pos = remove( coll.begin( ), coll.end( ), 5 );
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 32
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Containers", Rule 82
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Avoid using remove and similar algorithms (i.e., remove_if and unique) on containers of
dynamically allocated pointers [STL-24-3]
DESCRIPTION
"Be wary of remove-like algorithms on containers of pointers. This makes
the
resource leak especially obvious, and it should now be clear why you
should
try to avoid using remove and similar algorithms (i.e., remove_if and
unique)
on containers of dynamically allocated pointers. In many cases, you'll
find
that the partition algorithm is a reasonable alternative. If you can't
avoid
using remove on such containers, one way to eliminate this problem
is to delete the pointers and set them to null prior to applying the
eraseremove idiom, then eliminate all the null pointers in the container. If
you're
willing to replace the container of pointers with a container of smart
pointers
that perform reference counting, the remove-related difficulties wash
away, and
you can use the erase-remove idiom directly."
SINCE
v7.0
BENEFITS
"Be wary of remove-like algorithms on containers of pointers. Failure to
heed
this advice is just asking for resource leaks."
EXAMPLE
#include <vector>
#include <algorithm>
#include <functional>
REPAIR
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class Widget{
public:
bool isCertified();
};
void delAndNullifyUncertified(Widget*& pWidget)
{
if (!pWidget->isCertified()) { // delete the pointer
delete pWidget;
// and set it to null pWidget
pWidget = 0;
}
}
void myFunction()
{
vector<Widget*> v;
v.push_back(new Widget);
for_each(v.begin(), v.end(), delAndNullifyUncertified);
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 33
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
If you pass a sorted range to an algorithm that also takes a comparison function, be sure that
the comparison function you pass behaves the same as the one you used to sort the range
[STL-25-4]
DESCRIPTION
"(...) the most common is that some algorithms require ranges of sorted
values.
It's important that you adhere to this requirement whenever it applies,
because violating it leads not to compiler diagnostics, but to undefined
runtime behavior. (...) list of the algorithms that require the data on
which
they operate to be sorted:
binary_search, lower_bound, upper_bound, equal_range, set_union,
set_intersection, set_difference, set_symmetric_difference,
merge inplace_merge, includes
With so many different ways to sort things, it's critical that you give
the STL
consistent sorting related information to work with. If you pass a sorted
range
to an algorithm that also takes a comparison function, be sure that the
comparison function you pass behaves the same as the one you used to sort
the
range."
SINCE
v7.0
BENEFITS
"The eleven algorithms that require sorted ranges do so in order to offer
greater efficiency than would otherwise be possible. As long as you
remember
to pass them only sorted ranges, and as long as you make sure that the
comparison function used by the algorithms is consistent with the one used
to
do the sorting, you'll revel in trouble-free search, set, and merge
operations,
plus you'll find that unique and unique_copy eliminate all duplicate
values,
EXAMPLE
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
void myFunction()
{
vector<int> v;
sort(v.begin(), v.end(), greater<int>());
bool a3exists = binary_search(v.begin(),v.end(),3);
Violation
}
//
REPAIR
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
void myFunction()
{
vector<int> v;
sort(v.begin(), v.end(), greater<int>());
bool a3exists = binary_search(v.begin(),v.end(),3, greater<int>()); //
OK
}
REFERENCES
Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of the
Standard Template Library", Chapter 5, item 34
Proper implementation of copy_if should not be based on returning the remove_copy_if with a
not1 in front of the predicate [STL-26-3]
DESCRIPTION
"One of the more interesting aspects of the STL is that although there are
11
algorithms with "copy" in their names, none of them is copy_if. To
implement
copy_if, then, it seems that all we need to do is throw a not1 in front of
the
predicate we'd like to pass to copy_if, then pass the resulting predicate
to
remove_copy_if. The result is the code below.
// a not-quite-right implementation of copy_if
template< typename Inputlterator, typename Outputlterator, typename
Predicate>
Outputlterator copy_if( InputIterator begin, Inputlterator end,
Outputlterator destBegin, Predicate p)
{
return remove_copy_if(begin, end, destBegin, not1(p));
}
If the above reasoning were valid, we could write out our defective
Widgets
this way:
// well-intentioned code that will not compile
copy_if( widgets.begin(), widgets.end(), ostream_iterator<Widget>(cerr,
"\n"),
isDefective);
Your STL platforms will take a jaundiced view of this code, because it
tries to
apply not1 to isDefective. not1 can't be applied directly to a function
pointer: the function pointer must first be passed through ptr_fun. To
call this
implementation of copy_if, you must pass not just a function object, but
an
adaptable function object. That's easy enough to do, but clients of a
would-be
STL algorithm shouldn't have to. Standard STL algorithms never require
that
SINCE
v7.0
BENEFITS
"Given how useful copy_if is, plus the fact that new STL programmers tend
to
expect it to exist anyway, there's a good case to be made for putting
copy_if
the correct one!"
EXAMPLE
#include
#include
#include
#include
#include
<vector>
<algorithm>
<iostream>
<iterator>
<functional>
v.push_back( 1 );
v.push_back( 2 );
v.push_back( 3 );
copy_if( v.begin( ), v.end( ), ostream_iterator<int>( cout, " " ),
is_not_3<int> );
}
REPAIR
#include
#include
#include
#include
<vector>
<algorithm>
<iostream>
<iterator>
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, Item 36
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
If accumulate() is used on a container of floating point values, use floating point value as
initial one [STL-27-3]
DESCRIPTION
If accumulate is performed for i.e. list of doubles and the initial value
would be the int 0, the accumulate would internally use an int to store
the
value it was computing. "That int would ultimately become accumulate's
return
value, and it would be used to initialize the variable sum. The code would
compile and run, but sum's value would be incorrect. Instead of holding
the
true sum of a list of doubles, it would hold the result of adding all the
doubles together, but converting the result to an int after each
addition."
SINCE
v7.0
BENEFITS
Rule prevents loss of data.
EXAMPLE
#include <list>
#include <numeric>
using namespace std;
void foo()
{
list<double> li;
double sum = accumulate(li.begin(), li.end(), 0);
}
REPAIR
#include <list>
// Violation
#include <numeric>
using namespace std;
void foo()
{
list<double> li;
double sum = accumulate(li.begin(), li.end(), 0.0);
}
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 5, item 37
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
NOTES
By small class functor rule means the one with the number of non-static
members not exceeding 5.
BENEFITS
Rule prevents the slicing problem and expensive copying.
EXAMPLE
// compiles with msvc 6.0, 7.1
#include <functional>
using namespace std;
class Widget;
template<typename T>
class BPFC: public unary_function<T, void>
{
private:
Widget w;
int x;
int y;
void someFunction();
bool checkWidget(Widget &);
// Violation
public:
virtual void operator()(const T& val) const; // Violation
};
REPAIR
#include <functional>
using namespace std;
class Widget;
template <typename T> class BPFC{};
template<typename T>
class BPFCImpl
{
private:
Widget w;
int x;
virtual ~BPFCImpl();
virtual void operator()(const T& val) const;
friend class BPFC<T>;
};
template<typename T>
class BPFC2: public unary_function<T, void>
{
private:
BPFCImpl<T> *pImpl;
public:
void operator()(const T& val) const
{
pImpl->operator() (val );
}
};
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 38
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Rule prevents disabling the compiler from detecting an error if you try to
change any data members that the predicate type may have.
EXAMPLE
#include <functional>
#include <algorithm>
#include <list>
using namespace std;
int global;
class Widget{};
class MeetsThreshold: public std::unary_function<Widget, bool> {
public:
bool operator( ) ( const Widget& ) {
// Violation
return ++global == 0;
}
private:
size_t current, n_;
};
REPAIR
#include <functional>
#include <algorithm>
#include <list>
using namespace std;
class SampleVol: public std::unary_function<int, bool> {
bool operator( ) ( const int& b ) const {
// OK
int a = 0;
return a == b;
}
public:
size_t current, n_;
};
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 39
2. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Algorithms", Rule 87
3. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Each functor class should has only one operator() function, and it's parameter and return
types should be passed to unary_function or binary_function [STL-30-3]
DESCRIPTION
"(...) unary_function and binary_function are templates, so you can't
inherit
from them directly. Instead, you must inherit from structs they generate,
and
that requires that you specify some type arguments. For unary_function,
you
must specify the type of parameter taken by your functor class's
operator(),
as well as its return type. For binary_function, you specify three types:
the
types of your operator's first and second parameters, and your operator's
return type. Let's not forget the fundamental reason for all this
unary_function and binary_function base class gobbledegook. These classes
supply typedefs that are required by function object adapters, so
inheritance
from those classes yields adaptable function objects."
STL function objects are modeled on C++ functions, and a C++ function has
only
one set of parameter types and one return type. As a result, the STL
implicitly assumes that each functor class has only one operator()
function,
and it's the parameter and return types for this function that should be
passed
to unary_function or binary_function. This means that, tempting though it
might
be, you shouldn't try to combine the functionality of WidgetNameCompare
and
PtrWidgetNameCompare by creating a single struct with two operator()
functions.
If you did, the functor would be adaptable with respect to at most one of
its
calling forms, and a functor that's adaptable only half the time might
just as
well not be adaptable at all."
SINCE
v7.0
BENEFITS
"Adaptability is important, and you should strive to facilitate it each
time
you write a functor class."
EXAMPLE
#include <functional>
using namespace std;
class Widget{};
template<typename T>
class MeetsThreshold2: public std::unary_function<Widget, int>
Violation
{
private:
const T threshold;
public:
MeetsThreshold2(const T& threshold);
bool operator()(const Widget&) const;
};
//
REPAIR
#include <functional>
using namespace std;
class Widget{};
//
template<typename T>
class MeetsThreshold: public std::unary_function<Widget, bool>
{
private:
const T threshold;
public:
MeetsThreshold(const T& threshold);
bool operator()(const Widget&) const;
};
struct WidgetNameCompare:
OK
std::binary_function<Widget, Widget, bool>{
bool operator()(const Widget& lhs, const Widget& rhs) const;
};
// OK
//
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 40
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
You must employ ptr_fun, mem_fun, or mem_fun_ref whenever you pass a function to an STL
component [STL-31-3]
DESCRIPTION
"If you get confused about when to use ptr_fun and when not to, consider
using
it every time you pass a function to an STL component. You must employ
them
(mem_fun and mem_fun_ref) whenever you pass a member function to an STL
component, because, in addition to adding typedefs (which may or may not
be
necessary), they adapt the calling syntaxes from the ones normally used
with
member functions to the one used even-where in the STL. If you don't use
them
when passing member function pointers, your code will never compile."
SINCE
v7.0
BENEFITS
"The objects produced by mem_fun and mem_fun_ref do more than allow STL
components to assume that all functions are called using a single syntax.
They
also provide important typedefs, just like the objects produced by
ptr_fun."
EXAMPLE
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
class Widget {
};
int test(Widget& x) { return 0; };
void myFunction()
{
vector<Widget> WidgetVector;
for_each(WidgetVector.begin(),WidgetVector.end(), test);
Violation
};
//
REPAIR
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
class Widget {
};
int test(Widget& x) { return 0; };
void myFunction()
{
vector<Widget> WidgetVector;
for_each(WidgetVector.begin(), WidgetVector.end(), ptr_fun(test));
OK
};
//
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 41
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
"Having less do something other than call operator< is a gratuitous
violation
of programmers' expectations. It runs contrary to what has been called
"the
principle of least astonishment." It's callous. It's mean. It's bad.(...)
Don't mislead all those programmers by playing games with the definition
of
less."
EXAMPLE
#include <functional>
using namespace std;
class Widget {
public:
REPAIR
#include <functional>
using namespace std;
class Widget {
public:
size_t weight() const;
size_t maxSpeed() const;
};
bool operator<(const Widget& lhs, const Widget& rhs)
{
return lhs.weight() < rhs.weight();
}
struct maxSpeedCompare:
// OK
public binary_function<Widget, Widget, bool> {
bool operator()(const Widget& lhs, const Widget& rhs) const
{
return lhs.maxSpeed() < rhs.maxSpeed();
}
};
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 6, item 42
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule improves efficiency, correctness and maintainability of code.
EXAMPLE
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void foo()
{
const int VECTOR_SIZE = 8 ;
vector<int> Numbers(VECTOR_SIZE) ;
vector<int>::iterator start, end, it ;
start = Numbers.begin() ;
end = Numbers.end() ;
for(it = start; it != end; it++)
cout << *it;
// Violation
REPAIR
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(int n)
{
cout << n;
}
void foo()
{
const int VECTOR_SIZE = 8 ;
vector<int> Numbers(VECTOR_SIZE) ;
vector<int>::iterator start, end, it ;
start = Numbers.begin() ;
end = Numbers.end() ;
for_each(start, end, print) ;
// OK
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 7, item 43
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
Rule improves efficiency and stability.
EXAMPLE
#include <list>
#include <set>
#include <algorithm>
using namespace std;
void myFunction( ) {
set<int> s;
list<int> l;
list<int>::iterator begin = l.begin();
list<int>::iterator end = l.end();
set<int>::iterator i = find(s.begin(), s.end(), 727);
// Violation
reverse(begin,end);
reverse(l.begin(),l.end());
// Violation
// Violation
REPAIR
#include <list>
#include <set>
#include <algorithm>
using namespace std;
void myFunction( ) {
set<int> s;
list<int> l;
set<int>::iterator i = s.find(727); // OK
l.reverse();
// OK
}
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 7, item 44
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
Do not rely on the conversion of count()'s nonzero values to true and zero to false [STL-35-3]
DESCRIPTION
"Using count as an existence test, count returns either zero or a positive
number, so we rely on the conversion of nonzero values to true and zero to
false. It would arguably be clearer to be more explicit about what we
are doing."
SINCE
v7.0
BENEFITS
Rule improves readability and maintainability of code.
EXAMPLE
#include <list>
#include <algorithm>
using namespace std;
void foo()
{
list<int> lw;
int w;
if(count(lw.begin(), lw.end(), w))
{
/*...*/
}
}
REPAIR
#include <list>
#include <algorithm>
// Violation
REFERENCES
1. Scott Meyers, "Effective STL: 50 Specific Ways to Improve Your Use of
the
Standard Template Library", Chapter 7, item 45
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Rule improves efficiency and prevents memory leaks.
EXAMPLE
#include <algorithm>
#include <vector>
using namespace std;
void setElem( int elem ) {
elem = 1;
}
void foo( ) {
vector<int> coll;
vector<int> moll;
for_each( coll.begin( ), moll.end( ), setElem );
for_each( moll.begin( ), coll.end( ), setElem );
for_each( coll.end( ), coll.begin( ), setElem );
}
REPAIR
#include <algorithm>
#include <vector>
// Violation
// Violation
// Violation
// OK
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Algorithms", Rule 83
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
Rule helps writing safer and more scalable code.
EXAMPLE
class A{};
void foo( ) {
A arrayA[10]; // Violation
}
REPAIR
#include <vector>
using namespace std;
class A{};
void foo( ) {
A obj;
vector <A> vectorA; // OK
vectorA.push_back(obj);
}
REFERENCES
Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," Addison-Wesley,
(C) 2005 Pearson Education, Inc.
Chapter: "STL: Containers", Rule 77
BENEFITS
Rule improves efficiency and prevents memory leaks.
EXAMPLE
#include <vector>
using namespace std;
void foo( ) {
vector<int> coll;
vector<int> moll;
vector<int>::iterator c_pos = coll.begin( );
vector<int>::iterator m_pos = moll.begin( );
if (c_pos < m_pos) {}
// Violation
}
REPAIR
#include <vector>
using namespace std;
void foo( ) {
vector<int> coll;
vector<int> moll;
vector<int>::iterator c_pos = coll.begin( );
vector<int>::iterator m_pos = moll.begin( );
if (c_pos != m_pos) {}
// OK
}
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Templates and Genericity", Rule 67
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
BENEFITS
"Traits classes make information about types available during compilation.
They're implemented using templates and template specialization.
In conjunction with overloading, traits classes make it possible to
perform
compile-time if...else on types."
EXAMPLE
#if _MSC_VER == 1310
#include <typeinfo>
template <typename IterT, typename DistT>
void advancedd( IterT& iter, DistT d ) {
//**** construction if-else
if (typeid( typename std::iterator_traits<IterT>
Violation
::iterator_category ) ==
typeid( std::random_access_iterator_tag )) {
iter += d;
} else {
if (d >= 0) { while (d--) ++iter; }
else { while (d++) --iter; }
}
}
//
#include <vector>
void example( std::vector<int>::iterator iterator, int distant ){
advancedd<std::vector<int>::iterator, int>( iterator, distant );
}
#endif
REPAIR
#if _MSC_VER == 1310
//**** overloading
template<typename IterT, typename DistT>
// use this impl for
void doAdvance( IterT& iter, DistT d,
// random access
std::random_access_iterator_tag ) { // iterators
iter += d;
}
template<typename IterT, typename DistT>
// use this impl for
void doAdvance( IterT& iter, DistT d,
// bidirectional
std::bidirectional_iterator_tag ) { // iterators
if (d >= 0) { while (d--) ++iter; }
else { while (d++) --iter; }
}
template<typename IterT, typename DistT>
// use this impl for
void doAdvance( IterT& iter, DistT d,
// input iterators
std::input_iterator_tag ) {
if (d < 0 ) {
throw std::out_of_range("Negative distance");
}
while (d--) ++iter;
}
template<typename IterT, typename DistT>
void advancett( IterT& iter, DistT d ) {
doAdvance(
// call the version of doAdvance
that
iter, d,
// is appropriate for iter's
iterator
typename
std::iterator_traits<IterT>::iterator_category( ) // OK
);
}
#include <vector>
void repair( std::vector<int>::iterator iterator, int distant ) {
advancett<std::vector<int>::iterator, int>( iterator, distant );
}
#endif
REFERENCES
Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 47-48
When calling swap, employ a using declaration for std::swap, then call swap without
namespace qualification [STL-40-3]
DESCRIPTION
"When calling swap, employ a using declaration for std::swap,
then call swap without namespace qualification."
See also: STL-41, STL-42
SINCE
v7.0
BENEFITS
"When compilers see the call to swap, they search for the right swap to
invoke. C++'s name lookup rules ensure that this will find any T-specific
swap
at global scope or in the same namespace as the type T. If no T-specific
swap
exists,compilers will use swap in std, thanks to the using declaration
that
makes std::swap visible in this function. Even then, however, compilers
will
prefer a T-specific specialization of std::swap over the general template,
so
if std::swap has been specialized for T, the specialized version will be
used.
The one thing you want to be careful of is to not qualify the call,
because
that will affect how C++ determines the function to invoke. For example,
if
you were to write the call to swap this way,
std::swap(obj1, obj2); // the wrong way to call swap
you'd force compilers to consider only the swap in std, thus eliminating
the possibility of getting a more appropriate T-specific version defined
elsewhere."
EXAMPLE
#include <vector>
using namespace std;
template<typename T>
void doSomething( T& obj1, T& obj2 ) {
std::swap( obj1, obj2 );
}
// Violation
REPAIR
#include <vector>
using namespace std;
template<typename T>
void doSomething( T& obj1, T& obj2 ) {
using std::swap;
swap( obj1, obj2 );
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 25
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.0
NOTES
Rule detects attempt of std::swap overloading.
BENEFITS
"Programs that cross this line will almost certainly compile and run, but
their behavior is undefined. If you want your software to have predictable
behavior, you'll not add new things to std."
EXAMPLE
template<typename T>
class WidgetImpl {};
template<typename T>
class Widget {
public:
void swap( Widget<T>& other ) {
using std::swap;
swap(pImpl, other.pImpl );
}
private:
WidgetImpl<T> *pImpl;
};
namespace std {
template<typename T>
void swap( Widget<T>& a, Widget<T>& b ) {
a.swap( b );
}
}
// Violation
REPAIR
namespace WidgetStuff {
template<typename T>
class WidgetImpl {};
template<typename T>
class Widget {
public:
void swap( Widget<T>& other ) {
using std::swap;
swap( pImpl, other.pImpl );
}
private:
WidgetImpl<T> *pImpl;
};
template<typename T>
void swap( Widget<T>& a, Widget<T>& b ) {
a.swap( b );
}
// OK
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 25
SINCE
v7.0
BENEFITS
"That's because one of the most useful applications of swap is to help
classes
(and class templates) offer the strong exception-safety guarantee."
EXAMPLE
#include <iostream>
class WidgetImpl {};
class Widget {
public:
void swap( Widget& other ) {
try {
using std::swap;
swap( pImpl, other.pImpl );
} catch(...) {
throw;
}
}
private:
WidgetImpl *pImpl;
};
// Violation
REPAIR
#include <iostream>
class WidgetImpl {};
class Widget {
public:
void swap( Widget& other ) {
// OK
try {
using std::swap;
swap( pImpl, other.pImpl );
} catch(...) {
// something else than "throw;"
}
}
private:
WidgetImpl *pImpl;
};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 4, Item 25
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
TEMPL
Template
RULES
Factor parameter-independent code out of templates [TEMPL-01-3]
Define non-member functions inside templates when type conversions are
desired [TEMPL-02-3]
Do not overload functions within a template class [TEMPL-03-3]
In template global functions use 'typename' to identify nested dependent
type names [TEMPL-04-3]
In template classes use 'typename' to identify nested dependent type names
[TEMPL-05-3]
Don't change default arguments of virtual functions in template classes
[TEMPL-06-3]
A copy constructor shall be declared when there is a template constructor
with a single parameter that is a generic parameter [TEMPL-07-3]
The viable function set for a function call should either contain no
function specializations, or only contain function specializations [TEMPL08-3]
Overloaded function templates shall not be explicitly specialized [TEMPL09-3]
All partial and explicit specializations for a template shall be declared
in the same file as the declaration of their primary template [TEMPL-10-3]
A copy assignment operator shall be declared when there is a template
assignment operator with a parameter that is a generic parameter [TEMPL11-3]
In a class template with a dependent base, any name that may be found in
that dependent base shall be referred to using a qualified-id or this->
[TEMPL-12-3]
SINCE
v7.0
BENEFITS
Rule prevents possible implicit replication of code.
EXAMPLE
#include <iostream>
template<typename T>
class SquareMatrixBase {
protected:
REPAIR
#include <iostream>
template<typename T>
class SquareMatrixBase {
protected:
void invert( std::size_t matrixSize );
};
template< typename T, std::size_t n>
class SquareMatrix: private SquareMatrixBase<T> {
private:
using SquareMatrixBase<T>::invert;
public:
void invert( ) { this->invert(n); }
// OK
};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 44
2. General Principles of Software Validation;
Define non-member functions inside templates when type conversions are desired [TEMPL02-3]
DESCRIPTION
"Define non-member functions inside templates when type conversions are
desired. When writing a class template that offers functions related to
the
template that support implicit type conversions on all parameters, define
those
functions as friends inside the class template."
SINCE
v7.0
BENEFITS
"Defining functions related to the template that support implicit type
conversions on all parameters as friend prevent from improper using of
those
functions."
EXAMPLE
template<typename T>
class Rational {
public:
Rational( const T& );
};
template<typename T>
const Rational<T> operator*( // Violation
const Rational<T>& lhs, const Rational<T>& rhs )
{ /* ... */ }
REPAIR
template<typename T>
class Rational {
public:
Rational( const T& );
friend
const Rational<T> operator*( // OK
const Rational<T>& lhs, const Rational<T>& rhs )
{ /* ... */ }
};
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 46
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
This rule detects if you overload functions within a template class.
Overloading functions may indicate a design flaw in the template class.
EXAMPLE
template <class T> class A
{
public:
int foo( T );
int foo( int );
// Violation
};
REPAIR
template <class T> class A
{
public:
int foo( T );
// OK
};
REFERENCES
1. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
In template global functions use 'typename' to identify nested dependent type names [TEMPL04-3]
DESCRIPTION
In template global functions use typename to identify
nested dependent type names.
See also: TEMPL-05
SINCE
v7.0
BENEFITS
"Nested dependent names can lead to parsing difficulties. (...) if the
parser
encounters a nested dependent name in a template, it assumes that the name
is
not a type unless you tell it otherwise. By default, nested dependent
names are
not types. The general rule is simple: anytime you refer to a nested
dependent
type name in a template, you must immediately precede it by the word
typename."
EXAMPLE
#include <vector>
#include <iostream>
using namespace std;
template<typename T>
void print2nd( const T& container ) {
if (container.size( ) >= 2) {
T::const_iterator iter( container.begin( ) );
++iter;
int value = *iter;
cout << value;
}
}
// Violation
void test( ) {
typedef vector<int> int_v;
int_v container( 10 );
print2nd<int_v>( container );
}
REPAIR
#include <vector>
#include <iostream>
using namespace std;
template<typename T>
void print2nd( const T& container ) {
if (container.size( ) >= 2) {
typename T::const_iterator iter( container.begin( ) );
++iter;
int value = *iter;
cout << value;
}
}
void test( ) {
typedef vector<int> int_v;
int_v container( 10 );
print2nd<int_v>( container );
}
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 42
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
// OK
In template classes use 'typename' to identify nested dependent type names [TEMPL-05-3]
DESCRIPTION
"Use typename to identify nested dependent type names, except in base
class
lists or as a base class identifier in a member initialization list."
See also: TEMPL-04
SINCE
v7.0
BENEFITS
"Nested dependent names can lead to parsing difficulties. (...) if the
parser
encounters a nested dependent name in a template, it assumes that the name
is
not a type unless you tell it otherwise. By default, nested dependent
names are
not types. The general rule is simple: anytime you refer to a nested
dependent
type name in a template, you must immediately precede it by the word
typename."
EXAMPLE
#include <vector>
using namespace std;
template<class T>
class Base {
public:
class Nested {
public:
Nested( int a );
Nested( );
void foo( );
};
};
template<typename T>
class Derived2: public Base<T>::Nested {
public:
explicit Derived2( int x ): Base<T>::Nested( x ) {
Base<T>::Nested temp;
// Violation
temp.foo( );
}
void goo(Base<T>::Nested temp){}
// Violation
};
void test( ) {
Derived2<int> obj(1);
}
REPAIR
#include <vector>
using namespace std;
template<class T>
class Base {
public:
class Nested {
public:
Nested( int a );
Nested( );
void foo( );
};
};
template<typename T>
class Derived2: public Base<T>::Nested {
public:
explicit Derived2( int x ): Base<T>::Nested( x ) {
typename Base<T>::Nested temp;
// OK
temp.foo( );
}
void goo( typename Base<T>::Nested temp ){}
// OK
};
void test( ) {
Derived2<int> obj(1);
REFERENCES
1. Scott Meyers, "Effective C++: 55 Specific Ways to Improve
Your Programs and Design", Third Edition, Addison-Wesley,
(C) 2005 Pearson Education, Inc., Chapter 7, Item 42
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
BENEFITS
This rule prevents misinterpretation which value is passed as default.
EXAMPLE
template<class T> class Base {
public:
virtual void foo( T i = 1 ) { }
};
template<class T> class Derived: public Base<T> {
public:
virtual void foo( T i = 0 ) { }
// Violation
};
void foo( ) {
Base<int>
b;
Derived<int> d;
d.foo( );
b.foo( );
}
REPAIR
template<class T> class Base {
public:
virtual void foo( T i = 1 ) { }
};
REFERENCES
1. Herb Sutter, Andrei Alexandrescu, "C++ Coding Standards," AddisonWesley,
(C) 2005 Pearson Education, Inc.
Chapter: "Class Design and Inheritance", Rule 38
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
A copy constructor shall be declared when there is a template constructor with a single
parameter that is a generic parameter [TEMPL-07-3]
DESCRIPTION
"Contrary to possible developer expectations, a template constructor
will not suppress the compiler generated copy constructor."
SINCE
v7.2
NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].
BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.
EXAMPLE
typedef signed int int32_t;
class A
{
public:
A ( );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};
// Violation
REPAIR
typedef signed int int32_t;
class A
{
public:
A ( );
A ( A const & rhs );
template <typename T>
A ( T const & rhs )
: i ( new int32_t )
{
*i = *rhs.i;
}
private:
int32_t * i;
};
// OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-5-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
The viable function set for a function call should either contain no function specializations, or
only contain function specializations [TEMPL-08-3]
DESCRIPTION
"The viable function set for a function call should either contain no
function
specializations, or only contain function specializations. If a function
and a specialization of a function template are deemed equivalent after
overload resolution, the non-specialized function will be chosen over the
function specialization"
SINCE
v7.2
EXCEPTIONS
"Rule does not apply to copy constructors or copy assignment operators."
BENEFITS
Rule prevents writing of code that may be inconsistent
with developer expectations.
EXAMPLE
void f ( short b){}
template <typename T> void f ( T ){}
// Example 1
// Example 2
void b ( short s )
{
f ( s );
// Violation - Calls Example 1
f ( s + 1 ); // Violation - Calls Example 2
}
REPAIR
void f ( short b){}
// Example 1
// Example 2
void b ( short s )
{
f<> ( s );
// OK - Calls Example 2
f<> ( s + 1 ); // OK - Calls Example 2
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-2
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
SINCE
v7.2
BENEFITS
"Where a template is not overloaded with other templates, or is overloaded
with non-template functions then it can be explicitly specialized, as it
is
consistent with developer expectation that the explicit specializations
will only be considered if that primary template is chosen."
EXAMPLE
template <typename T> void f ( T );
template <typename T> void f ( T* );
template <> void f<int*> ( int* ); // Violation
REPAIR
template <typename T> void f ( T );
template <> void f<int*> ( int* ); // OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-8-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
All partial and explicit specializations for a template shall be declared in the same file as the
declaration of their primary template [TEMPL-10-3]
DESCRIPTION
"It is undefined behaviour if, for a set of template-arguments, an
implicit
instantiation is generated by the compiler, and a partial or explicit
specialization is declared or defined elsewhere in the program that would
match the set of template-arguments."
SINCE
v7.2
BENEFITS
Rule prevents undefined behaviour.
EXAMPLE
// file.h
template <typename T> void foo () {}
// file.cpp
#include "file.h"
template <> void foo<int> () {} // Violation
REPAIR
// file.h
template <typename T> void foo () {}
template <> void foo<int> () {} // OK
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-7-3
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff
Document issued on: January 11, 2002
A copy assignment operator shall be declared when there is a template assignment operator
with a parameter that is a generic parameter [TEMPL-11-3]
DESCRIPTION
"Contrary to possible developer expectations, a template assignment
operator will not suppress the compiler generated copy assignment
operator."
SINCE
v7.2
NOTES
A template type parameter T is a generic parameter if, in the function
declaration, it has the (possibly cv-qualified) form T &[opt].
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter
of type X, X&, const X&, volatile X& or const volatile X&.
BENEFITS
Prevents incorrect copy semantics for members requiring deep copies.
EXAMPLE
typedef signed int int32_t;
class A
// Violation
{
public:
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;
}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}
REPAIR
typedef signed int int32_t;
class A
// OK
{
public:
A & operator= ( A const & rhs )
{
i = rhs.i;
return *this;
}
template <typename T>
T & operator= ( T const & rhs )
{
if ( this != &rhs ) {
delete i;
i = new int32_t;
*i = *rhs.i;
}
return *this;
}
private:
int32_t * i;
};
void f ( A const & a1, A & a2 )
{
a2 = a1;
}
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
In a class template with a dependent base, any name that may be found in that dependent
base shall be referred to using a qualified-id or this-> [TEMPL-12-3]
DESCRIPTION
"In a class template with a dependent base, any name that may be found in
that
dependent base shall be referred to using a qualified-id or this->"
SINCE
v7.2
BENEFITS
"Using a qualified-id or prefixing the identifier with this-> ensures that
the entity chosen is consistent with developer expectations."
EXAMPLE
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
TYPE t = 0; // Violation
g ( );
// Violation
i++;
// Violation
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );
int i;
};
template class A<int>;
REPAIR
typedef int TYPE;
void g ( );
int i;
template <typename T>
class B;
template <typename T>
class A : public B<T>
{
void f1 ( )
{
::TYPE t1 = 0; // OK ::g ( );
// OK ::i++;
// OK typename B<T>::TYPE t2
this->g ( );
this->i;
}
};
template <typename T>
class B
{
public:
typedef T TYPE;
void g ( );
int i;
};
template class A<int>;
explicit use
explicit use
explicit use
= 0; // OK // OK // OK -
global TYPE
global func
global var
explicit use base TYPE
explicit use base "g"
explicit use base "i"
REFERENCES
1. MISRA C++:2008 Guidelines for the use of the C++ language in critical
systems
Chapter 6, Section 14, Rule 14-6-1
2. General Principles of Software Validation;
Final Guidance for Industry and FDA Staff