user’s guide - massachusetts institute of technology · pdf fileiii parasoft end user...

459
i User’s Guide Version 4.3 UNIX

Upload: doantuong

Post on 07-Feb-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

User’s GuideVersion 4.3

UNIX

i

Parasoft Corporation101 E. Huntington Drive, 2nd Floor

Monrovia, CA 91016Phone: (888) 305-0041

Fax: (626) 256-6884E-mail: [email protected]

URL: www.parasoft.com

Copyright© 1993-2004

Printed in the U.S.A January 15, 2004

ii

PARASOFT END USER LICENSE AGREEMENTREDISTRIBUTION NOT PERMITTEDThis Agreement has 3 parts. Part I applies if you have not purchased a license to the accompanying software (the "SOFTWARE"). Part II applies if you have purchased a license to the SOFTWARE. Part III applies to all license grants. If you initially acquired a copy of the SOFTWARE without purchasing a license and you wish to purchase a license, contact ParaSoft Corporation ("PARASOFT"):

(626) 305-0041

(888) 305-0041 (USA only)

(626) 305-9048 (Fax)

[email protected]

http://www.parasoft.com

PART I -- TERMS APPLICABLE WHEN LICENSE FEES NOT (YET) PAID GRANT.DISCLAIMER OF WARRANTY. Free of charge SOFTWARE is provided on an "AS IS" basis, without warranty of any kind, including without limita-tion the warranties of merchantability, fitness for a particular purpose and non-infringement. The entire risk as to the quality and performance of the SOFTWARE is borne by you. Should the SOFTWARE prove defective, you and not PARASOFT assume the entire cost of any service and repair. This disclaimer of warranty constitutes an essential part of the agreement. SOME JURISDICTIONS DO NOT ALLOW EXCLUSIONS OF AN IMPLIED WARRANTY, SO THIS DISCLAIMER MAY NOT APPLY TO YOU AND YOU MAY HAVE OTHER LEGAL RIGHTS THAT VARY BY JURISDICTION.

PART II -- TERMS APPLICABLE WHEN LICENSE FEES PAIDGRANT OF LICENSE. PARASOFT hereby grants you, and you accept, a limited license to use the enclosed electronic media, user man-uals, and any related materials (collectively called the SOFTWARE in this AGREEMENT). You may install the SOFTWARE in only one location on a single disk or in one location on the temporary or permanent replacement of this disk. If you wish to install the SOFTWARE in multiple locations, you must either license an additional copy of the SOFTWARE from PARASOFT or request a multi-user license from PARASOFT. You may not transfer or sub-license, either temporarily or permanently, your right to use the SOFTWARE under this AGREEMENT without the prior written consent of PARASOFT.

LIMITED WARRANTY. PARASOFT warrants for a period of thirty (30) days from the date of purchase, that under normal use, the material of the electronic media will not prove defective. If, during the thirty (30) day period, the software media shall prove defective, you may return them to PARASOFT for a replacement without charge.

THIS IS A LIMITED WARRANTY AND IT IS THE ONLY WARRANTYMADE BY PARASOFT. PARASOFT MAKES NO OTHER EXPRESS WARRANTY AND NO WARRANTY OF NONINFRINGEMENT OF THIRD PARTIES' RIGHTS. THE DURATION OF IMPLIED WARRANTIES, INCLUDING WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY AND OF FITNESS FOR A PARTICULAR PURPOSE, IS LIMITED TO THE ABOVE LIMITED WARRANTY PERIOD; SOME JURISDICTIONS DO NOT ALLOW LIMITATIONS ON HOW LONG AN IMPLIED WARRANTY LASTS, SO LIMITATIONS MAY NOT APPLY TO YOU. NO PARASOFT DEALER, AGENT, OR EMPLOYEE IS AUTHORIZED TO MAKE ANY MODIFICATIONS, EXTENSIONS, OR ADDITIONS TO THIS WARRANTY.

iii

If any modifications are made to the SOFTWARE by you during the warranty period; if the media is subjected to accident, abuse, or improper use; or if you violate the terms of this Agreement, then this warranty shall immedi-ately be terminated. This warranty shall not apply if the SOFTWARE is used on or in conjunction with hardware or software other than the unmodified version of hardware and software with which the SOFTWARE was designed to be used as described in the Documentation. THIS WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS, AND YOU MAY HAVE OTHER LEGAL RIGHTS THAT VARY BY JURISDICTION.

YOUR ORIGINAL ELECTRONIC MEDIA/ARCHIVAL COPIES. The electronic media enclosed contain an original PARASOFT label. Use the original electronic media to make "back-up" or "archival" copies for the purpose of running the SOFTWARE program. You should not use the original electronic media in your terminal except to create the archival copy. After recording the archival copies, place the original electronic media in a safe place. Other than these archival copies, you agree that no other copies of the SOFTWARE will be made.

TERM. This AGREEMENT is effective from the day you install the SOFTWARE and continues until you return the original SOFTWARE to PARASOFT, in which case you must also certify in writing that you have destroyed any archival copies you may have recorded on any memory system or magnetic, electronic, or optical media and likewise any copies of the written materials.

CUSTOMER REGISTRATION. PARASOFT may from time to time revise or update the SOFTWARE. These revisions will be made generally avail-able at PARASOFT's discretion. Revisions or notification of revisions can only be provided to you if you have reg-istered with a PARASOFT representative or on the ParaSoft Web site. PARASOFT's customer services are available only to registered users.

PART III -- TERMS APPLICABLE TO ALL LICENSE GRANTSSCOPE OF GRANT.DERIVED PRODUCTS. Products developed from the use of the SOFTWARE remain your property. No royalty fees or runtime licenses are required on said products.

PARASOFT'S RIGHTS. You acknowledge that the SOFTWARE is the sole and exclusive property of PARASOFT. By accepting this agree-ment you do not become the owner of the SOFTWARE, but you do have the right to use the SOFTWARE in accor-dance with this AGREEMENT. You agree to use your best efforts and all reasonable steps to protect the SOFTWARE from use, reproduction, or distribution, except as authorized by this AGREEMENT. You agree not to disassemble, de-compile or otherwise reverse engineer the SOFTWARE.

SUITABILITY. PARASOFT has worked hard to make this a quality product, however PARASOFT makes no warranties as to the suitability, accuracy, or operational characteristics of this SOFTWARE. The SOFTWARE is sold on an "as-is" basis.

EXCLUSIONS. PARASOFT shall have no obligation to support SOFTWARE that is not the then current release.

TERMINATION OF AGREEMENT. If any of the terms and conditions of this AGREEMENT are broken, this AGREEMENT will terminate automatically. Upon termination, you must return the software to PARASOFT or destroy all copies of the SOFTWARE and Docu-mentation. At that time you must also certify, in writing, that you have not retained any copies of the SOFTWARE.

iv

LIMITATION OF LIABILITY. You agree that PARASOFT's liability for any damages to you or to any other party shall not exceed the license fee paid for the SOFTWARE.

PARASOFT WILL NOT BE RESPONSIBLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM THE USE OF THE SOFTWARE ARISING OUT OF ANY BREACH OF THE WARRANTY, EVEN IF PARASOFT HAS BEEN ADVISED OF SUCH DAMAGES. THIS PRODUCT IS SOLD "AS-IS".

SOME STATES DO NOT ALLOW THE LIMITATION OR EXCLUSION OF LIABILITY FOR INCIDENTAL OR CON-SEQUENTIAL DAMAGES, SO THE ABOVE LIMITATION OR EXCLUSION MAY NOT APPLY TO YOU. YOU MAY ALSO HAVE OTHER RIGHTS WHICH VARY FROM STATE TO STATE.

ENTIRE AGREEMENT.This Agreement represents the complete agreement concerning this license and may be amended only by a writ-ing executed by both parties. THE ACCEPTANCE OF ANY PURCHASE ORDER PLACED BY YOU IS EXPRESSLY MADE CONDITIONAL ON YOUR ASSENT TO THE TERMS SET FORTH HEREIN, AND NOT THOSE IN YOUR PURCHASE ORDER. If any provision of this Agreement is held to be unenforceable, such pro-vision shall be reformed only to the extent necessary to make it enforceable. This Agreement shall be governed by California law (except for conflict of law provisions).

All brand and product names are trademarks or registered trademarks of their respective holders.

Copyright 1993-2004

Parasoft Corporation

101 E. Huntington Drive, 2nd Floor

Monrovia, CA 91016Printed in the U.S.A, January 15, 2004

v

CodeWizard User’s Guide

IntroductionIntroduction ..................................................................................................................................................1Installation....................................................................................................................................................3

Using CodeWizardUsing CodeWizard.......................................................................................................................................10Preventing Errors in Embedded Development.............................................................................................13

Customizing CodeWizardCreating Custom Coding Standards ............................................................................................................17Customizing Output With Suppressions ......................................................................................................19

Static Analysis RulesGlobal Reporting System.............................................................................................................................28Oracle Proc Files .........................................................................................................................................29Customizing CodeWizard Options With Configuration Files........................................................................30

Viewing Results in InsraInsra.............................................................................................................................................................42

Static Analysis RulesRules Enforced ............................................................................................................................................48

Effective C++ ItemsEffective C++ Items .....................................................................................................................................49

More Effective C++ ItemsMore Effective C++ Items ............................................................................................................................80

Built-in MISRA ItemsBuilt-in MISRA Guidelines ...........................................................................................................................89

vi

Meyers-Klaus ItemsMeyers-Klaus Items .....................................................................................................................................130

Universal Coding Standard ItemsUniversal Coding Standard Items ................................................................................................................133

User ItemsUser Items ...................................................................................................................................................169

Ellemtel (Telecom Industry) ItemsEllemtel (Telecom Industry) Items ...............................................................................................................269

MISRA GuidelinesUser MISRA Guidelines...............................................................................................................................344

Legal NoticesLegal Notices ...............................................................................................................................................442

IndexIndex ............................................................................................................................................................451

vii

Introduction

IntroductionIntroductionWelcome to CodeWizard, a unique C/C++ tool that prevents errors by automatically enforcing built-inand custom C/C++ coding standards.

Coding standards are language-specific rules that, if followed, will significantly reduce the opportunityfor you to make errors. When you consistently implement and enforce coding standards for everyproject, you can prevent errors from entering code and greatly reduce the amount of debugging thatyou must perform to find and fix errors after they have been introduced.

CodeWizard automatically enforces C and C++ coding standards to help you prevent errors and makeyour code more portable and maintainable. CodeWizard is an automatic source code analysis toolbased on programming ideas from C and C++ experts. CodeWizard enforces over 300 built-in C/C++coding standards, and any number of custom C/C++ coding standards that you create with RuleWiz-ard, a CodeWizard feature which lets you graphically create your own coding standards or customizeexisting CodeWizard coding standards. See “Rules Enforced” on page 48 for more information on thecoding standards enforced by CodeWizard.

If you develop software for embedded systems, CodeWizard can help you prevent errors before yourcode leaves the host system. CodeWizard enforces a set of coding standards designed specifically toprevent errors in embedded software development; it also lets you easily create and enforce your ownembedded development coding standards.

New Features for CodeWizard 4.3CodeWizard 4.3 for UNIX contains significant changes from previous versions that will help youprevent coding errors more efficiently. New features/enhancements include:

• Support for Global Reporting System (GRS). This provides a single place to store reports fromCodeWizard processes running on multiple machines (for example, during nightly builds).

• Support for Python scripting and cross-rules in the enhanced RuleWizard functionality.

• Support for new #pragma codewizard directive for fine-grained suppression control withinsource code.

• Support for two new rulesets based on MISRA and Telecom Industry coding standards.

• Support for "volatile" modifier in C++ dictionary of RuleWizard.

• Support for GCC 3.2.

• Added ability to return non-zero exit code if number of violations exceeds specified thresholds.This feature is particularly useful when using CodeWizard in scripts and nightly builds.

• General user enhancements.

1

Introduction

Supported Platforms and CompilersThe platforms and compilers supported by CodeWizard at the time this manual was printed are sum-marized in the table below:

The OS version listed is the version under which CodeWizard was built. Older OS versions may work, and newer versions will generally work. If you have a different compiler, you may be able to customize CodeWizard for your needs. For more information, contact technical support.

Platform OS VersionC++ Compilers C Compilers

CC cxx g++ xlC aCC gcc cc

AIX4 4.3.3 X X X X

AIX5L 5.1 X X X X

HP-UX 11 (IA-64)

11i v1.5 X X X X

HP-UX 11 (PA-RISC)

11.x, 11i X X X X

IRIX 6.5.x X X X X

Linux RedHat 6.2 - 7.3 (glibc 2.1-2.2) X X

Linux_PPC Yellow Dog 2.0+ (glibc 2.1+) X X

Solaris 7, 8, 9 X X X X

2

Installation

InstallationThe following steps describe the process of installing CodeWizard from either:

• A physical medium such as a CD-ROM.

• An electronic archive obtained via our Web server.

Installing CodeWizard from a Web server requires no particular system privileges other than the abilityto create a directory into which the software will be placed. Installing from a CD-ROM requires rootprivileges.

Installing CodeWizard involves the following steps:

• Step 1. Create a Directory for Extracting the CodeWizard Distribution

• Step 2. Extract the CD-ROM Contents

• Step 3. Extract the Installation Script

• Step 4. Install CodeWizard

• Step 5. Install a License

• Step 6. Set the PARASOFT Environment Variable (Optional)

• Step 7. Modify your PATH Environment Variable

• Step 8: Redefine the LD_LIBRARY_PATH Variable

• Step 9: Set the JAVA_HOME Environment Variable (Optional)

• Step 10. Modify Your Environment

Each of these steps is fully explained in this section.

Step 1. Create a Directory for Extracting the CodeWizard DistributionChoose a location in which to install CodeWizard and make this directory with a command such as:mkdir /usr/local/parasoft

All subsequent steps must be performed in the new directory, so you should cd into that directory now:cd /usr/local/parasoft

Note: From now on we will assume that you have chosen to install software in a directory called/usr/local/parasoft as indicated above. If you actually choose a different directory name, youwill have to modify the following commands appropriately.

If you received CodeWizard on a CD-ROM, proceed to Step 2. Extract the CD-ROM Contents.If youreceived CodeWizard via our Web server, skip Step 2 and proceed directly to Step 3. Extract the Instal-lation Script.

3

Installation

Step 2. Extract the CD-ROM ContentsTo mount the CD-ROM, you must be at the root: su root

Create a /cdrom directory, if necessary: mkdir /cdrom.

The actual mount command is different on each platform we support. Please use the appropriate com-mand for your system. Note that the following commands assume that your CD-ROM drive is SCSI ID6. If your drive is at a different SCSI location, substitute the appropriate device file name for yourCD-ROM drive.

cd into the installation directory you created in Step 1: cd /usr/local/parasoft

Then copy the tar file for your platform to the current directory with the following command: cp /cdrom/wizard/tar/cARCH.tar

Unmount the CD-ROM with the following command: unmount /cdrom

Be sure to eject the CD-ROM from your CD drive before proceeding to Step 3.

Step 3. Extract the Installation ScriptExtract the installation script for a compressed file with the following command:

uncompress -c <name_of_tar_file> | tar xvf - install

or, for a zipped file:

gzip -dc <name_of_tar_file> | tar xvf - install

For the zipped file, the name of the tar file supplied to you should be inserted in place of the text<archive_file>. If you are installing from a CD-ROM and your tar file is not compressed, use the follow-ing command to extract the installation script:

tar xvf <name_of_tar_file> install

You are now ready to install CodeWizard on your system using the provided installation script. Steps 4through 9 will lead you through this procedure.

Platform Mount Command

IBM AIX mount -v cdrfs -r /dev/cd0 /cdrom

HP-UX mount -F cdfs -r /dev/disk/c0t6d0 /cdrom

Linux mount -t iso9660 -o ro /dev/scd0 /cdrom

SGI IRIX mount -t iso 9660 -r /dev/scsi/sc0d610 /cdrom

Solaris mount -F hsfs -r /dev/dsk/c0t6d0s2 /cdrom

4

Installation

Step 4. Install CodeWizardCodeWizard includes an installation script which will help you install CodeWizard on your system.

To run the installation script, execute the command: ./install

The script first prints version and Quality Consulting information:

Extracting installation script...

CodeWizard Installation Script

Copyright (C) 2003 by Parasoft Corporation

Quality Consulting is available at:

E-mail: [email protected]

Web: http://www.parasoft.com

Telephone: (626) 305-0041

Fax: (626) 305-9048

The script then asks you to confirm that you want to install CodeWizard into the current directory.

The CodeWizard distribution consists of the following directories and files.

• bin.$ARCH/: CodeWizard executables

• lib.$ARCH/: CodeWizard configuration files

• rules: CodeWizard built-in rules

• examples: CodeWizard example programs

• insra: Insra help files

• install: CodeWizard installation script

• manuals: CodeWizard User’s Guide files

• README: CodeWizard README

• release_notes.txt: CodeWizard release notes

Once the files have been installed, you will be led through a series of questions as the installation scriptconfigures CodeWizard for your system.

We recommend that you choose “yes” when asked if you want to use the default CodeWizard installa-tion. If you do, CodeWizard will be configured automatically. The script will update CodeWizard’s con-figuration files for use with your compilers.

This step does not tell CodeWizard which compiler to use when checking your source code. You willstill need to add the following option to your $HOME/.psrc file (if it doesn't exist, please create one):

codewizard.compiler CC

Note: CC can also be xlC, g++, cxx, aCC or whatever compiler is available on your system.

Once CodeWizard is installed, your system must be configured and a license installed before use. Youwill need to complete steps 5, 7, 8, and 10 before you can use CodeWizard.

5

Installation

Step 5. Install a LicenseAfter installing the necessary files, the installation script will ask if you would like to install a license touse CodeWizard.

Machine-Locked LicensesIf you need to install a machine-locked license, choose “Yes.” The script will start pslic, the ParasoftLicense Manager.

Note: If you get an error message from pslic saying that it cannot open a .psrc file, you shouldmake sure that you have write permission in the /usr/local/parasoft (installation) directoryand/or run pslic as superuser. pslic will print out your machine and network ID numbers. Youshould then phone, fax, or email this information to Parasoft. You will receive a license which you canenter using pslic.

Once you have the license, run pslic.

Choose the A option to add a license: (A)dd a license. The first item you will need to enter is thenetwork or host ID number, which should be the same number printed by pslic. Next, you will beprompted to enter the expiration date, which you received from Parasoft. Finally, enter the passwordyou were given. To complete the license installation, select E: (E)xit and save changes

Shared Network LicensesIf you are using Parasoft’s LicenseServer to manage a floating license, enter the following parametersin your .psrc file:

• LicenseServer_host ”hostname” (Replace “hostname” with the name of the machinehosting LicenseServer; for example, LicenseServer_host machine1).

• LicenseServer_port “port number” (Replace “port number” with the port that Licens-eServer is using; for example, LicenseServer_port 2002).

Note: You must first enter codewizard.networklicense yes in your .psrc file to activate the net-work license feature. The default setting is no.

Tip! If CodeWizard has problems obtaining a server license due to high network load, use the followingoptional parameter to increase the timeout period:

LicenseServer_timeout "timeout" (Replace "timeout" by license server timeout in seconds.

CodeWizard obtains the network license from the license server; connection data to the license serveris in the .psrc file, along with information concerning the local license. For example, in your .psrc fileyou can specify:

>>>> .psrc >>>># local licenseCodeWizard.Password 4.2 <machine ID> <password>

# network licenseCodeWizard.LicenseServer_host <host name>CodeWizard.LicenseServer_port 2222CodeWizard.networklicense yes<<<< .psrc <<<<

Using these settings, CodeWizard will obtain a local license, a valid CodeWizard.password, and allnecessary Network license server connection parameters, including license server port and host data(these are needed to get a license from the license server). Because the network license option is set

6

Installation

to yes, CodeWizard will use the network license. If this option were set to no, CodeWizard wouldchoose the local license.

Important: If you are using LicenseServer, you do not need to run pslic or enter anything in pslic.For information about the .psrc file, see “Customizing CodeWizard Options With Configuration Files”on page 30.

Step 6. Set the PARASOFT Environment Variable (Optional)This step is optional.

In most cases, you will not need to set this environment variable. However, you may find it useful as ashortcut to the CodeWizard installation. Also, a tool may prompt you to set this environment variable.

To set the PARASOFT environment variable correctly, you will need to know the name of the directoryin which CodeWizard has been installed on your system. Once you know this path you should defineand environment variable called PARASOFT to be this pathname.

Typically, you do this by editing the file .cshrc in your home directory and adding a line like one of thefollowing:

• For csh or tcsh shells: setenv PARASOFT /usr/local/parasoft

• For sh, ksh, or bash shells: PARASOFT=/usr/local/parasoft export PARASOFT

Step 7. Modify your PATH Environment VariableYou must add the directory containing the executables to your execution path. Normally, you do this byadding to the definition of either the path or PATH variables as follows:

• For csh and tcsh shells: set path=($path /usr/local/parasoft/bin.$ARCH)

• For sh, ksh, or bash shells: PATH=$PATH:/usr/local/parasoft/bin.$ARCH exportPATH

Important: Replace ARCH with the name of your architecture (aix4, alpha5, hp11, hp11_ia64, linux2,linux_ppc, sgi6, solaris).

The directory in which the executables are located will have a name which can be derived from thetype of system you are running on, and is given to you by the install script.

Many systems have a built-in command called ARCH which can be used to determine the name of thedirectory to put on your path as follows

• For csh or tcsh shells: set path= $path /usr/local/parasoft/bin.$ARCH)

• For sh, ksh, and bash shells: PATH=$PATH:/usr/local/parasoft/bin.$ARCH exportPATH

If you are not certain which directory to put on your search path, ask your system administrator for help.

7

Installation

Step 8: Redefine the LD_LIBRARY_PATH VariableYou must add the directory containing the CodeWizard libraries to your LD_LIBRARY_PATH environ-ment variable by entering one of the following commands:

• For csh or tcsh shells: setenv LD_LIBRARY_PATH $LD_LIBRARY_PATH:/usr/local/parasoft/lib.$ARCH

• For sh, ksh, or bash shells: LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/parasoft/lib.$ARCH export LD_LIBRARY_PATH

Important: Replace ARCH with the name of your architecture (aix4, alpha5, hp11, hp11_ia64, linux2,linux_ppc, sgi6, solaris).

Step 9: Set the JAVA_HOME Environment Variable (Optional)This step is optional but highly recommended.

To run RuleWizard, you need to perform one of the following tasks:

• Set your PATH to the location of your Java binaries

• Set your JAVA_HOME environment variable to the location of your Java installation directory(recommended option)

Note: RuleWizard requires JAVA 1.4.x (JDK/JRE). You can obtain this for free at http://java.sun.com.

Step 10. Modify Your EnvironmentAfter modifying the appropriate configuration files, you should execute one of the following sets of com-mands to actually modify your working environment:

• For csh or tcsh shells:source ~/.cshrcrehash

• For sh, ksh, or bash shells: . ~/.profile

Note: The '.' before ~/.profile is intentional.

8

Installation

Contacting ParasoftParasoft is committed to providing you with the best possible product support for CodeWizard. If youhave any trouble installing or using CodeWizard, please follow the procedure below in contacting ourQuality Consulting department.

• Check the manual.

• Be prepared to recreate your problem.

• Know your CodeWizard version. The number and date of your version can be seen in the ban-ner printed when running CodeWizard on one of your files.

• If the problem is not urgent, report it by e-mail or by fax.

• If you call, please use a phone near your computer. The Quality Consultant may need you torun the software while you are on the phone.

Contact Information

USA Headquarters Parasoft UK

Phone (888) 305-0041 +44 (020) 8263 2827

FAX (626) 256-6884 +44 (020) 8263 2701

Email Email: [email protected] Email: [email protected]

Parasoft France Parasoft Germany

Phone +(33 1) 64 89 26 00 +49 7805/ 956 960

FAX +(33 1) 64 89 26 10 +49 7805/ 919 714

Email Email: [email protected] Email: [email protected]

9

Using CodeWizard

Using CodeWizardUsing CodeWizardYou use CodeWizard by processing your source code with the special codewizard program in placeof your normal compiler. CodeWizard will then call your compiler and proceed as usual.

While processing your code, CodeWizard will detect and report various violations of good C/C++ pro-gramming practices, such as:

• Using new and delete instead of malloc and free.

• Not calling delete on pointer members in destructors.

• Not making destructors virtual in base classes.

• Avoiding breaks in for loops.

• Not comparing chars to constants out of char range.

• Avoiding assignment in if statement condition.

By default, CodeWizard sends its messages to the Insra GUI. For more information on using this GUI,see “Insra” on page 42. You can also have CodeWizard send its messages to stderr or a report file.

A Getting Started ExampleThe easiest way to learn how to use CodeWizard is to use it on an example program and see what itdoes. This section introduces one of the examples supplied with CodeWizard.

To get started, make a temporary directory and copy the source code for the example to it with com-mands similar to:

mkdir $HOME/codewizard

cd $HOME/codewizard

cp/usr/local/parasoft/codewizard/examples/item11SV.C.

Compiling and Running Without CodeWizardOnce you have copied the example program into your current directory, you can compile it with the command:

CC -g -o item11SV item11SV.C

and then run it from the shell in the normal manner:

item11SV

Notice that the program does not crash and does not print any error messages; however, this programcontains a serious problem within its coding structure.

Running CodeWizard On Item11SV.cppYou can now run CodeWizard on this simple example to see how a violation is reported. To do this, fol-low these steps:

1. Although your default compiler should have been set during installation, set it now in your cur-rent directory by adding the option:

codewizard.compiler CC

to your .psrc configuration file. For more information about .psrc files and options, see “Customizing CodeWizard Options With Configuration Files” on page 30.

10

Using CodeWizard

2. Now replace CC with codewizard on your command line:

codewizard -g -o item11SV item11SV.C

CodeWizard will analyze the code for violations and report the following message in Insra:

3. Click the ‘+” sign next to the message header to reveal the source code where the violationoccurs.

11

Using CodeWizard

4. Double-click the message header to open a message window containing the line of sourcecode where the violation occurred and an explanation of the violation detected. The messagewindow is shown below:

5. To make immediate corrections to the source code, simply double–click the excerpt of codeshown in Insra, or click the arrow in the Message window. This will open the associated file inyour selected editor, and bring you directly to the line containing the violation..

Note: By default, the command line will also be passed to the compiler, which will produce an executable.

If you want to use CodeWizard for checking only, you would type:

codewizard -Zoi "codewizard.analyze_only on" filename

This will analyze the code with CodeWizard, but will not pass it to the compiler. You may also do the same by including in your .psrc file:

codewizard.analyze_only on

For information about the .psrc file, see “Customizing CodeWizard Options With Configura-tion Files” on page 30.

Running CodeWizard From Your MakefileTo run CodeWizard from your makefile, simply replace the name of the compiler in your makefile with codewizard. For example, you could use: make CC=codewizard.

12

Preventing Errors in Embedded Development

Preventing Errors in Embedded DevelopmentCodeWizard now supports embedded development by:

• Enforcing a set of coding standards designed specifically to prevent errors in C/C++ embed-ded software development.

• Allowing you to easily create and enforce your own embedded software development codingstandards.

Enforcing Embedded Development Coding StandardsTo use CodeWizard on your embedded projects, you must compile your code with one of CodeWiz-ard’s supported compilers prior to running it through CodeWizard. You do not need to stop using yourregular compiler; rather, you should use a supported compiler before you check your code withCodeWizard, fix the problems found, then continue to compile your code with your regular compiler.

Supported CompilersSupported compilers for CodeWizard include:

Platform OS VersionC++ Compilers C Compilers

CC cxx g++ xlC aCC gcc cc

AIX4 4.3.3 X X X X

AIX5L 5.1 X X X X

HP-UX 11 (IA-64)

11i v1.5 X X X X

HP-UX 11 (PA-RISC)

11.x, 11i X X X X

IRIX 6.5.x X X X X

Linux RedHat 6.2 - 7.3 (glibc 2.1-2.2) X X

Linux_PPC Yellow Dog 2.0+ (glibc 2.1+) X X

Solaris 7, 8, 9 X X X X

13

Preventing Errors in Embedded Development

Enabling Embedded Coding StandardsThe embedded coding standards are not enabled by default. To configure CodeWizard to enforcethese coding standards:

1. Open the .psrc file (located in your CodeWizard installation directory) in any text editor.

2. Find the line that references:

CodeWizard.rulesdirlist /.../cw_install_dir/rules/cwrules.txt

3. Replace cwrules.txt with embedded.txt.

After you have performed these initial configuration steps, CodeWizard will enforce embedded devel-opment coding standards whenever you run CodeWizard.

Creating Customized Embedded Development Coding StandardsYou can also extend and customize CodeWizard’s set of embedded development coding standardswith the RuleWizard feature that lets you graphically create your own company, personal, or tar-get-specific coding standards, as well as modify existing coding standards. For information onRuleWizard, see “Creating Custom Coding Standards” on page 17.

Embedded Development Coding StandardsThe set of coding standards designed especially for embedded software developers includes:

• ArrayElementAccess.rule

• AssignCharTooHigh.rule

• AssignCharTooLow.rule

• AssignUnCharTooHigh.rule

• AssignUnCharTooLow.rule

• BitwiseInCondition.rule

• BreakInForLoop.rule

• CastFuncPtrToPrimPtr.rule

• CastPointer.rule

• CastUnsigned.rule

• CharacterTest.rule

• CharCompareLeft.rule

• CharCompareRight.rule

• CommaOperator.rule

• ConstParam.rule

• ConstPointerFunctionCall.rule

• DeclareArrayMagnitude.rule

• DeclareBitfield.rule

• DeclareRegister.rule

• DeclareStaticLocal.rule

• DeclDimArray.rule

• DoWhile.rule

14

Preventing Errors in Embedded Development

• EqualityFloatLeft.rule

• EqualityFloatRight.rule

• ExplicitEnumValues.rule

• ExplicitLogicalTest.rule

• ExprInSizeof.rule

• FileNameConvention.rule

• ForLoopVarAssign.rule

• FractionLoss.rule

• FuncModifyGlobalVar.rule

• FunctionSize.rule

• GlobalPrefixExclude.rule

• GlobalVarFound.rule

• HeaderInitialization.rule

• IfAssign.rule

• IfElse.rule

• ImplicitUnsignedInit.rule

• InitCharOutOfRange.rule

• InitPointerVar.rule

• InitUnCharOutOfRange.rule

• LocalVariableNames.rule

• LongConst.rule

• ManyCases.rule

• ModifyInCondition.rule

• NameBool.rule

• NameConflict.rule

• NameConstantVar.rule

• NameDouble.rule

• NameEnumType.rule

• NameFloat.rule

• NameGlobalVar.rule

• NameInt.rule

• NameIsFunction.rule

• NameLongInt.rule

• NamePointerVar.rule

• NameShortInt.rule

• NameSignedChar.rule

• NameString.rule

• NameStructType.rule

15

Preventing Errors in Embedded Development

• NameUnsignedChar.rule

• NameUnsignedInt.rule

• NameVariable.rule

• NamingStructUnionMembers.rule

• NonScalarTypedefs.rule

• NumberFunctionParam.rule

• PassByValue.rule

• PointerParamDereference.rule

• ReferenceInitialization.rule

• SingularSwitchStatement.rule

• SourceFileSize.rule

• SourceNamingConvention.rule

• TooManyFields.rule

• UnionFieldNotDefined.rule

• UnnecessaryEqual.rule

• UnreachableCode.rule

• UnusedLocalVar.rule

• UnusedParameter.rule

• UsePositiveLogic.rule

16

Creating Custom Coding Standards

Customizing CodeWizardCreating Custom Coding StandardsCustom coding standards are rules that are specific to a certain development team, or even a certaindeveloper. There are two types of custom coding standards:

• Company coding standards. Company coding standards are rules that are specific to yourcompany or development team. For example, a rule that enforces a naming convention uniqueto your company would be a company coding standard.

• Personal coding standards. Personal coding standards are rules that help you prevent yourmost common errors. Every time you make an error, you should determine why it occurred,then design a personal coding standard that prevents it from reoccurring. If you do this on aregular basis, you will quickly build a set of coding standards that can prevent your most com-mon errors from entering your code.

CodeWizard’s RuleWizard feature lets you design custom coding standards by graphically expressingthe pattern that you want CodeWizard to look for during automatic coding standard enforcement. Asshown in the following graphic, rules are created by selecting a main "node," then adding additionalelements until the rule expresses the pattern that you want to check for. Rule elements are added bypointing, clicking, and entering values into dialog boxes. You can also use this tool to customize manyof CodeWizard’s built-in coding standards.

To launch RuleWizard, type rulewizard at the prompt. A complete user’s guide is available inRuleWizard; to access this user’s guide, choose Help> View in the RuleWizard GUI. Refer to theRuleWizard User’s Guide for information about creating, enforcing and enabling/disabling rules. TheRuleWizard GUI is shown in the following graphic:

17

Creating Custom Coding Standards

18

Customizing Output With Suppressions

Customizing Output With SuppressionsSuppressions stop CodeWizard from enforcing certain coding standards. You can use suppressions totailor CodeWizard's output to your development team and the current project. By default, CodeWizardis configured to suppress all violations in the Universal Coding Standard category and all violations thathave an Informational severity, and to unsuppress any enabled User items.

Topics discussed in this section include:

• “How Suppression Options Work”

• “Adding a Suppression Option”

• “Deleting a Suppression Option”

• “Moving a Suppression Option”

• “Determining Where Suppression Options Are Saved”

• “Suppressing Errors within the Source File”

• “An Example With Suppressions”

How Suppression Options WorkSuppression options are read from top to bottom when CodeWizard determines which item violationswill be reported and which will be suppressed. Because of this, you can think of a series of suppressionoptions as a series of sieves that remove options as they pass through from top to bottom of the sup-pressions page. Conversely, unsuppress options can restore violations that were screened out by ear-lier suppress options. This can get complicated when many suppress and unsuppress options arebeing used concurrently, but offers a very powerful method of controlling the messages that will be dis-played.

19

Customizing Output With Suppressions

The following flow chart illustrates one simple example.

item 2, item 3,... item 39, item ....

Unsuppressitem 3

SuppressAll

item 3

Suppressitem3

Unsuppressitem 2

item 2, 3

item 2

Violations Reported

Suppression Option

Violations Reported

Violations Reported

Suppression Option

Suppression Option

Suppression Option

Violations Reported

Violations Reported

20

Customizing Output With Suppressions

Adding a Suppression OptionYou can enter suppressions in the Suppressions Control Panel, which is accessible by clicking theSuppress button in Insra when Insra is running and contains violations.

To add a new suppression option, place your cursor in the table row where you want the suppressionoption inserted, then click the Insert button. As is, this new option will suppress all violations reportedby CodeWizard.

To determine exactly what violations this option suppresses (or unsuppresses), edit its various fields.Each field can be modified to restrict the messages that will be suppressed or unsuppressed. Theavailable fields are:

• “The Action Field”

• “The Persistence Field”

• “The Item Field”

• “The Type Field”

• “The Class Field”

• “The File Field”

• “Add Lines Field”

• “The Notes Field”

The Action FieldThis field specifies whether the violation message listed is to be suppressed (as indicated by a speakerwith an X through it) or unsuppressed (indicated by a speaker with no X through it). Double clicking onthe field toggles between suppressing and unsuppressing the violation message.

The Persistence FieldThis field specifies whether the suppression option will be saved to the .psrc file under which it islisted. Double-clicking this field toggles it from persistent (the field is checked) to temporary (the field isunchecked). Options marked as persistent will be added to the appropriate .psrc files when the Savebutton is clicked on. Options marked as temporary will be discarded.

Options with an X in this field cannot be made persistent, either because they are hardwired orbecause the file in which it is placed is not writable. New suppression options are marked as persistentby default.

21

Customizing Output With Suppressions

The Item FieldThe Item field lets you determine the item violation that you would like to suppress or unsuppress. Bydefault, there is an asterisk present, which signifies that all items are suppressed or unsuppressed(depending on which option you selected in the Action field).

To enter the item number, double-click in the Item field. A text field will open. Enter the item that you want to suppress or unsuppress in the text field, then press Enter.

Choose the item that you would like to suppress or unsuppress. * matches all item numbers. The prefix"ecpp" stands for Effective C++, "mecpp" for More Effective C++, "mk" for Meyers-Klaus, and "ucs" forUniversal Coding Standards; "user" is used to indicate rules created in RuleWizard or built-in rules thatcan be modified in RuleWizard.

The Type FieldThe Type field allows you to select the type of violation for which messages will be suppressed orunsuppressed. To select the type, double-click the Type field. A pull-down menu button will appear.

This menu contains the following options (in increasing order of seriousness):

• I Informational (suppressed by default)

• PV Possible Violation

• V Violation

• PSV Possible Severe Violation

• SV Severe Violation

* Matches all types

22

Customizing Output With Suppressions

The Class FieldThe Class field allows you to enter a class for which messages will be suppressed or unsuppressed. Afield containing only "*" will match all classes To enter the class, double-click the Class field. A text fieldwill open. Enter the desired class name in the text field, then press Enter.

The File FieldThis field allows you to enter a file for which messages will be suppressed or unsuppressed. A fieldcontaining only "*" will match all files. To enter a file name, type it in the File field, or double-click theFile field and select a file using the file chooser that opens.

23

Customizing Output With Suppressions

Add Lines FieldThis field allows you to enter line numbers for which messages will be suppressed or unsuppressed. Afield containing only "*" will match all lines. To enter a line statement, type it in the Line field. Availablestatements include:

• 2 - line 2

• 2-10 - lines from 2 to 10

• *-10 - lines less and equal 10

• 2-* - lines equal and greater than 2

• * or *-* - all lines

You can type more than one line statement per line by using a comma as a separator (don't use whitespaces between line numbers and the commas). For example: *-4,7,9-12,15-* - indicates thatyou want to look at lines 1 to 4, then line 7, then from lines 9 to 12, and then from line 15 to the end.

The Notes FieldThis field allows you to create notes to explain the purpose of the current suppression item. To enter anote, double-click the Note field. A text field will open. Enter the desired note in the text field, thenpress Enter.

24

Customizing Output With Suppressions

Deleting a Suppression OptionTo delete a suppression option, click it to select it, then click the Delete button.

Once this deletion has been applied, the effects of this option will be gone. This change will appear inInsra immediately.

Moving a Suppression OptionYou may move individual suppression options into new locations on the suppressions page by clickingthe Up and Down buttons. This will affect how CodeWizard reports item violations. For more informa-tion on this topic see “How Suppression Options Work” above.

Determining Where Suppression Options Are SavedThe headers in Insra show the various locations in which .psrc files reside. Insra will display the sup-pression options as read from each file under the appropriate header. When you add a new option using the Insert button, it will be inserted below the currently selected option. You can then move it into the file in which you would like it saved, or mark it as temporary by double-clicking the persistence field (see above). There are two special locations where suppression options may reside other than actual .psrc files: hardwired options and command line options. The former are set internally by CodeWizard, and therefore cannot be permanently changed. They can be edited and/or removed in the window tem-porarily, however. The latter are options passed using the -Zop and -Zoi options on the command line. These options, like hardwired options, cannot be made persistent, but can be moved into a .psrc file if you decide that you want to make them permanent.

Suppressing Errors within the Source FileYou can use #pragma to suppress CodeWizard errors within the source file. In the following example,CodeWizard will suppress the first MECPP item 2 violation while allowing the second:

source file:int main() { char *pc1 = 0; char *pc2 = 0; #pragma CodeWizard OFF pc1 = (char *)pc2; // suppressed #pragma CodeWizard ON pc1 = (char *)pc2; // MECPP item 2 Violation return 0; }

This option is useful if you are debugging code and want to skip a line, a set of lines, or a small block ofcode that you know contains errors but that you do not want to appear as part of your CodeWizard vio-lations report.

25

Customizing Output With Suppressions

Using #pragma suppress/unsuppress DirectivesCodeWizard Version 4.3 allows users to define suppressions directly in their source code, using#pragma codewizard suppress and #pragma codewizard unsuppress directives.

This feature allows for fine-grained control over which rules are enforced on files, classes, or even atthe line level. Another advantage is that since these directives are placed in the sources being ana-lyzed, the suppressions are kept together with the code they apply to. Therefore, it is very easy to havea given set of suppressions visible among all developers working on source files containing such direc-tives.

When running static analysis, all such directives are collected and applied to filter out unwanted viola-tion reports. To specify suppression information the following directive should be used in the sourcecode:

#pragma codewizard suppress <pattern>

To specify unsuppression information the following directive should be used in the source code:

#pragma codewizard unsuppress <pattern>

<pattern> may be any of the following:

1. item RULE_IDENTIFIER (e.g.: item user-200, item ecpp-*)

2. class CLASS_NAME (e.g.: class MyClass, class *)

3. file FILE_NAME (e.g.: file example.cpp, file ex*.cpp)

4. line LINE_NUMBER (e.g.: line *, line 10, line 50-*)

5. all

Elements 1 through 4 can be combined together by separating each entry with a space, as shown inexamples below.

Example A:#pragma codewizard suppress item mecpp-02

This suppresses reports of violation mecpp-02 for the current file, starting from the line where the sup-pression is located.

Example B:#pragma codewizard unsuppress item * class MyClass line 10-*

This unsuppresses all items for class MyClass in the current file starting from line 10.

Example C:#pragma codewizard unsuppress item user-250 file example.cpp

This unsuppresses the item user-250 in the file example.cpp for the current compilation unit.

Example D:#pragma codewizard suppress all

This suppresses all messages in the current file starting from the line where this directive was entered.

26

Customizing Output With Suppressions

Additional Notes• When no item is specified, (un)suppression will be applied to all rules. This is equivalent to

specifying item *.

• When no file is specified, (un)suppression will be applied only to the current file.

• When no line is being specified, (un)suppression will be applied starting from the line thatcontains the directive.

• To suppress files with whitespaces in their names, quotes should be used. For example:

#pragma suppress file "file with whitespace.cpp"

• Putting suppression with file * pattern in a header file makes it valid for all the files thatinclude that header file. When no file is specified, suppression will be applied only to thatheader.

An Example With SuppressionsThis section shows how to use suppressions by building upon the examples given in the UsingCodeWizard section.

For example, let’s assume that you have just run the simple example, then have decided that you wantto unsuppress all violations of rule ucs-19. This rule states that a class that has pointer members shallhave an operator= and a copy constructor. Adhering to this rule prevents memory leaks and datacorruption. If you do not define a copy constructor, the default constructor will be used, which is usuallynot the desired behavior when a class has pointer members.

To have CodeWizard report all violations of ucs-19 that it finds in all files that it analyzes, perform thefollowing steps:

1. To open the Suppressions Control Panel, click the Suppress button in Insra when Insra con-tains one or more violations.

2. In the Suppressions Control Panel, place your cursor in the last row of suppressions, then clickthe Insert button. An additional row of asterisks will appear.

3. In the new suppression option’s Action field, choose Unsuppress by clicking the speaker iconuntil the speaker does not have an X over it.

4. In the new suppression’s Item field, enter ucs-19.Save your new suppression by clicking Save.The Insra GUI will then report that a violation of the ucs-19 rule occurred in item11SV.C.

27

Global Reporting System

28

Static Analysis RulesGlobal Reporting SystemCodeWizard 4.3 allows you to report coding violations detected during source code analysis to the Glo-bal Reporting System (GRS) server. This provides a single place to store reports from CodeWizardprocesses running on multiple machines (for example, during nightly builds).

Before enabling the GRS support, make sure you have the following information from your systemadministrator:

• The GRS server's host name or the IP address.

• The port on which the GRS server is waiting for connections from the clients (that is, fromCodeWizard processes).

Using the GRS ServerFollow the directions given below to configure CodeWizard to send reports to the GRS server.

Enabling the GRS Server for UNIX SystemsTo enable GRS server support for UNIX systems you must add appropriate GRS options to your.psrc file, as described below:

1. The CodeWizard.report_file option must include the grs pseudo-file. This will tellCodeWizard that it should send results to the GRS server.

For example:

• To enable sending results to the GRS server only:

CodeWizard.report_file grs

• To enable sending results to both Insra viewer and the GRS server:

CodeWizard.report_file insra; grs

• To enable sending results to the Insra viewer, the GRS server, and the standard out-put:

CodeWizard.report_file insra; grs; stdout

• To enable sending results to the GRS server and a file called "report.txt":

CodeWizard.report_file grs; report.txt

2. Specify the GRS server hostname and port number by adding the following entries in your.psrc file:

• CodeWizard.GRS_server_host <GRS-server-hostname -or-IP-address>

• CodeWizard.GRS_server_port <GRS-server-port-number>

For example:

• CodeWizard.GRS_server_host grs.server.machine

• CodeWizard.GRS_server_port 32323

Disabling the GRS Server for UNIX SystemsTo disable the GRS server support for UNIX systems, simply remove the grs pseudo-file from theCodeWizard.report_file setting in your .psrc file.

Oracle Proc Files

29

Oracle Proc FilesCodeWizard supports processing of Oracle Proc (*.pc) files for use in embedded SQL programs.CodeWizard dynamically suppresses errors inherited from Proc generated code, allowing you to focuson errors that CodeWizard finds within your own source code.

Note: All Oracle Proc support is for command line usage only. The following instructions provide onlypartial support from the command line.

To run CodeWizard on Proc files in the UNIX space, the environment must first be configured:

1. Install Oracle Proc.

2. Ensure that the binary file *proc is accessible from the command line.

3. Do not mix the different versions of Oracle Proc.

4. Pass all necessary include directories to CodeWizard.

Now it is possible call CodeWizard.

• Using Proc to generate 'c' file call:

codewizard $(ALL_INCLUDES) proc_file.pc

• Using Proc to generate 'c++' file call:

• codewizard $(ALL_INCLUDES) proc_file.pc -Zoi "procflags CODE=CPP". In .psrc files, use codewizard.procflags CODE=CPP.

If your proc_file does not have a standard *.pc extension, use the ‘-Zproc’ option to force Proc mode:

codewizard $(ALL_INCLUDES) -Zproc proc_file.PROC -Zoi "procflags CODE=CPP"

Makefile ExampleThe following is an example of an Oracle Proc makefile:

ORACLE_HOME=$(HOME)/oracleORACLE_INCLUDES = -I$(ORACLE_HOME)/precomp/public \ -I$(ORACLE_HOME)/rdbms/demo \ -I$(ORACLE_HOME)/rdbms/public \ -I$(ORACLE_HOME)/plsql/public \ -I$(ORACLE_HOME)/network/publicPROCOPTIONS= CODE=CPP PARSE=NONE NLS_LOCAL=YES

Within CodeWizard, to use this makefile call:

codewizard -Zoi "procflags $(PROCOPTIONS)" $(ORACLE_INCLUDES) proc_file.pc

Customizing CodeWizard Options With Configuration Files

Customizing CodeWizard Options With Configuration FilesCodeWizard reads options from files called .psrc, which may exist at various locations in the file sys-tem. These options control the behavior of CodeWizard and other Parasoft tools. The files are pro-cessed in the order specified below:

• The file .psrc in the appropriate lib and compiler subdirectories of the main Parasoft installa-tion directory. For example:/usr/local/parasoft/lib.linux/CC/.psrc

• The file .psrc in the main installation ($PARASOFT) directory. For example: /usr/local/parasoft/.psrc

• A file .psrc in your $HOME directory, if it exists.

• A file .psrc in the current working directory, if it exists.

• Files specified on the command line with -Zop and/or -Zoi to the codewizard command in theorder present on the command line.

In each case, options found in later files override those seen earlier. All files mentioned above will beprocessed and the options set before any source files are processed.

Typically, compiler-dependent options are stored in the first location, site-dependent options are storedin the second location, user-dependent options are stored in the third location, and project-dependentoptions are stored in the fourth location. -Zop is commonly used for file-dependent options, and -Zoi iscommonly used for temporary options.

FormatCodeWizard configuration files are simple ASCII files created and modified with a normal text editor.

Entries which begin with the character `#' are treated as comments and ignored, as are blank lines.

All keywords can be specified in either upper or lower case, and embedded underbar characters (`_')are ignored. Arguments can normally be entered in either case, except where case has specific mean-ing, such as in directory or file names. If a line is too long, or would look better on multiple lines, youcan use the ‘\’ character as a continuation line.

Option ValuesThe following sections describe the interpretation of the various parameters. Some options havedefault values, which are printed in the following section in boldface.

30

Customizing CodeWizard Options With Configuration Files

FilenamesSeveral CodeWizard options can specify filenames for various configuration and/or output files. Youmay either enter a simple filename or give a template which takes the form of a string of charactersincluding tokens such as those in the following table, environment variables, and the `~' character.Each of these is expanded to indicate a certain property of your program as indicated in the followingtable.

Thus, the template:

report_file $HOME/codewizard/%a/%c/foo.C.out

will cause CodeWizard to write its output to a file with a name such as:

/usr/me/codewizard/linux/CC/foo.C.out

in which the environment variable HOME has been replaced by its value and the `%a' and `%c'tokens have been expanded to indicate the architecture and compiler name in use.

Using -Zop and -ZoiOn the command line, the -Zop and -Zoi options are processed from left to right, after all other .psrcfiles, and before processing any source code. Therefore, the following command line would tellCodeWizard to analyze all the files using the CC compiler.

codewizard -Zoi "compiler g++" foo.C -Zop foo.def foo2.C -Zoi "compiler g++" foo3.C -Zoi "compiler CC"

foo.def:compiler CC

Options passed using -Zoi do not require the codewizard prefix as options passed in .psrc or -Zopfiles do. With -Zoi, the appropriate prefix is implicitly added using the name of the command to whichthe -Zoi is being passed.

Key Meaning

%a Machine architecture on which you are running, for example, linux, rs6000, hp, and so on.

%c Abbreviated name of the compiler you are using, for example, CC, gcc, xlC, and so on.

%d Time of program compilation in format: YYYYMMDDHHMMSS

%p Process I.D.

%r CodeWizard version number, for example, 4.1

%R CodeWizard version number without ‘.' character. For example, version 4.1 becomes 41.

31

Customizing CodeWizard Options With Configuration Files

Options Used by CodeWizard1. codewizard.analyze_only [on|off]

Specifies whether CodeWizard should pass the file to the compiler or just check for item viola-tions (the default). Turning this option to off tells CodeWizard to pass the file on to the compilerafter checking for item violations.

2. codewizard.buildinruleload

Using this option, CodeWizard loads particular built-in rules. For example, use the name of abuilt-in rule you wish to load, such as ucs-24. You can choose to load all rules by enteringcodewizard.buildinruleload all.

3. codewizard.buildinruleremove

Using this option, CodeWizard removes particular built-in rules. For example, use the name ofa built-in rule you wish to remove, such as ucs-24. You can choose to remove all rules byentering codewizard.buildinruleremove all.

4. codewizard.c_as_cpp [on|off]Specifies whether files with the .c extension should be treated as C++ source code. With thisoption off, CodeWizard will treat files with the .c extension as C code only. If you use C++code in .c files, you should turn this option on.

5. codewizard.compiler compiler_name

Specifies the name of an alternative compiler, such as gcc. If your new compiler is not recog-nized by CodeWizard, you may have to set the compiler_acronym option. This option over-rides the compiler_* options: compiler_acronym, compiler_c, compiler_cpp, andcompiler_default. The indicated compiler will be called every time codewizard is called.

6. codewizard.compiler_acronym abbreviation

Specifies the colloquial name of an alternative compiler, such as gcc. This name is used tolocate the appropriate .psrc files. It does not indicate which compiler will actually be called tocompile source files (see the other compiler_* options). This option overrides thecompiler_c, compiler_cpp, and compiler_default options. In addition, this optionmust be placed after the active compiler option. The order must be:

compiler c89

compiler_acronym cc

and not vice-versa. This option defaults to the last path component of your compiler's name,with the exception of the System V compatibility compiler on Sun workstations(/usr/5bin/cc), which has the acronym 5cc.

7. codewizard.compiler_c C_compiler_name

Specifies the name of the default C compiler, such as gcc. This compiler will be called for any.c files. The default is cc. This option is overridden by the compiler andcompiler_acronym options.

32

Customizing CodeWizard Options With Configuration Files

8. codewizard.compiler_cpp C++_compiler_name

Specifies the name of the default C++ compiler, such as g++. This compiler will be called forany .cc, .cpp, .cxx, and .C files. The default is platform dependent: cxx for Alpha, g++ forLinux, xlC for RS/6000, and CC for other platforms. This option is overridden by the compilerand compiler_acronym options.

9. codewizard.compiler_default [c|cpp]

Specifies whether the default C or C++ compiler should be called to link when there are nosource files on the link line. This option is overridden by the compiler andcompiler_acronym options.

10. codewizard.compiler_flags flags

CodeWizard will add the flags whenever you compile your program (but they will not bepassed to the preprocessor).

11. codewizard.compiler_keyword [*|const|inline|signed|volatile] keyword

Specifies a new compiler keyword (by using the *) or a different name for a standard keyword.For example, if your compiler uses __const as a keyword, use the option:

compiler_keyword const __const

12. codewizard.compiler_options keyword value

Specifies various capabilities of the compiler in use, as described in the following table:

Keyword Value Meaning

ansi None Assumes compiler supports ANSI C (default).

<type> bfunc Function name

Specifies that the indicated function is a compiler "built-in" that is dealt with specially. The optional type keyword specifies that the built-in has a return type other than int. Currently, only long, double, char *, and void * types are supported.

btype Type name

Specifies that the named type is a "built-in" that is treated specially by the compiler.

bvar Variable name

Specifies that the named variable is a "built-in" that is treated specially by the compiler.

esc_x Integer Specifies how the compiler treats the ‘\x’ escape sequence. Possible values are: 0: treat ‘\x' as the single character ‘x' (Kernighan & Ritchie style). -1: treat as a hex constant. Consume as many hex digits as possible. >0: treat as a hex constant. Consume at most the given number of hex digits.

33

Customizing CodeWizard Options With Configuration Files

13. codewizard.error_format string

Specifies the format for error message banners generated by CodeWizard. The string argu-ment will be displayed as entered with the macro substitutions taking place as shown in the fol-lowing table. The string may also contain standard C formatting characters, such as ‘\n’.

for_scope nestednot-nestedoptional

Specifies how for(int i; ...; ...) is scoped. Possible values are: nested: New ANSI standard, always treat as nested. notnested: Old standard, never treat as nested. optional: New standard by default, but old-style code is detected and treated properly (and silently).

knr None Assumes compiler uses Kernighan and Ritchie (old-style) C.

loose None Enables non-ANSI extensions (default).

namespaces None Specifies that namespace is a keyword (default).

no- namespaces

None Specifies that namespace is not a keyword.

promote_long

None If this option is found, integral data types are promoted to long in expressions, rather than int.

sizet d,ld,u, lu Specifies the data type returned by the sizeof operator, as follows: d = int, ld = long, u = unsigned int, lu = unsigned long.

strict None Disables non-ANSI extensions (compiler dependent).

xfunctype Function name

Indicates that the named function takes an argument which is a data type rather than a variable (for example, alignof).

Key Expands to

%b Error message included in output component.

%c Error category (and sub-category if required).

%C Name of the class in which the error occurred.

%d Date on which the error occurs. (DD-MON-YYYY).

%f Filename containing the error.

%F Full pathname, including directories, or the file containing the error.

%h Name of the host on which the application is running.

%l Line number containing the error.

34

Customizing CodeWizard Options With Configuration Files

14. codeWizard.exit_code_threshold [0|1|2|...]

This option tells CodeWizard to return non-zero exit code if the number of reported violations isgreater or equal to this option's value. The default value is 0 (zero).

For example, if the parameter is set to 5, and 5 or more violations are found in the analyzedcode, then CodeWizard will exit with non-zero exit code to indicate this situation.

Set this value to 1 if CodeWizard should exit only if there are no violations in the code. Settingthis option to 0 (zero) disables this mechanism, thus telling CodeWizard to always exit withzero no matter how many violations are found.

15. codewizard.file_ignore <full_path_to_any_directory>/*

Specifies which files you do not want CodeWizard to analyze. No item violations from thesefiles will be displayed by CodeWizard.

16. codeWizard.grs_server_host GRS_server_host

Specify here the name of IP address of GRS server, which will receive CodeWizard messages.

17. codeWizard.grs_server_port GRS_server_port

Specify here the port number of GRS server, which will receive CodeWizard messages. Thedefault is 32323, but it may have to be set to a different value depending on configuration ofthe GRS server in the local network.

18. codewizard.max_call_stack_depth [1|2|3|...]

Specifies how deeply CodeWizard should traverse the call stack in checking for violations.This option currently only affects item 16, which suggests that operator= should assign alldata members. With the default setting of 1, CodeWizard will see all assignments made inoperator= and any function called by operator=. However, if one of the functions called byoperator= calls another function which assigns a data member, CodeWizard will not see thisassignment and will report a violation. With this option set to 2, CodeWizard will see theassignment and will not report a violation.

19. codewizard.msgsrcsize [0|1|2|3|...20]

used to indicate how many source lines should be include in the error message. Available inStandard out, Standard error and Report file.

%p Process ID of the process incurring the error.

%t Time at which the error occurred. (HH:MM:SS).

%v The severity level of a violation.

%V Brief description of violation.

35

Customizing CodeWizard Options With Configuration Files

20. codewizard.okmessage [message]

message you would like diplayed when CodeWizard doesn’t find any bugs. Available in Stan-dard out, Standard error, and Report file.

21. codewizard.optionfile [option] file

Directs CodeWizard to read the specified file as a .psrc file. If [option] is specified, then itinterprets every line in the file as arguments to the option.

22. codewizard.preprocessor_flag flag

Specifies a flag or flags that can safely be passed to the preprocessor. Any flags on CodeWiz-ard command lines that are not listed in a preprocessor_flag statement will be strippedfrom the command before invoking the preprocessor. The list of pre-processor flags is usuallymaintained in the file:

<install_dir>/lib.$ARCH/$COMPILER/.psrc

Flags specified by this option will be passed to the preprocessor only, unless they are alsospecified in a preprocessor_propagate_flag option.

23. codewizard.preprocessor_propagate_flag flag

Specifies a flag or flags that should be passed to both the preprocessor and the compiler. If theflag is not listed in a preprocessor_flag option, this option will be ignored.

24. CodeWizard.proc_flags <flags>

This option specifies additional flags to be passed to the Oracle Proc. For more information,See “Oracle Proc Files” on page 29.

25. codewizard.report_banner [on|off]

Controls whether or not a message is displayed on your terminal, reminding you that errormessages have been redirected to a file.

26. codewizard.reportfile output;output

Specifies the name of the report file(s), using semi-colons (;) as separators. Environment vari-ables and various pattern generation keys may appear in filename. Add options for the particu-lar report type needed. Options include:

• insra for the Insra GUI

• stdout for standard output

• stderr for standard error

• grs to send results to the GRS server

• filepath for the path to the report file

For example, to send reports to both insra and standard error use reportfileinsra;stderr;/tmp/myfile.txt

36

Customizing CodeWizard Options With Configuration Files

27. codewizard.report_overwrite [on|off]

If set to off, error messages are appended to the report file rather than overwriting it on eachrun.

28. codewizard.rulefile <rule/file/path>

Using this option, the user can analyze source code against one particular rule. For example,to load a given rule:

CodeWizard.rulefile ./cw_install_dir/rules/paramnameinprototype.rule

(Note: ignore the line break in this example; this is due to space restrictions on the manualpage. A space comes between the word rulefile and the ./).

29. codewizard.rulesdirlist filename

Specifies the path to a text file that lists a set of user-defined .rule files that you CodeWizard toenforce; the rules listed in the text file must be contained in the same directory as the text file.By default, this option is set to <codewizard_install_dir>/rules/ cwrules.txt. You may have morethan one rulesdirlist entry.

30. codewizard.ruleset NAME PATH

NAME is the identifier. PATH is the absolute location of shared libraries. Set PATH to empty tonot load libraries. Basic libraries that come with CodeWizard are Effective C++, More EffectiveC++, MK, and UCS.

31. codewizard.skipduplicatedmessages [yes|no]

Using this option, CodeWizard collects all triggered messages and skips those that are dupli-cates, that is, that have already been triggered.

For example, skipduplicatedmessages yes.

32. codewizard.support [support_type]

Using this option, CodeWizard creates additional files for support. Add options for the particu-lar support type needed. Options include:

• source for source file

• log for log files

• preprocessed for preprocessed files

For example, support log preprocessed to create both a log file and a preprocessed filefor support purposes.

33. codewizard.supportpath [pathname]

Use this option to save your support results to a particular location. For example, support-path tmp/cwsupportdir.

37

Customizing CodeWizard Options With Configuration Files

34. codewizard.suppress [class <name>] [file <name>] [item <number>] [line <number(s)>] [typeI|PSV|PV|SV|V] [all]

Suppresses violations matching the indicated suppression codes. Only one of each type ofsuppression category is allowed per line. For example:

suppress class foo file foo.c item ecpp-2 line *-10 type I

is allowed, but:

suppress class foo class bar

is not.

Of course, multiple lines are permissible, with later unsuppress options superseding earliersuppress options (and vice-versa) if there are common categories. The all category sup-presses all messages. It can be used in conjunction with subsequent unsuppress options toturn on a limited set of messages.

The line field allows you to enter a number of lines for which messages will be suppressed orunsuppressed. A field containing only "*" will match all lines. Available statements:

• 2 - line 2

• 2-10 - lines from 2 to 10

• *-10 - lines less and equal 10

• 2-* - lines equal and greater than 2

• * or *-* - all lines

You can type more than one line statement per line by using a comma as a separator (don'tuse white spaces between line numbers and the commas). For example: *-4,7,9-12,15-*- indicates that you want to look at start to 4, then 7, then from 9 to 12, and then from 15 to theend.

35. codewizard.suppress_c_structs [on|off]

Suppresses item violations in C structs using a heuristic method. Turning this option to off willdisable this method, and may result in some incorrect item violations.

36. codewizard.suppress_file string

This option tells CodeWizard not to report any violations from files which match the string. Thestring should be a glob-style regular expression and should include the full path. This optionoverrides any suppress options. To see violations from the files covered by this option, you willneed to remove it. The unsuppress option will not unsuppress violations from these files.

37. codeWizard.suppress_line_with_function_macro [on|off]

This option is used to suppress messages originating from code that was created by expand-ing function-like macros.

This suppression applies only to macros defined in suppressed header files (for example,using the "CodeWizard.suppress_file" option). The default value is on.

38

Customizing CodeWizard Options With Configuration Files

38. codeWizard.suppress_line_with_macro [on|off]

This option operates exactly as the option "CodeWizard.suppress_line_with_function_macro".It is provided for backward compatibility only.

39. codeWizard.suppress_line_with_simple_macro [on|off] This option suppresses messages originating from code that was created by expanding simple(not function-like) macros. This suppression applies only to macros defined in suppressedheader files (for example, using the "CodeWizard.suppress_file" option). The default value isoff.

40. codewizard.suppress_warning code

Suppresses parser warnings matching the indicated code. The code should match the numeri-cal code CodeWizard prints with the warning message you would like to suppress. The codescorrespond to the chapter, section, and paragraph(s) of the draft ANSI standard on which thewarning is based. For example, to suppress the warning:

Warning:12.3.2-5: return type may not be

specified for conversion functions

add the following line to your .psrc file.

suppress_warning 12.3.2-5

41. codewizard.temp_directory path

Specifies the directory where CodeWizard will write its temporary files, for example, /tmp. Thedefault is the current directory.

42. codewizard.textanalyzeheader [yes|no]

Configures CodeWizard to analyze included headers using textwizard analyze feature.

For example, textanalyzeheader yes.

43. codeWizard.text_analyze_only [on|off] This option tells CodeWizard to perform analysis using text rules only (that is, only RuleWiz-ard's "C++Text" dictionary will be used during analysis). This option also implies that only agiven source file will be checked — all included files will be ignored. The default value is off.

44. codewizard.timestamp YYYY-MM-DD

CodeWizard will not check a file if its modification date is older than its timestamp date.Acceptable date format is YYYY-MM-DD.

45. codewizard.unsuppress [class <name>] [file <name>] [item <number>] [line <number(s)>][type I|PSV|PV|SV|V] [all]

Unsuppresses violations matching the indicated suppression codes. For more details on howto properly use this option, see the suppress option.

39

Customizing CodeWizard Options With Configuration Files

Options Used by InsraRunning Insra

1. insra.body_background_color [White|color]

Specifies the color Insra will use for the message body area background.

2. insra.body_font [Fixed|font]

Specifies the font Insra will use for the message body text. On some systems, for example,SGI, the Fixed font is much too large. This option can be used to select a smaller font.

3. insra.body_height [0|1|2|...|80|...]

Specifies the starting height of the Insra message body area in number of rows of visible text.This may be modified while Insra is running using the standard Motif controls.

4. insra.body_text_color [Black|color]

Specifies the color Insra will use for the message body text.

5. insra.body_width [0|1|2|...|80|...]

Specifies the starting width of the Insra message body area in number of columns of visibletext. This may be modified while Insra is running using the standard Motif controls. If this optionis set to a different value than header_width, the larger value will be used.

6. insra.header_background_color [White|color]

Specifies the font Insra will use for the message header area background.

7. insra.header_font [Fixed|font]

Specifies the font Insra will use for the header body text. On some systems, for example, SGI,the Fixed font is much too large. This option can be used to select a smaller font.

8. insra.header_height [0|1|2|...|80|...]

Specifies the starting height of the Insra message header area in number of rows of visibletext. This may be modified while Insra is running using the standard Motif controls.

9. insra.header_highlight_color [LightSteelBlue2|color]

Specifies the color Insra will use to indicate the currently selected message or session headerin the message header area.

40

Customizing CodeWizard Options With Configuration Files

10. insra.header_highlight_text_color [Black|color]

Specifies the color Insra will use for the text of the currently selected message or sessionheader in the message header area.

11. insra.header_session_color [Black|color]

Specifies the color Insra will use to indicate a session header.

12. insra.header_text_color [Black|color]

Specifies the color Insra will use to for session header text.

13. insra.header_width [0|1|2|...|80|...]

Specifies the starting width of the Insra message header area in number of columns of visibletext. This may be modified while Insra is running using the standard Motif controls. If this optionis set to a different value than body_width, the larger value will be used.

14. insra.port [3255|port_number]

Specifies which port Insra should use to communicate with CodeWizard.

15. insra.toolbar [on|off]

Specifies whether Insra's toolbar is displayed. All toolbar commands can also be chosen fromthe menu bar.

16. insra.visual [xterm -e vi +%l %f|emacs +%l %f]

Specifies how Insra should call an editor to display the line of source code causing the error.Insra will expand the %l token to the line number and the %f token to the file name before exe-cuting the given command. It is important to include the full path of any binary that lives in alocation not on your path. Setting this option with no command string disables source browsingfrom Insra.

41

Insra

Viewing Results in InsraInsraInsra is a graphical user interface for displaying violation messages generated by CodeWizard. Themessages are summarized in a convenient display, which allows you to quickly navigate through thelist of violation messages, suppress messages, invoke an editor for immediate corrections to thesource code, and delete messages as violations are fixed.

Topics discussed in this section include:

• “The Insra Display”

• “Sending Messages to Insra”

• “Viewing and Navigating”

• “Deleting Messages”

• “Suppressing Messages”

• “The Suppressions Tool Bar”

• “Miscellaneous Issues”

• “Troubleshooting”

• “Help”

The Insra DisplayStatus BarDuring analysis, CodeWizard makes a connection to Insra each time a violation is detected. The statusbar will report the number of violation messages currently being displayed and the number of activeconnections. An active connection is denoted by a yellow star to the left of the session header. A con-nection will remain active as long as the program is still compiling/running. Insra will not allow you todelete a session header as long as its connection remains active, and you may not exit Insra until allconnections have been closed.

Tool BarToolbar

Session Header

Message Header

Status Bar

42

Insra

The tool bar allows you to:

• Scroll up and down through messages.

• Delete selected messages as bugs are fixed.

• Suppress violations detected by CodeWizard.

• Sort messages by order (time) reported, violation category, or directory and file.

• Kill the selected active connection.

Message Header AreaThe message header area contains session headers and message headers for programs currentlyconnected to Insra.

Session HeaderWhen the first violation is detected for a particular compilation or execution, a session header is sent toInsra. The session header includes the following information:

• Compilation/execution

• Source file/program

• Host on which the process is running

• Process ID

Message HeaderMessage headers generated by CodeWizard include:

• Item violated and severity of violation

• File name

• Line number of violation

All messages sent to Insra are marked with a special icon. Refer to the following table for a briefdescription of each icon.

Clicking the ‘+” sign next to the message header will reveal the source code where the violation occurs.Double-clicking a message header brings up a Message window.

Icon Explanation

CodeWizard violation message

Trapped signal

43

Insra

Error Message WindowThe Message window opens when you double-click a message header. This window contains the vio-lation message for the selected message header.

CodeWizard’s Message window contains:

• The line of source code where the violation occurred.

• An explanation of the violation detected.

To make immediate corrections to the source code, simply double-click the excerpt of code shown inInsra, or click the arrow in the Message window. This will open the file in a text editor, and bring youdirectly to the line containing the violation..

Sending Messages to InsraBy default, both CodeWizard sends output messages to Insra. You may choose to send your output toanother location, such as stderr, stdout, or a report file of your choice. To change your output loca-tion, you would enter the following line to your .psrc file:

codewizard.report_file <filename>

The option:

codewizard.runtime.report_file insra

will send only runtime messages to Insra. Compile-time messages will be sent to stderr.

The option:

codewizard.compile.report_file insra

will send only compile-time messages to Insra. Run-time messages will be sent to stderr.

To direct messages back to Insra, simply replace the above line with the following line in your .psrcfile:

codewizard.report_file insra

Your compile-time and run-time messages will be sent to Insra. When CodeWizard is configured tosend output to Insra, CodeWizard attempts to establish a connection to Insra each time a violation isdetected. If Insra is not yet running, it will automatically start. Once the connection is established, asession header and all corresponding message headers will be reported in the order they were

44

Insra

detected. Each new compilation or program, with its own session header and messages, will be dis-played in the order in which it connected to Insra. To change your output location using the commandline, see “Customizing CodeWizard Options With Configuration Files” on page 30.

Viewing and NavigatingMessage headers sent to Insra are denoted by specific icon. (See “The Insra Display”). The body of thecurrently selected message is displayed in a separate Message window. Double-click the messageheader to view the message itself. The message header area and the Message window are both resiz-able, and scroll bars are also available to access text that is not visible. Currently active messagesbecome inactive when they are deleted or suppressed

Deleting MessagesOnce violation messages have been read and analyzed, you may wish to clear them from the window.The Delete button on the Insra tool bar allows you to remove messages from the display as violationsare corrected in your code. A message or an entire session may be removed by selecting the corre-sponding entry in the message header area and clicking the Delete button. A message can also bedeleted by selecting Messages> Delete from the menu bar.

Suppressing MessagesYou can use suppressions to tailor CodeWizard's output to your development team and the currentproject. By default, CodeWizard is configured to suppress all violations that have an Informationalseverity and all violations in the Universal Coding Standard category, then unsuppress any violationsthat have a Severe Violation severity and unsuppress any enabled User items.

Suppressions are entered in the Suppressions Control Panel, which is accessible by clicking the Sup-press button in Insra when Insra is running and contains violations. For more information about sup-pressing and unsuppressing messages, see “Customizing Output With Suppressions” on page 19.

The Suppressions Tool BarMoving from left to right across the suppressions tool bar:

The Prev and Next arrows select the next higher or next lower suppression option, respectively.

The Up and Down arrows move the currently selected suppression option up or down in the order ofoptions. Because CodeWizard follows suppression options in the order they are listed (from top to bot-tom), they order in which they are listed affects the outcome of the suppressions.

The Delete button deletes the currently selected suppression option.

The Insert button inserts a new suppression option below the currently selected option. If you had aviolation message selected when you pressed the Suppress button on the Insra GUI, a suppressionoption for that particular violation will be inserted. Otherwise, the default suppression option (suppressall violation messages) will be inserted.

The Save button writes all the suppression options which have been marked as persistent (see below)into the indicated .psrc files (see below). These suppression options will be in effect the next time youuse CodeWizard.

The Help button provides context-sensitive help, which in this window means that clicking anywherewill bring up this file.

The Close button closes the suppression window.

45

Insra

Miscellaneous IssuesSuppression options are read from top to bottom when determining which messages will be displayed.

Kill ProcessWhen an active connection is selected, pressing the Kill button will stop the selected compilation orexecution.

Viewing Source FilesYou can view the corresponding source file and line number for a particular violation message by dou-ble clicking on any line of the stack trace displayed in the Message window. In most cases, the file andline number associated with a given message have been transmitted to Insra. If Insra is unable tolocate the source file, a dialog box will appear requesting that you indicate the correct source file.

Selecting an EditorIn addition to the location of the source file, Insra must also know the name of your editor, and (if avail-able) the command line syntax, in order to display the correct file and line from the original sourcecode.

Insra obtains information by reading the .psrc option:

insra.visual [editor_command]

This command may contain the special token %f and %l, which represent the file name and line num-ber, respectively.

The command will then be executed to lead the file into your editor. It is most important to include thefull path of any binary that lives in a location not pointed to by your PATH environment variable. If thevariable has not been set, vi will be used by default.

Some editors are not X applications and must be run in a terminal window. vi requires the followingcommand in order to lead the file successfully:

insra.visual xterm -e vi +%l %f

Other editors (for example, Emacs) do not require an external terminal program like xterm when config-ured for use as an X application. In this case, the command string should be similar to the following:

insra.visual emacs +%l %f

Note: Most implementations of vi and Emacs appear to be sensitive to the order of the line number andfile name command line arguments, requiring the line number to precede the file name.

Saving/Loading MessagesAll current messages can be saved to a file by selecting File> Save or File> Save As from the Insramenu bar. A dialog box allows you to select the destination directory and name of the report file. Reportfiles have the default extension rpt. After a report file name has been selected, subsequent File>Save selections save all current messages into the report file without prompting for a new filename. Apreviously saved report file can be loaded by selecting File> Load from the menu bar. A dialog boxthen allows you to select which report file to load.

The command insra.visual [editor command] specifies how Insra should call an editor to dis-play the line of source code causing the violation. Insra will match the %l token to the line number andthe %f token to the file name before executing the command. Setting this option with no commandstring disables source browsing from Insra. The default is: xterm -e vi +%l %f.

46

Insra

TroubleshootingInsra Does Not Start AutomaticallySymptom:

While compiling or running, your program seems to hang when output is directed to Insra and Insra isnot yet running.

Solution:

Run Insra by hand. Type

insra &

at the prompt, wait for the Insra window to appear, and then run or compile your program again. Outputshould now be sent to Insra.

Multiple Users of Insra On One MachineSymptom:

When more than one user is attempting to send message reports to Insra, messages are lost.

Solution:

Each invocation of Insra requires a unique port number. By default, Insra uses port 3255. If collisionsare experienced, e.g. multiple users are on one machine, set the .psrc option insra.port to a dif-ferent port above 1024. Ports less than 1024 are officially reserved for suid-root programs and shouldnot be used with Insra.

Source Browsing Is Not WorkingSymptom:

***Error while attempting to spawn browser execvp failed!

Solution:

Insra attempted to launch your editor to view the selected source file, but could not locate either xtermor your editor on your path. Please make sure that both of these applications are in directories that areon your path or that you call them with their complete pathnames.

HelpOnline help can be obtained by choosing Help from the Insra menu bar. Help contains the followingdrop–down menu:

• Overview: About Insra

• Insra toolbar

• Sending messages to Insra

• Suppressing Messages

• Viewing Source Files

• Troubleshooting

• About

Choosing anyone of these options opens an online help window with links about the chosen subject.These same online links are available by simply clicking the Help button on the tool bar.

47

Rules Enforced

48

Static Analysis RulesRules EnforcedCode violations are reported in terms of the "items" described in several popular Scott Meyers books,including Effective C++ and More Effective C++. Violations in these two categories are labeled "ecpp-<item number>" for Effective C++ violations and "mecpp-<item number>" for More Effective C++ viola-tions.

These items are supplemented by the article “Examining C++ Program Analyzers” written by Meyersand Martin Klaus and published in the February 1997 issue of Dr. Dobbs' Journal. Violations in this cat-egory are labeled "MK-<item number>" for Meyers-Klaus violations.

A fourth violation category includes industry accepted C++ coding rules known collectively as the Uni-versal Coding Standards. Violations in this category are labeled "ucs-<item number>" for ucs viola-tions.

Using the new RuleWizard feature, you can even create your own "custom" C or C++ items for ruleenforcement pertaining to your particular company, project, or personal coding needs. These customitems are included in the fifth violation category, User Items. Violations in this category are labeled“user-<item number> for user-customized violations.

Included within the User Item category is a set of built-in, modifiable “items” written by Parasoft basedupon specialized groups of standards. These items encompass 32-bit to 64-bit transition rules, Text-related rules, Metrics rules, Naming Conventions rules, and others. Violations of these built-in, modifi-able coding standards are labeled in the same manner as the custom user rules, “user-<item number>.See User Items for a more detailed description of these specialized items.

Each item, along with a general description, is accompanied by its category, the severity of the viola-tion, and whether it is enabled by default. Items reported have different levels of severity. The higherthe level of severity an item is assigned, the greater the chance that violating that error will result in abug. Each level is identified by its own unique abbreviation, as shown in the following table:

Each item category is described in depth within the following sections:

• Effective C++ Items

• More Effective C++ Items

• Built-in MISRA Guidelines

• Meyers-Klaus Items

• Universal Coding Standard Items

• User Items

• Ellemtel (Telecom Industry) Items

• User MISRA Guidelines

Severity Explanation

I Informational: least chance of resulting in a bug

PV Possible Violation

V Violation

PSV Possible Severe Violation

SV Severe Violation: greatest chance of resulting in a bug

Effective C++ Items

Effective C++ ItemsEffective C++ ItemsCategory Item Description Violation Enabled?

Shifting from C to C++

2 Prefer iostream.h to stdio.h. I N

3 Use new and delete instead of malloc and free.

V Y

Memory Management

5 Use the same form in corresponding calls to new and delete.

V Y

6 Call delete on pointer members in destruc-tors.

V Y

7 Check the return value of new. I N

8 Adhere to convention when writing new. V Y

9 Avoid hiding the global new. SV Y

10 Write delete if you write new. SV Y

Constructors, Destructors, and Assignment Operators

11 Define a copy constructor and assignment operator for classes with dynamically allo-cated memory.

V/ SV Y / Y

12 Prefer initialization to assignment in con-structors.

I N

13 List members in an initialization list in the order in which they are declared.

V Y

14 Make destructors virtual in base classes. SV Y

15 Have operator= return a reference to *this. SV Y

16 Assign to all data members in operator= PSV Y

17 Check for assignment to self in operator= PV Y

Classes and Functions: Design and Declaration

19 Differentiate among member functions, global functions, and friend functions.

V Y

20 Avoid data members in the public inter-face.

V Y

22 Pass and return objects by reference instead of by value.

V Y

23 Don't try to return a reference when you must return an object

PSV Y

25 Avoid overloading on a pointer and a numerical type.

V Y

49

Effective C++ Items

Item ecpp-2Prefer iostream.h to stdio.hThis rule finds instances of stdio.h functions (such as scanf/printf) and suggests changing them to iostream.h functions (such as operator>> and operator<< ). Errors are marked as violations of Item ecpp-02.

Reason for rule: iostream.h functions are type-safe and extensible.

Note: This item is suppressed by default.

Example/* * Item 2 - Prefer iostream.h to stdio.h */#include <stdio.h>

int main(){ printf("%s\n", "Hello World"); // ECPP item 2 violation return 0;}

Output[item02.C:8] Prefer iostream.h to stdio.hInformational: Effective C++ item 2

Classes and Functions: Implementation

29 Avoid returning "handles" to internal data from const member functions.

SV Y

30 Avoid member functions that return point-ers or references to members less acces-sible than themselves.

V Y

31 Never return a reference to a local object or a dereferenced pointer initialized by new within the function.

PSV / SV Y / Y

Inheritance and Object-Oriented

37 Never redefine an inherited nonvirtual function.

PV/V Y /Y

38 Never redefine an inherited default param-eter value.

I / V N /Y

39 Avoid casts down the inheritance hierar-chy.

I N

50

Effective C++ Items

Item ecpp-3Use new and delete instead of malloc and freeThis rule warns you if malloc and free are used in your code. Errors are marked as violations of Item ecpp-3.

Reason for rule: new and delete can handle constructors and destructors.

Example/* * Item 3 - Use new and delete instead of malloc and * free */

#include <malloc.h>int main(){ char *pc; pc = (char *)malloc(100); // ECPP item 3 violation free(pc); // ECPP item 3 violation return 0;}

Output[item03.C:10] Use new instead of mallocViolation: Effective C++ item 3

[item03.C:11] Use delete instead of freeViolation: Effective C++ Item 3

51

Effective C++ Items

Item ecpp-5Use the same form in corresponding calls to new and deleteThis rule checks calls to new and delete to make sure that they use the same form; it reports a viola-tion if you call new but forget to use [ ] when calling delete. Errors are marked as violations of Item ecpp-5.

Reason for rule: If you do not use the same form in corresponding calls to new and delete, an incor-rect number of destructors may be called.

Example/* * Item 5 - Use the same form in corresponding calls to * new and delete */class A{public: A() {}};

int main(){ A *a = new A[100]; delete a; // ECPP item 5 violation}

Output[item05.C:15] Use the same form in correspondingcalls to new and deleteViolation: Effective C++ item 5Found new[] with delete.

52

Effective C++ Items

Item ecpp-6Call delete on pointer members in destructorsThis rule warns you if it finds a pointer member that has no corresponding delete in the destructor. Errors are marked as violations of Item ecpp-6.

Reason for rule: Calling delete on pointer members in destructors prevents memory leaks now and as the code evolves in the future.

This severity level of this item is Violation (V).

Example/* * Item 6 - Call delete on pointer members in * destructors (SV,V). */class A{public: A() { cptr1=new char; cptr2=new char; } ~A() { // ECPP item 6 violation delete cptr1; delete vptr1; }

private: char *cptr1; void *vptr1; char *cptr2;};

int main(){ return 0;}

Output[item06.C:5] Call delete on pointer members in destructorsViolation: Effective C++ item 6Class A contains pointer members not obviously deleted in destructor:cptr2 ** allocated in constructor **

53

Effective C++ Items

Item ecpp-7Check the return value of newThis rule warns you if you do not check the return value of new. Errors are marked as violations of Item ecpp-7.

Reason for rule: In cases where new cannot allocate the requested memory, it will return 0.

Note: This item is suppressed by default.

Example/* * Item 7 - Check the return value of new */

int main(){ char *pc;

pc = new char[10*10*10]; // ECPP item 7 violation pc[0] = 'x'; delete [] pc; return 0;}

Output[item07.C:9] Check the return value of newInformational: Effective C++ item 7

54

Effective C++ Items

Item ecpp-8Adhere to convention when writing newWhen you write operator new, this rule checks to make sure that you are consistent with the default new. Errors are marked as violations of Item ecpp-8.

Reason for rule: 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/* * Item 8 - Adhere to convention when writing new */#include <stdlib.h>

class A{public: A() {} int* operator new(size-t size) // ECPP item 8 violation return (int *)(new int); };};

int main(){ return 0;}

Output[item08.C:10] New should return void *Violation: Effective C++ item 8

55

Effective C++ Items

Item ecpp-9Avoid hiding the global newThis rule detects when the global new is hidden by an operator new. Errors are marked as violations of Item ecpp-9.

Reason for rule: If you hide the global new, normal new operator functionality will be unavailable to maintainers of your code.

Example/* * Item 9 - Avoid hiding the global new */

#include <stdlib.h>

void ErrorHandler() {};

class A{public: void* operator new(size-t size, void (*pehf)()) // ECPP item 9 violation { return new int[size]; } void operator delete(void *A) { delete A; }};

int main(){ A *a = new (ErrorHandler) A; return 0;}

Output[item09.C:12] Avoid hiding the global newSevere violation: Effective C++ item 9

56

Effective C++ Items

Item ecpp-10Write delete if you write newThis rule makes sure that if you write your own version of operator new, you also write a corre-sponding operator delete. Errors are marked as violations of Item ecpp-10.

Reason for rule: If you write delete when you write new, you ensure that new and delete share the same assumptions.

Note: Item user-212 is a customizable version of this rule.

Example/* * Item 10 - Write delete if you write new. */

#include <stdlib.h>class A{ // ECPP item 10 violationpublic: A() {} void* operator new(size-t size) { return new int[size]; }};int main(){ A *a = new A; return 0;}

Output[item10.C:11] Write delete if you write newSevere violation: Effective C++ item 10

57

Effective C++ Items

Item ecpp-11Define a copy constructor and assignment operator for classes with dynamically allocated memoryThis rule ensures that copy constructors and assignment operators have been defined in classes with dynamically allocated memory. Errors are marked as violations of Item ecpp-11.

Reason for rule: By defining a copy constructor and assignment operator, you achieve significant memory savings and increased speed.

ExampleViolations of Item 11 are reported as either Violation (V) or Severe (SV). Examples of both are provided here.

/* * Item 11 - Define a copy constructor and an * assignment operator for classes with dynamically * allocated memory (V). */

class A{public: class X {}; A() { // ECPP item 11 violation cptr1 = new char[100]; if (!cptr1) { throw X(); } } ~A() {}

private: char *cptr1; void *vptr1; char *cptr2;};

int main(){ return 0;}

58

Effective C++ Items

/* * Item 11 - Define a copy constructor and an assignment * operator for classes with dynamically allocated * memory. (SV) */

class A{private: char *cptr1; void *vptr1; char *cptr2; public: A() {} ~A() { // ECPP item 11 violation delete cptr1; delete vptr1; delete cptr2; }};

int main(){ return 0;}

Output[item11V.C:7] Define a copy constructor and operator=for classes with dynamically allocated memoryViolation: Effective C++ item 11Class A missing assignment operator and copy constructor.

[item11SV.C:7] Define a copy constructor and operator=for classes with dynamically allocated memorySevere violation: Effective C++ item 11Class A missing assignment operator and copy constructor.

59

Effective C++ Items

Item ecpp-12Prefer initialization to assignment in constructors This rule checks constructors to see if you are assigning data members when you should be initializing them. const and reference can only be initialized, never assigned. Errors are marked as violations of Item ecpp-12.

Reason for rule: If you use initialization instead of assignment, you will increase efficiency and call fewer member functions.

Exception: The only time you should use assignment instead of initialization for data members in a class is when you have a large number of data members of built-in types and you want them all to be initialized in the same way in each constructor.

Note: This item is suppressed by default.

Example /* * Item 12 - Prefer initialization to assignment in * constructors */

class A{public: A(int i, float j) { // ECPP item 12 violation _idata = i; _fdata = j; }

private: int _idata; float _fdata;};

int main(){ return 0;}

Output [item12.C:9] Prefer initialization to assignmentin constructorsInformational: Effective C++ item 12

[item12.C:10] Prefer initialization to assignmentin constructorsInformational: Effective C++ item 12

60

Effective C++ Items

Item ecpp-13 List members in an initialization list in the order in which they are declaredThis rule checks initialization lists to make sure that members are listed in the same order there as they were when declared in the class. Errors are marked as violations of Item ecpp-13.

Reason for rule: Class members are initialized in the order of their declaration in the class, not by the order in which they are listed in a member initialization list.

Example/* * Item 13 - List members in an initialization list in * the order in which they are declared */

class A{public: // ECPP item 13 violation A(int i1, int i2, int i3) : idata3(i3), idata2(i2), idata1(i1) {}

private: int idata1, idata2, idata3;};

int main(){ return 0;}

Output[item13.C:10] List members in an initialization listin the order in which they are declared Violation: Effective C++ item 13

61

Effective C++ Items

Item ecpp-14Make destructors virtual in base classesThis rule verifies that destructors in base classes are virtual. Errors are marked as violations of Item ecpp-14.

Reason for rule: Declaring the destructor virtual tells the compiler that it must examine the object being deleted to see where to start calling destructors.

Example/* * Item 14 - Make destructors virtual in base classes */

class Base{public: Base() {} ~Base() {} // ECPP item 14 violation};

class Derived: public Base{public: Derived() {}; ~Derived() {};};

int main(){ return 0;}

Output[item14.C:6] Make destructors virtual in base classesSevere violation: Effective C++ item 14Class Base is a base class but does not have a virtualdestructor

62

Effective C++ Items

Item ecpp-15 Have operator= return a reference to *thisThis rule makes sure your assignment operators return a reference to their left-hand argument, *this. Errors are marked as violations of Item ecpp-15.

Reason for rule: 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 refer-ence to const, which is safer than just declaring it to be a reference.

Example/* * Item 15 - Have operator= return a reference to *this */

class A{public: explicit A(int i = 0) : _i(i) {} void operator=(const A& a) // ECPP item 15 violation { if (&a == this) { return; } int _i = a._i; return; } private: int _i;};

int main(){ return 0;}

Output[item15.C:9] Have operator= return a reference to*this Severe violation: Effective C++ item 15

63

Effective C++ Items

Item ecpp-16 Assign to all data members in operator=If you write operator=, this rule ensures that you assigned to every data member of your object. Errors are marked as violations of Item ecpp-16.

Reason for rule: Assigning to all data members in operator= allows you to take control of your assignments.

Example/* * Item 16 - Assign to all data members in operator= */

class A{public: A() {} A& operator=(const A&);

private: int _x, _y, _z;};

A& A::operator=(const A& a) // ECPP item 16 violation{ if (&a == this) { return *this; } _x = a._x; _y = a._y; return *this;}

int main(){ return 0;}

Output[item16.C:16] Assign to all data members in operator=Possible severe violation: Effective C++ item 16Members not assigned: _z

64

Effective C++ Items

Item ecpp-17 Check for assignment to self in operator= This rule checks your code for aliasing in assignment operators. Errors are marked as violations of Item ecpp-17.

Reason for rule: Not checking for assignment to self in operator= can free resources that might be needed during the process of allocating new resources. Checking for assignment to self may also save you a lot of work that you would otherwise have to do to implement assignments.

Example/* * Item 17 - Check for assignment to self in operator= */

class A{public: A() {} A& operator=(A& a) // ECPP item 17 violation { _i = a._i; return *this; }

private: int _i;

}; int main(){ return 0;}

Output[item17.C:8] Check for assignment to self in operator=Possible violation: Effective C++ item 17 expected: if (&a == this) return *this;

65

Effective C++ Items

Item ecpp-19 Differentiate among member functions, global functions, and friend functionsThis rule checks declared functions to make sure they are proper for the class type used. Disallowed functions are marked as violations of Item ecpp-19.

Reason for rule: Differentiating among functions leads to more object-oriented code with behavior that is more intuitive to use and maintain.

Example/** Item 19 - Differentiate among member, global, and * friend functions.*/

class Rational{public: Rational(int _num = 0, int _den = 1); int numerator() const { return _num; } int denominator() const { return _den; } Rational operator*(const Rational& rhs) const; // ECPP item 19 violation private: int _num; int _den;};

Rational Rational::operator*(const Rational& rhs) const{ Rational temp(_num * rhs.numerator(), _den * rhs.denominator()); return temp;}

int main(){ return 0;}

Output[item19.C:12] Differentiate among member functions,global functions and friend functionsViolation: Effective C++ item 19Function * should be global

66

Effective C++ Items

Item ecpp-20Avoid data members in the public interfaceThis rule warns you if data members are present in the public interface. Instead of making data mem-bers public, you should use functions. Errors are marked as violations of Item ecpp-20.

Reason for rule: Avoiding data members in the public interface provides more precise control over accessibility of data members, reduces confusion for callers, and enables functional abstraction (allow-ing the replacement of data members with computations without impacting users of the class). It also improves consistency, flexibility, and access-control.

Example/* * Item 20 - Avoid data members in the public interface */

class A{public: int _idata2; // ECPP item 20 violation int ReadData1(void) { return _idata1; } void WriteData1(int ival) { _idata1 = ival; }

private: int _idata1;};

int main(){ return 0;}

Output [item20.C:6] Avoid data members in the public interfaceViolation: Effective C++ item 20Public data members for class A:_idata2

67

Effective C++ Items

Item ecpp-22 Pass and return objects by reference instead of by valueThis rule detects where an object has been passed by value instead of by reference. These errors are marked as violations of Item ecpp-22.

Reason for rule: Passing and returning objects by reference is more efficient than passing by value because no new objects are being created and because it avoids the "slicing problem."

Exception: There are situations in which you cannot pass an object by reference (see Item ecpp-23). 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.

Example/* * Item 22 - Pass and return objects by reference * instead of by value */

class A{public: A() {} A foo(const A a) // 2 ECPP item 22 violations { // passing variables into foo by value return a; // returning by value when it is not required }};

int main(){ return 0;}

Output[item22.C:10] Pass objects by reference instead ofby valueViolation: Effective C++ item 22Parameter a of function foo passed by value

[item22.C:10] Return objects by reference instead of by valueViolation: Effective C++ item 22Function foo returns object by value

68

Effective C++ Items

Item ecpp-23Don't try to return a reference when you must return an objectThis rule detects when you return a reference where you are supposed to return an object. Errors are marked as violations of Item ecpp-23.

Reason for rule: Returning a reference instead of an object will result in corrupt data or a memory leak.

Example

/* * Item 23 - Don't try to return a reference when you * must return an object. */

class A{public: A(int num = 0, int den = 1) : _num(num), _den(den) {} int numerator() const { return _num; } int denominator() const { return _den; } private: int _num; int _den;};

// ECPP item 23 violationA& operator*(const A& lhs, const A& rhs) { A temp(lhs.numerator() * rhs.numerator(), lhs.denominator() * rhs.denominator()); return temp;}

int main(){ return 0;}

Output[item23.C:19] Don't try to return a reference when youmust return an objectPossible severe violation: Effective C++ item 23Operator * should return an object

69

Effective C++ Items

Item ecpp-25Avoid overloading on a pointer and a numerical typeThis rule detects when you are overloading on a pointer and a numerical type. Errors are marked as violations of Item ecpp-25.

Reason for rule: Calling with an argument of zero will invoke the numerical type even though it is intu-itively ambiguous.

Example/* * Item 25 - Avoid overloading on a pointer and a * numerical type. */

class A{public: int func(char *ch) { char c=*ch; return 0; } int func(int i) // ECPP item 25 violation { int var=i; return 0; }};

int main(){ return 0;}

Output[item25.C:8] Avoid overloading on a pointer and anumerical typeViolation: Effective C++ item 25 Function func overloaded at: [item25.C:8] [item25.C:13]

70

Effective C++ Items

Item ecpp-29Avoid returning "handles" to internal data from const member functionsThis rule detects when const member functions return “handles” to information that should be hidden. Errors are marked as violations of Item ecpp-29.

Reason for rule: If you return “handles” to internal data, you allow calling functions to modify variables that they should not have access to.

Example/* * Item 29 - Avoid returning "handles" to internal * data from const member functions */

class A{public: A() { ptr = 0; } operator char*() const { return ptr; } // ECPP item 29 violation

private: char *ptr;};

int main(){ return 0;}

Output[item29.C:13] Avoid returning "handles" to internaldata from const member functionsSevere violation: Effective C++ item 29

71

Effective C++ Items

Item ecpp-30 Avoid member functions that return pointers or references to members less accessible than themselvesThis rule detects when you write member functions that give clients access to restricted members. Errors are marked as violations of Item ecpp-30.

Reason for rule: Members are made private or protected to restrict access to them, so it does not make sense to write functions that give random clients the ability to freely access restricted members.

Exception: Cases where performance constraints dictate that you write a member function that returns a reference or pointer to a less-accessible member. To avoid sacrificing private and protected access restrictions, return a pointer to or a reference to a const object (see Item ecpp-21).

Example /* * Item 30 - Avoid member functions that return * pointers or references to members less accessible * than themselves */

class A{public: int& GetA() { return _personalA; }; // ECPP item 30 violation

protected: int _personalA;};

int main(){ return 0;}

Output [item30.C:9] Avoid member functions that returnpointers or references to members less accessiblethan themselvesViolation: Effective C++ item 30

72

Effective C++ Items

Item ecpp-31Never return a reference to a local object or a dereferenced pointer initialized by new within the functionThis rule detects when you return a reference to a local object or dereferenced pointer. Errors are marked as violations of Item ecpp-31.

Reason for rule: Returning a reference to a local object or a dereferenced pointer initialized by new within the function may cause a memory leak.

ExampleViolations of this item are reported as either Potentially Severe Violations (PSV) or Severe Violations (SV). Examples of both are provided here.

/* * Item 31 - Never return a reference to a local object * or a dereferenced pointer initialized by new * within the function */

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) // ECPP item 31 violation{ A *result = new A(p1._x + p2._x, p1._y + p2._y); return *result;}

int main(){ return 0;}

73

Effective C++ Items

/* * Item 31 - Never return a reference to a local object or a * dereferenced pointer initialized by new within * the function */

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) // ECPP item 31 violation{ A result(p1._x + p2._x, p1._y + p2._y); return result;}

int main(){ return 0;}

Output[item31PS.C:22] Never return a dereferenced localpointer initialized by new in this function scopePossible severe violation: Effective C++ item 31Dereferenced local pointer result returned.

[item31SV.C:22] Never return a reference to a localobjectSevere violation: Effective C++ item 31Reference to object result returned.

74

Effective C++ Items

Item ecpp-37Never redefine an inherited nonvirtual functionThis rule detects when you redefine an inherited nonvirtual function. These errors are violations of Item ecpp-37.

Reason for rule: Redefining an inherited nonvirtual function may cause objects to behave incorrectly.

Example Violations of this item are reported as either a Possible Violation (PV) or a Violation (V). Examples of both are provided here.

/* * Item 37 - Never redefine an inherited nonvirtual * function */

template<class T>class Base{public: void foo(T tval);};

template<class T>class Derived: public Base<T>{public: void foo(int tval); // ECPP item 37 violation};

int main(){ return 0;}

75

Effective C++ Items

/* * Item 37 - Never redefine an inherited nonvirtual function */

class Base{public: void func(void) {};};

class Derived: public Base{public: void func(void) {}; // ECPP item 37 violation};

int main(){ return 0;}

Output [item37PV.C:16] Never redefine an inherited nonvirtualfunctionPossible violation: Effective C++ item 37Redefinition of function foo in class DerivedFunction foo is inherited from class Base

[item37V.C:14] Never redefine an inherited nonvirtualfunctionViolation: Effective C++ item 37Redefinition of function func in class DerivedFunction func is inherited from class Base

76

Effective C++ Items

Item ecpp-38Never redefine an inherited default parameter valueThis rule detects where you redefine an inherited virtual function with a default parameter value. Errors are marked as violations of Item ecpp-38.

Reason for rule: As illustrated in the first example below, inherited nonvirtual functions should never be redefined. In the second example, virtual functions are dynamically bound and default parameter values are statically bound.

ExampleViolations of this item are reported as either Informational (I) or as a Violation (V). Examples of both are provided here.

/* * Item 38 - Never redefine an inherited default * parameter value */

template<class T>class Base{public: virtual void func(T i = -1111) {}};

template<class T>class Derived: public Base<T>{public: virtual void func(int i = 11) {} // ECPP item 38 violation};

int main(){ return 0;}

77

Effective C++ Items

/* * Item 38 - Never redefine an inherited default parameter * value */

class Base{public: virtual int func(int i = -1111) { return i; }};

class Derived: public Base{public: virtual int func(int i = 11) { return i; } // ECPP item 38 violation};

int main(){ return 0;}

Output [item38I.C:16] Never redefine an inherited default parameter valueInformational: Effective C++ item 38Function func in class Derived redefines default parameter i

[item38V.C:14] Never redefine an inherited default parameter valueViolation: Effective C++ item 38Function func in class Derived redefines default parameter i

78

Effective C++ Items

Item ecpp-39Avoid casts down the inheritance hierarchyThis rule detects casts from a base class pointer to a subclass pointer. Errors are marked as violations of Item ecpp-39.

Reason for rule: Allowing casts down the inheritance hierarchy leads to maintenance problems, and downcasting from a base class is always illegal. Note: This item is suppressed by default.

Example/* * Item 39 - Avoid casts down the inheritance hierarchy */

class Base {};

class Derived: public Base {};

int main(){ Base *pb; Derived *pd = (Derived *)pb; // ECPP item 39 violation return 0;}

Output[item39.C:12] Avoid casts down the inheritance hierarchyInformational: Effective C++ item 39Class Derived inherits from class Base

79

More Effective C++ Items

More Effective C++ ItemsMore Effective C++ ItemsCategory Item Description Violation Enabled?

Basics 2 Prefer C++ style casts V Y

Operators 5 Be wary of user-defined conversion functions I / V N / Y

6 Distinguish between prefix and postfix forms of increment and decrement operators

V Y

7 Never overload &&, | |, or , V Y

Efficiency 22 Consider using op= instead of stand-alone op V Y

24 Understand the costs of virtual functions, multi-ple inheritance, virtual base classes, and RTTI

V Y

Techniques 26 Limiting the number of objects in a class I N

80

More Effective C++ Items

Item mecpp-2Prefer C++ style castsThis rule detects C-style casts in your code. Errors are marked as violations of Item mecpp-02.

Reason for rule: C++ casts are more specific than C casts and are much easier to locate and read.

Example//// More Effective C++ Item 2//

class Base{public: Base(); virtual ~Base();};

class Derived : public Base{public: Derived(); ~Derived();};

int main(){ Base *pB; Derived *pD = (Derived *) pB; // MECPP item 2 violation. return 0;}

Output[ME-item02.C:23] Prefer C++-style castsViolation: More Effective C++ item 2

81

More Effective C++ Items

Item mecpp-5 Be wary of user-defined conversion functionsThis rule warns you when it finds user-defined conversion functions. Errors are marked as violations of Item mecpp-05.

Reason for rule: Using user-defined conversion functions may result in incorrect program behavior.

Note: The Information part of this rule is suppressed by default.

ExampleViolations are reported as either Information (I) or Violation (V). Examples of both are provided here.

//// More Effective C++ Item 5//

#include <stdlib.h>

class A{public: A(int i): _i(i) {} // MECPP item 5 violation virtual ~A() {} operator int() const // MECPP item 5 violation { return _i; } private: int _i;};

int main(){ int j = 10; A a(12); if (a < j) { // MECPP item 5 violation exit(1); } return 0;}

82

More Effective C++ Items

Output[ME-item05.C:8] Be wary of user-defined conversion functionsInformational: More Effective C++ item 5Constructor allowing conversion should be made explicit

[ME-item05.C:11] Be wary of user-defined conversion functionsViolation: More Effective C++ item 5User-defined conversion should be made explicit

[ME-item05.C:26] Be wary of user-defined conversion functionsViolation: More Effective C++ item 5Use of implicit cast should be made explicit

Item mecpp-6Distinguish between prefix and postfix forms of increment and decrement operatorsThis rule checks for a distinction between prefix and postfix forms of increment and decrement opera-tors. Failure to make this distinction in ++ and -- operators results in a violation of Item mecpp-06.

Reason for rule: Prefix and postfix forms return different types (prefix forms return a reference and postfix forms return a const object). Postfix operators should be implemented in terms of the prefix operator.

Example//// More Effective C++ Item 6//

class A{ friend bool operator==(const A&, int);

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

A& operator=(const A& a) { if (&a == this) { return *this; } _i = a._i; return *this; } A& operator=(int i) { _i = i; return *this; }

83

More Effective C++ Items

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

bool operator==(const A& a, int i){ return (a._i == i);}

bool operator!=(const A& a, int i){ return (!(a == i));}

int main(){ A a;

for (a = 0; a != 10; a++) { // MECPP item 6 violation // Do something }

return 0;}

Output[ME-item06.C:57] Distinguish between prefix and postfix forms of increment and decrement Violation: More Effective C++ item 6Prefix form is recommended here

84

More Effective C++ Items

Item mecpp-7Never overload &&, | |, or ,This rule detects when you overload operator && , | | or ,. Errors are marked as violations of item mecpp-07.

Reason for rule: Overloading these operators changes the way the compiler reads the semantics of an expression, resulting in unpredictable program behavior.

Example//// More Effective C++ Item 7//

class A{public: A(int i) : _i(i) {} ~A(); int value() { return _i; } private: int _i;};

operator&&(A& lhs, A& rhs) { // MECPP item 7 violation return lhs.value() && rhs.value();}

int main(){ return 0;}

Output[ME-item07.C:17] Never overload &&, || or ,Violation: More Effective C++ item 7Function && is overloaded

85

More Effective C++ Items

Item mecpp-22Consider using op= instead of stand-alone opThis rule warns you whenever it finds stand-alone versions of operator. Errors are marked as viola-tions of Item mecpp-22.

Reason for rule: Assignment versions of operator are more efficient than stand-alone versions.

Example//// More Effective C++ Item 22//

class A{public: A(int i) : _i(i) {} ~A(); int value() { return _i; } A operator+() {} // MECPP item 22 violation

private: int _i;};

int main(){ return 0;}

Output[ME-item22.C:13] Consider using op= instead ofstand-alone opViolation: More Effective C++ item 22Operator + found, but no appropriate operator += found

86

More Effective C++ Items

Item mecpp-24Understand the costs of virtual functions, multiple inheritance, virtual base classes, and RTTIThis rule warns you when virtual functions, multiple-inheritance, virtual base classes, and RTTI are implemented inefficiently. Errors are marked as violations of Item mecpp- 24.

Reason for rule: Inefficient implementation may have noticeable effects on the size of objects and the speed at which member functions execute, significantly impacting performance.

Example//// More Effective C++ Item 24//

class A{public: A(int i) : _i(i) {} virtual ~A() {} // MECPP item 24 violation int value() { return _i; } private: int _i;};

int main(){ return 0;}

Output[ME-item24.C:9] Understand the costs of virtualfunctions ... Violation: More Effective C++ item 24Function ~A is both virtual and inline

87

More Effective C++ Items

Item mecpp-26Limiting the number of objects in a classThis rule detects the need to limit the number of objects in a class. Errors are marked as violations of Item mecpp-26.

Reason for rule: Limiting the number of objects in a class can reduce code complexity. Note: This item is suppressed by default.

Example//// More Effective C++ Item 26//

class Base{public: class X {}; Base() { if(numObjects >= 1) throw X(); // constructor stuff here ++numObjects; } ~Base() { --numObjects; // destructor stuff here } private: static int numObjects;};

int main(){ return 0;}

Output[item06.C:6] Limiting the number of objects of a classInformational: More Effective C++ item 26

88

Built-in MISRA Guidelines

Built-in MISRA ItemsBuilt-in MISRA GuidelinesCodeWizard 4.3 includes a suite of rules to enforce requirements imposed by the Motor Industry Soft-ware Reliability Association (MISRA). These requirements can be found in the MISRA document "Guidelines For The Use Of The C Language In Vehicle Based Software.”

Note: All statically enforceable rules from the MISRA Guidelines document were implemented. This section contains those MISRA rules implemented in CodeWizard as Built-in rules. Built-in MISRA rules are grouped under common prefix "misra.” For example "misra-20," "misra-112," and so on. The num-ber corresponds to a number given to the rule in the original MISRA document.

Important Cross ReferencesMISRA User RulesAdditional MISRA guidelines are implemented in CodeWizard as User rules. see “User MISRA Guide-lines” on page 344 for more information on the MISRA User rules included in CodeWizard.

Important! What is the difference between Built-in MISRA rules and User MISRA rules?

• User MISRA rules, like all rules in the User category (including the Ellemtel rules), can be cus-tomized using RuleWizard.

• Built-in MISRA rules, along with the Effective C++, More Effective C++, Meyer-Klaus, and Uni-versal Coding Standard rules, cannot be altered using RuleWizard.

Multiple File Static AnalysisSome of the rules will need symbol information collected across multiple source files. For example, to verify that given symbol has only one definition, CodeWizard can analyze information collected from multiple sources, and issue a violation if more than a single definition was detected. To facilitate static analysis preformed on multiple files, CodeWizard is now bundled with a new command line utility (cwmfs), that is capable of enforcing the new built-in MISRA-25, MISRA-26, and MISRA-27 rules.

This utility is described after the following rule descriptions. For more information, see “CodeWizard's cwmfs Utility” on page 127.

Additional MISRA RulesA few MISRA rules are not supported by CodeWizard, because they are not statically enforceable. These include MISRA-2, MISRA-15, and MISRA-116. For more information, see “A Note On Additional MISRA Rules” on page 127.

A Note On Severity LevelsThe MISRA Guidelines classify rules as "required" or "advisory." CodeWizard uses "Violation" and "Informational" severity levels for rules classified as "required" and "advisory," respectively.

Item Description Violation Enabled?

1 All code shall conform to ISO 9899 standard C, with no exten-sions permitted.

V Y

12 No identifier in one name space shall have the same spelling as an identifier in another name space.

I Y

20 All object and function identifiers shall be declared before use. V Y

25 An identifier with external linkage shall have exactly one external definition.

V Y

89

Built-in MISRA Guidelines

26 If objects or functions are declared more than once they shall have compatible declarations.

V Y

27 External objects should not be declared in more than one file. I Y

29 The use of a tag shall agree with its declaration. V Y

34 The operands of a logical && or || shall be primary expressions. V Y

47 No dependence should be placed on C's operator precedence rules in expressions.

I Y

53 All non-null statements shall have a side-effect. V Y

66 Only expressions concerned with loop control should appear within for statement.

I Y

71 Functions shall always have visible prototype at both the function definition and call.

V Y

77 The type of parameters passed to a function should be compati-ble with expected types defined in prototype.

V Y

78 The type of parameters passed to a function should be compati-ble with expected types defined in prototype.

V Y

94 A function-like macro shall not be 'called' without all of its argu-ments.

V Y

95 Arguments to a function-like macro shall not contain tokens that look like pre-processing directives.

V Y

97 Identifiers in pre-processor directives should be defined before use.

I Y

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

V Y

112 Avoid using bit fields of type signed int which are less than two bits long.

V Y

115 Standard library function names shall not be reused. V Y

117 The validity of values passed to library functions shall be checked.

V Y

118 Dynamic heap memory allocation shall not be used. V Y

90

Built-in MISRA Guidelines

MISRA-1All code shall conform to ISO 9899 standard C, with no extensions permitted. The MISRA Guidelines require the use of a "standardized structured language." The rule applies this to the C programming language. Any detected compiler extensions in the code will be flagged as viola-tions of this rule. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example

/* misra001.c */

typedef void (*PTF)();

void foo() { void *ptr; PTF ptf = (PTF)ptr; /* violation - unable to cast from pointer to object to pointer to function */ }

#ifdef _MSC_VER /* MSVC specific part */ void __cdecl bar(); /* violation - uses msvc __cdecl keyword */ #endif /* _MSC_VER */

#ifdef __GNUC__ /* GNU gcc specific part */ struct Struct { char _c; int _buf[2] __attribute__ ((packed)); }; typedef int DeprecatedType1 __attribute__ ((deprecated)); DeprecatedType1 t1; #endif /* __GNUC__ */

Outputmisra001.c(8):All code shall conform to ISO 9899 standard C, with no extensions permitted.Violation: MISRA Guidelines item 1ISO 9899 nonconformance: invalid type conversion

misra001.c(14):All code shall conform to ISO 9899 standard C, with no extensions permitted.Violation: MISRA Guidelines item 1ISO 9899 nonconformance: incomplete type is not allowed

91

Built-in MISRA Guidelines

misra001.c(14):All code shall conform to ISO 9899 standard C, with no extensions permitted.Violation: MISRA Guidelines item 1ISO 9899 nonconformance: expected a ";"

misra001.c(22):All code shall conform to ISO 9899 standard C, with no extensions permitted.Violation: MISRA Guidelines item 1ISO 9899 nonconformance: expected a ";"

misra001.c(24):All code shall conform to ISO 9899 standard C, with no extensions permitted.Violation: MISRA Guidelines item 1ISO 9899 nonconformance: expected a ";"

MISRA-12No identifier in one name space shall have the same spelling as an identifier in another name space.The ISO 9899 C standard defines a number of different name spaces. Although it is technically possi-ble to use the same name in separate name spaces to represent completely different items, this prac-tice should not be used because it can cause confusion. Therefore, it is a violation to reuse names, even in separate name spaces. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra012.c */

typedef struct Violation /* tags name space */ { int Violation; /* violation - name space of struct 'Violation' */ } Violation; /* violation - name space of identifiers */

Outputmisra012.c(5):No identifier in one name space shall have the same spelling as an identi-fier in another name space.Informational: MISRA Guidelines item 12Name Violation already used in other namespace.

misra012.c(6):No identifier in one name space shall have the same spelling as an identi-fier in another name space.Informational: MISRA Guidelines item 12Name Violation already used in other namespace.

92

Built-in MISRA Guidelines

MISRA-20All object and function identifiers shall be declared before use.MISRA rule 20 requires that all objects and functions must be declared before they are used. A decla-ration provides information to the compiler about the type of an object or function.

For example, if undeclared function is found, the compiler will have to make assumptions about the function prototype, and will not verify if actual parameter types match types specified in function decla-ration. This may lead to undefined behavior, which can result in hard-to-find errors at runtime. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra020.c */

void foo(); int global;

void goo() { int local;

foo(); undeclaredfoo(); /* violation */ local = global; local = undefinedglobal; /* violation */ }

Outputmisra020.c(11):All object and function shall be declared before useViolation: MISRA Guidelines item 20Undeclared function: undeclaredfoo is used

misra020.c(13):All object and function shall be declared before useViolation: MISRA Guidelines item 20Undeclared variable: undefinedglobal is used

93

Built-in MISRA Guidelines

MISRA-25An identifier with external linkage shall have exactly one external definition.This rule issues a violation if more than one definition of an identifier is found. Multiple definitions of a symbol can be a serious problem even if they are of the same type. Note: This rule is implemented as a built-in rule and it is active for C code only. It can be enforced using cwmfs command line tool bun-dled with CodeWizard.

Example /* misra25_1.c */ int a;

/* misra25_2.c */ int a;

Outputmisra25_1.c(5):An identifier with external linkage shall have exactly one external defini-tion.Violation: MISRA Guidelines item 25An identifier `int a' has more than one definition:misra25_1.c:2: `int a'misra25_2.c:2: `int a'

MISRA-26If objects or functions are declared more than once they shall have compatible declarations.This rule will report a violation if incompatible variable of function types are encountered. Note: This rule is implemented as a built-in rule and it is active for C code only. It can be enforced using cwmfs command line tool bundled with CodeWizard.

Example /* misra26_1.c */

static void foo (float t, int a) { }

int a() { extern int boo(float); return boo(1); }

void bar(float t, int i) {} void bar_decl(float t, int i);

94

Built-in MISRA Guidelines

int someFunc(int i);

extern int b(int i); int b(int i); int b(int i); int b(int i) { return i; }

int foo1(float a) { return 0; }

int someOtherFunc(int i); int someOtherFunc(char *);

/* misra26_2.c */

static void foo(float t) { }

int b() { extern int boo(int); return boo(0); }

void bar(float t) { } void bar_decl(float t); void* someFunc(const char *);

int foo1(int a) { return 0; }

Outputmisra26_1.c(23):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int someOtherFunc(int)' have incompatible declaration:misra26_1.c:24: `int someOtherFunc(char *)'

misra26_1.c(16):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int b(int)' have incompatible declaration: misra26_2.c:6: `int b()'

misra26_1.c(17):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int b(int)' have incompatible declaration: misra26_2.c:6: `int b()'

95

Built-in MISRA Guidelines

misra26_1.c(18):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int b(int)' have incompatible declaration: misra26_2.c:6: `int b()'

misra26_1.c(19):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int b(int)' have incompatible declaration: misra26_2.c:6: `int b()'

misra26_1.c(7):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int boo(float)' have incompatible declaration: misra26_2.c:7: `int boo(int)'

misra26_1.c(11):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `void bar(float, int)' have incompatible declaration: misra26_2.c:11: `void bar(float)'

misra26_1.c(12):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `void bar_decl(float, int)' have incompatible declaration: misra26_2.c:12: `void bar_decl(float)'

misra26_1.c(14):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int someFunc(int)' have incompatible declaration: misra26_2.c:13: `void * someFunc(const char *)'

misra26_1.c(21):If objects or functions are declared more than once they shall have compat-ible declarations.Violation: MISRA Guidelines item 26Symbol `int foo1(float)' have incompatible declaration: misra26_2.c:15: `int foo1(int)'

96

Built-in MISRA Guidelines

MISRA-27External objects should not be declared in more than one file.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. Note: This rule is implemented as a built-in rule and it is active for C code only. It can be enforced using cwmfs com-mand line tool bundled with CodeWizard.

Example /* misra027.h */

extern int a;

/* misra027_1.c */

#include "misra027.h" int a;

/* misra027_2.c */

extern int a;

Outputmisra027.h(3):External object should not be declared in more than one file.Informational: MISRA Guidelines item 27Symbol `int a' is also declared in: misra027_2.c:3

97

Built-in MISRA Guidelines

MISRA-29The use of a tag shall agree with its declaration.This rule will report violation when tag initializers do not agree with the structure declared for that tag. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra029.c */

struct tagSTRUCT { int _x; };

/* OK - initialiser of type int matches type of field _x: */ struct tagSTRUCT s = { 123 };

/* violation - 'char *' initialiser does not match type of field _x: */ struct tagSTRUCT t = { "abc" };

Outputmisra029.c(12):The use of a tag shall agree with its declaration.Violation: MISRA Guidelines item 29Usage of tag STRUCT does not agree with the declaration.

98

Built-in MISRA Guidelines

MISRA-34The operands of a logical && or || shall be primary expressions.This rule requires that only primary expressions appear as operands of logical && and || operators. Effectively, the rule requires that if an operand is other than a single identifier or constant or string lit-eral, then it must be parenthesized. Complying with this rule both improves readability of code and ensures that the code behaves as intended. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra034.c */

int bar();

enum E { AA, BB, CC };

void foo(int i, int j) { if (i == 1 && (j == 2)) { /* violation */ }

if (i == 1 || j == 2 || j == 3) { /* 2 violations */ } if (i == 1 && j == 2 || j == 3) { /* 2 violations */ }

if (12 || i || "abc" || (i + j)) { /* OK */ }

if (bar() && (j == 1)) { /* violation */ } if ((bar()) && (j == 1)) { /* OK */ }

if (i && j) { /* OK */ }

if (i << 2 || j >> 3) { /* violation */ }

while (i != AA || j != BB) { /* violation */ i = AA; }

j = i == AA || j==i; /* violation */ }

99

Built-in MISRA Guidelines

Outputmisra034.c(10):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34The left operand of logical operator AND is not a primary expression.

misra034.c(13):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34The right operand of logical operator OR is not a primary expression.

misra034.c(13):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34Operands of logical operator OR are not primary expressions.

misra034.c(15):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34The right operand of logical operator OR is not a primary expression.

misra034.c(15):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34Operands of logical operator AND are not primary expressions.

misra034.c(21):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34The left operand of logical operator AND is not a primary expression.

misra034.c(30):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34Operands of logical operator OR are not primary expressions.

misra034.c(33):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34Operands of logical operator OR are not primary expressions.

misra034.c(37):The operands of a logical && or || shall be primary expressions.Violation: MISRA Guidelines item 34Operands of logical operator OR are not primary expressions.

100

Built-in MISRA Guidelines

MISRA-47No dependence should be placed on C's operator precedence rules in expressions.This rule encourages to use parentheses not only to override the default operator precedence, but also to emphasize it. Complying with this rule both improves readability of code and ensures that the code behaves as intended. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra047.c */

void foo(int i, int j) { int a, b, c, d, x; a = b = c = d = x = 1;

x = (3 * a) + (b / c); /* OK */ x = 3 * a + b / c; /* violation */

x = a + b - c + d; /* OK */ x = ((a + b) - c) + d; /* OK */ x = a + b - (c + d); /* OK */ x = (a + b) - (c + d); /* OK */

x = a + b, c * d; /* OK */ x = 3 * a & b / c; /* violation */ x = 3 % a >> b + c; /* violation */ x = 3 ^ a | b >= c; /* violation */

x = 3 ^ a || b >= c && d >> 1; /* 2 violations */

x = (3 ^ a) || (b >= c) && d >> 1; /* 2 violations */ x = (3 ^ a) && (b >= c) || d >> 1; /* violation */ x = ((3 ^ a) && (b >= c)) || d >> 1; /* violation */ x = ((3 ^ a) || (b >= c)) && d >> 1; /* violation */ }

void bar(int i, char **arr) { if (i > 1 && arr[1][0] == '-') { /* violation */ } }

101

Built-in MISRA Guidelines

Outputmisra047.c(9):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of addition operator (+).

misra047.c(17):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of bitwise AND operator (&).

misra047.c(18):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of right shift operator (<<).

misra047.c(19):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of bitwise OR operator (|).

misra047.c(21):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical OR operator (||).

misra047.c(21):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical AND operator (&&).

misra047.c(23):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical OR operator (||).

misra047.c(23):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical AND operator (&&).

102

Built-in MISRA Guidelines

misra047.c(24):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical OR operator (||).

misra047.c(25):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical OR operator (||).

misra047.c(26):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical AND operator (&&).

misra047.c(31):Do not depend on C's operator precedence.Informational: MISRA Guidelines item 47Emphasize precedence by using parentheses around operand(s) of logical AND operator (&&).

MISRA-53All non-null statements shall have a side-effect.As defined by ISO/IEC 9899:1999 standard, a side effect is defined as: "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 is, according to the standard, a statement "consisting of just a semicolon." This rule will report a violation message each time a non-null statement (i.e. statement consisting of just a semi-colon) is detected with no side-effects. 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 acciden-tally wrote "==" instead of "=", the statement is considered not to have a side effect. Such program-ming errors are potentially disastrous.

This rule will also report violation if an empty block statement is detected, since such a statement has no effect. 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 func-tion call. Note: This rule is implemented as a built-in rule and it is active for C code only.

103

Built-in MISRA Guidelines

Example /* misra053.c */

struct tagStruct { int _iField; char * _p; };

volatile struct tagStruct _SSS;

int bar();

void foo() { int i = 0; volatile int j = 0; struct tagStruct s, *ps;

/* with side effects: */ i = i + 3; /* OK - assignment */ i <<= 3; /* OK - assignment */ bar(); /* OK - function call */ j; /* OK - volatile variable */ _SSS._p; /* OK - volatile variable */

/* no side effects: */ i + 3; /* violation - result not used */ 3; /* violation - result not used */ i; /* violation - result not used */ i + bar(); /* violation - result not used */ switch (i) { } /* violation - empty block - no side-effect */ ps->_p + s._iField; /* violation - result not used */ ps->_iField << s._iField; /* violation - result not used */ *(ps->_p); /* violation - result not used */

/* null statement - OK */ ;

{ /* violation - empty block - no side-effect */ }

} /* foo() */

Outputmisra053.c(27):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53Statement with no side-effects detected.

104

Built-in MISRA Guidelines

misra053.c(28):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53Statement with no side-effects detected.

misra053.c(29):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53Statement with no side-effects detected.

misra053.c(30):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53Statement with no side-effects detected.

misra053.c(31):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53An empty block statement has no side-effect.

misra053.c(32):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53Statement with no side-effects detected.

misra053.c(33):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53Statement with no side-effects detected.

misra053.c(34):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53Statement with no side-effects detected.

misra053.c(39):All non-null statements shall have a side-effect.Violation: MISRA Guidelines item 53An empty block statement has no side-effect.

105

Built-in MISRA Guidelines

MISRA-66Only expressions concerned with loop control should appear within for statement.This rule analyzes for statements to find any variables that are used within initialization or update sec-tions of the statements, but do not seem to be concerned with loop control. Often, variables are initial-ized 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. Complying with this rule leads to safer and more readable code. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra066.c */

int bar(int i);

void foo() { int i, j, k, l;

i = j = k = l = 0;

for (i = 0; i < 10; ++ i) { /* OK */ }

for (i = 0; i < 10; ++ i, ++j) { /* violation - j */ } for (i = 0, j = 1; i < 10; ++ i) { /* violation - j */ } for (i = 0, j = 1; i < 10; ++ i, ++ j) { /* violation - j */ } for (i = 0, j = 1; i+j < 10; ++ i, ++ j) { /* OK */ }

for (i = 0; i < 10; ++ i, bar(j)) { /* violation - j */ }

for (i = 0; i < 10; ++ i, bar(j), ++k, l >> 1) { /* violation - j, k, l */ }

for (i = j; i < k; ++ i) { /* OK */ } for (i = j, l = j; i < k; ++ i) { /* violation - l */ } for (i++, l++, j += i; i < k; ++ i) { /* violation - j, l */ } for (bar(j), l + 3; i < k; ++ i) { /* violation - j, l */ } }

106

Built-in MISRA Guidelines

Outputmisra066.c(14):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: j

misra066.c(16):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: j

misra066.c(18):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: j

misra066.c(23):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: j

misra066.c(26):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: j, k, l

misra066.c(31):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: l

misra066.c(33):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: l, j

misra066.c(35):Only expressions concerned with loop control should appear within a for statement.Informational: MISRA Guidelines item 66The following variables do not seem to be concerned with for loop control: j

107

Built-in MISRA Guidelines

MISRA-71Functions 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 its 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. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra071.c */

/* case 1 - both function call and definition have visible prototype */ void case1foo(void); /* prototype */ void case1goo(void); /* prototype */ void case1goo() { /* OK */ case1foo(); /* OK */ }

/* case 2 - definition without prototype */ void case2goo() { /* violation */ }

/* case 3 - call without prototype */ void case3goo(void); void case3goo(void) { case3foo(); /* violation */ }

/* case 4 - definition without prototype although function declared */ void case4goo(); /* this is not a prototype (no arguments declared) */ void case4goo() { /* violation */ }

/* case 5 - call without prototype although function declared */ void case5foo(); void case5goo(void); void case5goo() { case5foo(); /* violation */ }

/* case 6 - definition w prototype declared after function definition */ void case6goo() { /* violation */ } void case6goo(void);

108

Built-in MISRA Guidelines

/* case 7 - call with prototype declared after function call */ void case7goo(void); void case7goo(void) { case7foo(); /* violation */ } void case7foo(void);

Outputmisra071.c(13):Functions shall always have visible prototype at both the function defini-tion and callViolation: MISRA Guidelines item 71Function case2goo has no visible prototype at the point of definition

misra071.c(20):Functions shall always have visible prototype at both the function defini-tion and callViolation: MISRA Guidelines item 71Function case3foo has no visible prototype at the point of call

misra071.c(26):Functions shall always have visible prototype at both the function defini-tion and callViolation: MISRA Guidelines item 71Function case4goo has no visible prototype at the point of definition

misra071.c(34):Functions shall always have visible prototype at both the function defini-tion and callViolation: MISRA Guidelines item 71Function case5foo has no visible prototype at the point of call

misra071.c(39):Functions shall always have visible prototype at both the function defini-tion and callViolation: MISRA Guidelines item 71Function case6goo has no visible prototype at the point of definition

misra071.c(47):Functions shall always have visible prototype at both the function defini-tion and callViolation: MISRA Guidelines item 71Function case7foo has no visible prototype at the point of call

109

Built-in MISRA Guidelines

MISRA-77The type of parameters passed to a function should be compatible with expected types defined in prototype.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 77 requires that types of arguments passed to a function match the types from the prototype, ignoring any const or volatile qualifiers. The exam-ple below illustrates cases verified by this rule. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra077.c */

/* case 1 - correct - unqualified types from prototype and call match */ void case1ifoo(const int, volatile int, const volatile int, int); void case1goo(void); void case1goo() { int i = 10; const int ci = 20; volatile int vi = 20; const volatile int cvi = 20; case1ifoo(10, 10, 10, 10); /* OK */ case1ifoo(i, i, i, i); /* OK */ case1ifoo(ci, ci, ci, ci); /* OK */ case1ifoo(vi, vi, vi, vi); /* OK */ case1ifoo(cvi, cvi, cvi, cvi); /* OK */ }

/* case 2 - unqualified types from prototype and call do not match */ void case2ifoo(const int, volatile int, const volatile int, int); void case2goo(void); void case2goo() { float f = 10; const float cf = 20; volatile float vf = 20; const volatile float cvf = 20; case2ifoo('a', 10., 0.1, "text"); /* 4 violations */ case2ifoo(f, cf, vf, cvf); /* 4 violations */ }

110

Built-in MISRA Guidelines

/* case 3 - a case with elipsis */ void case3ifoo(int, ...); void case3goo(void); void case3goo() { case3ifoo(10, 10); /* OK */ case3ifoo(10.1, 11); /* violation */ case3ifoo(10, 10.1); /* OK */ case3ifoo(10, 10, 10); /* OK */ case3ifoo(10); /* OK */ }

/* case 4 - a case with void */ void case4foo(void); void case4goo(void); void case4goo(void) { case4foo(); /* OK */ case4foo(10); /* OK */ }

/* case 5 - a case with structs */ typedef struct _AAA { int i; int j; } AAA; typedef struct _BBB { float f; float g; } BBB;

void case5Afoo(AAA); void case5Bfoo(BBB); void case5goo(void); void case5goo() { AAA a; const AAA ca; volatile AAA va; const volatile AAA cva; case5Afoo(a); /* OK */ case5Afoo(ca); /* OK */ case5Afoo(va); /* OK */ case5Afoo(cva); /* OK */ case5Bfoo(a); /* violation */ case5Bfoo(ca); /* violation */ case5Bfoo(va); /* violation */ case5Bfoo(cva); /* violation */ case5Afoo(10); /* violation */ }

111

Built-in MISRA Guidelines

Outputmisra077.c(32):The type of parameters passed to a function should be compatible with the expected types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 1Passed parameter type: charExpected parameter type: const int

misra077.c(32):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 2Passed parameter type: doubleExpected parameter type: volatile int

misra077.c(32):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 3Passed parameter type: doubleExpected parameter type: const volatile int

misra077.c(32):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 4

misra077.c(33):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 1Passed parameter type: floatExpected parameter type: const int

misra077.c(33):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 2Passed parameter type: const floatExpected parameter type: volatile int

112

Built-in MISRA Guidelines

misra077.c(33):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 3Passed parameter type: volatile floatExpected parameter type: const volatile int

misra077.c(33):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case2ifooParameter number: 4Passed parameter type: const volatile floatExpected parameter type: int

misra077.c(42):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case3ifooParameter number: 1Passed parameter type: doubleExpected parameter type: int

misra077.c(81):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case5BfooParameter number: 1Passed parameter type: _AAAExpected parameter type: _BBB

misra077.c(82):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case5BfooParameter number: 1Passed parameter type: _AAAExpected parameter type: _BBB

113

Built-in MISRA Guidelines

misra077.c(83):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case5BfooParameter number: 1Passed parameter type: _AAAExpected parameter type: _BBB

misra077.c(84):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case5BfooParameter number: 1Passed parameter type: _AAAExpected parameter type: _BBB

misra077.c(85):The type of parameters passed to a function should be compatible with expected the types defined in the prototypeViolation: MISRA Guidelines item 77Inconsistent parameter type during calling function: case5AfooParameter number: 1Passed parameter type: intExpected parameter type: _AAA

MISRA-78The type of parameters passed to a function should be compatible with expected types defined in prototype.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 78 requires that the number of arguments passed to a function match the number declared in the prototype. The example below illustrates various cases verified by this rule. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example

/* misra078.c */

void iiifoo(int, int, int); void iiefoo(int, int, ...); void vfoo(void);

void goo() { iiifoo(6, 6); /* violation */

iiifoo(6, 6, 6); /* OK */

iiifoo(6, 6, 6, 6); /* violation */

114

Built-in MISRA Guidelines

iiefoo(6, 6); /* violation */

iiefoo(6, 6, 6); /* OK */

iiefoo(6, 6, 6, 6); /* OK */

vfoo(); /* OK */

vfoo(7); /* violation */ }

Outputmisra078.c(9):The number of parameters passed to a function shall match the function pro-totypeViolation: MISRA Guidelines item 78Inconsistent number of parameters during calling function: iiifooPassed parameters count: 2Expected parameters count: 3

misra078.c(13):The number of parameters passed to a function shall match the function pro-totypeViolation: MISRA Guidelines item 78Inconsistent number of parameters during calling function: iiifooPassed parameters count: 4Expected parameters count: 3

misra078.c(15):The number of parameters passed to a function shall match the function pro-totypeViolation: MISRA Guidelines item 78Inconsistent number of parameters during calling function: iiefooPassed parameters count: 2Expected parameters count: 3+

misra078.c(23):The number of parameters passed to a function shall match the function pro-totypeViolation: MISRA Guidelines item 78Inconsistent number of parameters during calling function: vfooPassed parameters count: 1Expected parameters count: 0

115

Built-in MISRA Guidelines

MISRA-94A function-like macro shall not be 'called' without all of its arguments.If one or more arguments to the function-like macro are not supplied when it is called, then the behavior is undefined. Many pre-processors will issue an error, but in some cases no error is reported, which can lead to hard-to-detect errors at runtime. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra094.c */

#define MACRO1(x) x = 1 #define MACRO2(x, y) x = y = 1 #define MACRO3(x, y, z) x = y = z = 1

void violation(void) { int i; MACRO1(i); /* OK */ MACRO2(i); /* violation */ MACRO3(i, i, i); /* OK */ }

Outputmisra094.c(12):A function-like macro shall not be 'called' without all of its arguments.Violation: MISRA Guidelines item 94Function-like macro MACRO2 used without all of its arguments.

116

Built-in MISRA Guidelines

MISRA-95Arguments to a function-like macro shall not contain tokens that look like pre-processing directives.If any of the arguments to the function-like macro look like pre-processor directives, the behavior when macro substitution is made can be unpredictable. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra095.c */

#define MACRO1(x) #define MACRO2(x, y)

void violation(void) { int i = 0; MACRO1(i); /* OK */ MACRO1(#foo); /* violation */ MACRO2(i, i); /* OK */ MACRO2(i, #foo); /* violation */ MACRO2(i, "#foo"); /* violation */ }

Outputmisra095.c(11):Arguments to a function-like macro shall not contain tokens that look like pre-processing directives.Violation: MISRA Guidelines item 95Function-like macro MACRO1 called with argument that looks like pre-process-ing directive.

misra095.c(13):Arguments to a function-like macro shall not contain tokens that look like pre-processing directives.Violation: MISRA Guidelines item 95Function-like macro MACRO2 called with argument that looks like pre-process-ing directive.

misra095.c(14):Arguments to a function-like macro shall not contain tokens that look like pre-processing directives.Violation: MISRA Guidelines item 95Function-like macro MACRO2 called with argument that looks like pre-process-ing directive.

117

Built-in MISRA Guidelines

MISRA-97Identifiers in pre-processor directives should be defined before use.This rule requires that all identifiers used in pre-processor directives are defined. Otherwise the prepro-cessor will often silently assume a value of zero for that identifier without issuing any warnings, which can often lead to hard-to-detect errors. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra097.c */

#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

#define X 1

#if X /* OK */ #endif

#ifdef Y #if Y /* OK - check is done in the #ifdef above */ #endif #endif

Outputmisra097.c(3):Identifiers in pre-processor directives should be defined before use.Informational: MISRA Guidelines item 97Identifier X is undefined at this point.

misra097.c(7):Identifiers in pre-processor directives should be defined before use.Informational: MISRA Guidelines item 97Identifier Y is undefined at this point.

misra097.c(11):Identifiers in pre-processor directives should be defined before use.Informational: MISRA Guidelines item 97Identifier X is undefined at this point.

118

Built-in MISRA Guidelines

misra097.c(11):Identifiers in pre-processor directives should be defined before use.Informational: MISRA Guidelines item 97Identifier Y is undefined at this point.

MISRA-105All the functions pointed to by a single pointer to function shall be identical in the number and type of parameters and the return type.Pointers to functions can easily violate type integrity, so all pointed-to functions should be of identical type. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra105.c */

typedef int(*PTF)(int, char*); typedef void(*PTF2)(void);

int foo(int i, char* c){ return 0;}

void bar(void) { }

void test(void) { PTF p; void *purePtr = 0; char *charPtr = 0; PTF2 q = bar; /* OK */ PTF arrOK[] = { foo, &foo }; /* OK */ PTF arrV[] = { foo, (PTF)&bar }; /* violation */

p = &foo; /* OK */ p = (PTF) bar; /* violation */

p = (PTF) q; /* violation */

p = purePtr; /* violation */ p = (PTF) purePtr; /* OK */

p = (PTF)charPtr; /* violation */ }

119

Built-in MISRA Guidelines

Outputmisra105.c(19):All the functions pointed to by a single pointer to function shall be iden-tical in the number and type of parameters and the return type.Violation: MISRA Guidelines item 105Type of assignee doesn't match type of expression being assigned.

misra105.c(22):All the functions pointed to by a single pointer to function shall be iden-tical in the number and type of parameters and the return type.Violation: MISRA Guidelines item 105Type of assignee doesn't match type of expression being assigned.

misra105.c(24):All the functions pointed to by a single pointer to function shall be iden-tical in the number and type of parameters and the return type.Violation: MISRA Guidelines item 105Type of assignee doesn't match type of expression being assigned.

misra105.c(26):All the functions pointed to by a single pointer to function shall be iden-tical in the number and type of parameters and the return type.Violation: MISRA Guidelines item 105Type of assignee doesn't match type of expression being assigned.

misra105.c(29):All the functions pointed to by a single pointer to function shall be iden-tical in the number and type of parameters and the return type.Violation: MISRA Guidelines item 105Type of assignee doesn't match type of expression being assigned.

120

Built-in MISRA Guidelines

MISRA-112Avoid using bit fields of type signed int which are less than two bits long.This rule enforces that all fields of type 'signed int' are at least 2 bits 'long'. Note that the rule does not trigger for plain 'int' bit fields, because it is assumed that the code also complies with MISRA rule 111. The MISRA rule 111 considers it a violation not to explicitly specify whether bit field is signed or unsigned. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra112.c */

typedef signed int SINT; typedef SINT SINT2;

struct Misra112 { signed int si01:1; /* violation */ signed int si02:2; signed int si03:3; SINT si11:1; /* violation */ SINT si12:2; SINT si13:3; SINT2 si21:1; /* violation */ SINT2 si22:2; SINT2 si23:3; int i1:1; int i2:2; int i3:3; unsigned int ui1:1; unsigned int ui2:2; unsigned int ui3:3; }; typedef union { struct Nested { signed int nsi01:1; /* violation */ signed int nsi02:2; } nested; signed int usi01:1; /* violation */ signed int usi02:2; } Misra112;

void foo() { struct Internal { signed int Isi01:2; signed int Isi02:1; /* violation */ }; }

121

Built-in MISRA Guidelines

Outputmisra112.c(7):Avoid using bit fields of type signed int which are less than two bits longViolation: MISRA Guidelines item 112si01 is declared as variable which type is signed int and has bits size: 1

misra112.c(10):Avoid using bit fields of type signed int which are less than two bits longViolation: MISRA Guidelines item 112si11 is declared as variable which type is signed int and has bits size: 1

misra112.c(13):Avoid using bit fields of type signed int which are less than two bits longViolation: MISRA Guidelines item 112si21 is declared as variable which type is signed int and has bits size: 1

misra112.c(26):Avoid using bit fields of type signed int which are less than two bits longViolation: MISRA Guidelines item 112nsi01 is declared as variable which type is signed int and has bits size: 1

misra112.c(30):Avoid using bit fields of type signed int which are less than two bits longViolation: MISRA Guidelines item 112usi01 is declared as variable which type is signed int and has bits size: 1

misra112.c(37):Avoid using bit fields of type signed int which are less than two bits longViolation: MISRA Guidelines item 112Isi02 is declared as variable which type is signed int and has bits size: 1

122

Built-in MISRA Guidelines

MISRA-115Standard library function names shall not be reused.This rule requires that any new versions of standard functions are given names different than the origi-nal functions. This is to avoid confusion as to whether a standard library function is being used or whether a modified version of that function is being used.

This rule will report violation for the redefinition of functions listed in Annex B of the ISO/IEC 9899:1999 standard. It will also report any function definitions whose names conflict with any of function macros defined in the standard (see the example below). Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra115.c */

double sqrt(double); /* OK - just declared */

double sqrt(double arg) /* violation - redefined */ { return (arg); }

void strpbrk(double arg) { } /* violation - redefined */

/* macro redefined as function */ void offsetof(double arg) { } /* violation - std. macro name */

void foo() /* OK - user function */ { sqrt(123.0); /* OK - std. C function call */ }

Output[misra115.c][line:6] Standard library function names shall not be reused.Violation: MISRA Guidelines item 115Detected redefinition of standard C library function sqrt.

[misra115.c][line:11] Standard library function names shall not be reused.Violation: MISRA Guidelines item 115Detected redefinition of standard C library function strpbrk.

[misra115.c][line:14] Standard library function names shall not be reused.Violation: MISRA Guidelines item 115Detected redefinition of standard C library function offsetof.

123

Built-in MISRA Guidelines

MISRA-117The validity of values passed to library functions shall be checked.Since many of the standard C library functions are not required to check the validity of parameters passed to them. Even where checking is required by the standard, there is no guarantee that ade-quate checking will take place. Therefore the programmer shall provide appropriate checks of input values.

Implementation of this rule will search function body prior to the library function call to see if its argu-ments are used within conditional statement conditions, or passed to any functions. Such use will be considered as argument validation necessary to comply with this rule. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra117.c */

void* memcpy(void *, void*, int n);

void test(void *v) { }

int getSomeIntValue() { return 0; }

void foo() { void *p, *q; int n; memcpy(p, q, n); /* Violation - complain about p, q and n */ test(q); /* consider it a validation of q */ memcpy(p, q, n); /* Violation - complain about p, and n */ switch (n) { /* consider it a validation of n */ case 0: break; } if (p == 0) { /* consider it a validation of p */ }

memcpy(p, q, n); /* OK */ /* Violation - complain only about getSomeIntValue call */ memcpy(p, q, getSomeIntValue()); }

124

Built-in MISRA Guidelines

Outputmisra117.c(17):The validity of values passed to library functions shall be checked.Violation: MISRA Guidelines item 117Value p passed to library function without being checked.

misra117.c(17):The validity of values passed to library functions shall be checked.Violation: MISRA Guidelines item 117Value q passed to library function without being checked.

misra117.c(17):The validity of values passed to library functions shall be checked.Violation: MISRA Guidelines item 117Value n passed to library function without being checked.

misra117.c(34):The validity of values passed to library functions shall be checked.Violation: MISRA Guidelines item 117Result of getSomeIntValue passed to library function without being checked.

MISRA-118Dynamic heap memory allocation shall not be used.The rule will verify if any of the following standard C functions are used: malloc, realloc, calloc, free. In a call to any of these functions is detected, CodeWizard will report this as a violation. Note: This rule is implemented as a built-in rule and it is active for C code only.

Example /* misra118.c */

#include <stdlib.h>

int main() { char * p = 0;

p = (char *) malloc(128); /* violation */ p = (char *) realloc(p, 256); /* violation */

free(p); /* violation */ p = 0;

p = (char *) calloc(128, 1); /* violation */ free(p); /* violation */ return (0); }

125

Built-in MISRA Guidelines

Outputmisra118.c(9):Dynamic heap memory allocation shall not be used.Violation: MISRA Guidelines item 118Detected use of dynamic memory allocation function: malloc.

misra118.c(10):Dynamic heap memory allocation shall not be used.Violation: MISRA Guidelines item 118Detected use of dynamic memory allocation function: realloc.

misra118.c(12):Dynamic heap memory allocation shall not be used.Violation: MISRA Guidelines item 118Detected use of dynamic memory allocation function: free.

misra118.c(16):Dynamic heap memory allocation shall not be used.Violation: MISRA Guidelines item 118Detected use of dynamic memory allocation function: calloc.

misra118.c(17):Dynamic heap memory allocation shall not be used.Violation: MISRA Guidelines item 118Detected use of dynamic memory allocation function: free.

126

Built-in MISRA Guidelines

A Note On Additional MISRA RulesThe following MISRA rules are not supported by CodeWizard, because they are not statically enforce-able. However, for completeness, they are documented in order to provide basic information about MISRA guidelines of which you should be aware.

MISRA-2Code written in languages other than C should only be used if there is a defined interface standard for object code to which the compilers-assemblers for both languages conform. Note: This rule is not stat-ically enforceable and thus is not implemented in CodeWizard.

MISRA-15Floating point implementations should comply with a defined floating point standard. Note: This rule is not statically enforceable and thus is not implemented in CodeWizard.

MISRA-116 All libraries used in production code shall be written to comply with the provisions of MISRA Guidelines document, and shall have been subject to appropriate validation. Note: This rule is not statically enforceable and thus is not implemented in CodeWizard.

CodeWizard's cwmfs UtilitySome of the MISRA rules implemented by CodeWizard require information from multiple compilation units. Normally, CodeWizard works on single compilation units; therefore, it was necessary to add a new commandline utility to CodeWizard to support analysis of multiple compilation units. This new functionality is used only for checking the new MISRA-25, MISRA-26 and MISRA-27 built-in rules on C code only.

Enforcing MISRA-25, MISRA-26 and MISRA-37To enforce these rules, the first thing that needs to be done is to collect symbol information from compi-lation units. This is done by using the CodeWizard command line tool cwmfs. Information collected is stored in .cwinfo files (symbol files), one symbol file per compilation unit.Symbol information can be collected in two ways:

1. As a "by-product" of standard analysis, in which case violations are reported if found in the compilation units being analyzed. To instruct CodeWizard to create symbol files, pass the -ZdoMfs option to the tool, along with other necessary options. For example, CodeWizard is normally invoked like this:

codewizard -DSOME_FLAG -I some/include/dir source.c

However, in order to create symbol files the -ZdoMfs option should be passed as well:

codewizard -ZdoMfs -DSOME_FLAG -I some/include/dir source.c

The source.c will be analyzed as usual, and any violations found will be reported. Also, a file .source.cwinfo will be created in the current directory. Note that the symbol file name is based on the name of the original source file.

2. CodeWizard can be run specifically to create symbol files, without reporting any violations. A special -ZskipSfs option will prevent CodeWizard from performing analysis on a single com-pilation unit. This option must be paired with the -ZdoMfs option described above, so that

127

Built-in MISRA Guidelines

CodeWizard collects the symbol information in data files. For example, normally CodeWizard is invoked like this:

codewizard -DSOME_FLAG source1.c source2.c

In order to skip static analysis and only create symbol files the -ZdoMfs and -ZskifSfs options should be passed as well:

codewizard -ZdoMfs -ZskipSfs -DSOME_FLAG source1.c source2.c

The files source1.c and source2.c will not be checked for rule violations reported. Instead, the two files .source1.cwinfo and .source2.cwinfo will be created in the current directory. Note that the symbol file names are based on the names of original source files.

Once created, symbol files can be analyzed by the new cwmfs tool bundled with CodeWizard installa-tion. In order to enforce MISRA rules 25, 26 and 27, the appropriate symbol files should be passed to the tool.

Examples of cwmfs UseFor example, assume that we have three source files: src1.c, src2.c and src3.c and that we want to check their conformance to MISRA rules 25, 26 and 27.

1. First, we create symbol files:

codewizard <COMPILER OPTIONS> -ZdoMfs -ZskipSfs src1.c src2.c src3.c

2. Now, once these symbols files are created, run the cwmfs tool to check the rules:

cwmfs .src1.cwinfo .src2.cwinfo .src3.cwinfo

The cwmfs tool will not analyze symbol information from the data files, and report MISRA rule 25, 26 and 27 violations, if any were detected.

Having to replace all .c file names with appropriate symbol file names in cwmfs command line may not be very convenient. Therefore, instead of passing symbol file names to the cwmfs tool, one can simply pass source file names like this:

cwmfs src1.c src2.c src3.c

and the cwmfs tool will try to deduce symbol file names based on source names passed on the com-mand line, by pre-pending the source file name with a dot ('.') and by replacing its file extension with cwinfo.

128

Built-in MISRA Guidelines

CodeWizard Options Related To Multiple Compilation Unit AnalysisThe following options are recognized by the CodeWizard command line program:

The following options are also recognized by the cwmfs command line program:

Any other options will be ignored by the cwmfs tool. It is therefore possible to use the same command line for both CodeWizard and cwmfs.

Option Description

-ZdoMfs Instructs CodeWizard to collect symbol information from source files specified at the command line, and creates (or updates existing) symbol files for every source file specified. Standard single compilation unit analysis will proceed as normal unless the -ZskipSfs option was also specified to disable the analysis.

-ZskipSfs Used, in addition to the -ZdoMfs option described above, to disable the standard single compilation unit analysis. This can be useful when CodeWizard is run solely to create sym-bol data files.

-Zomfs "symbol_file_name" Used, in addition to the -ZdoMfs option described above, to tell CodeWizard to use specified file name when creating symbol data file. Cannot be used when multiple source files are specified at the command line.

Option Description

[file] [...] The cwmfs tool expects symbol file names and/or corresponding source file names passed at the command line.

-ZignoreMissing If the source file name is passed to the tool, for which there is no corre-sponding symbol file present, the cwmfs tool will issue an error message and will not proceed with analysis. This option instructs the tool to ignore any source files for which there is no data file present, and proceed with analysis.

129

Meyers-Klaus Items

Meyers-Klaus ItemsMeyers-Klaus Items

Item MK-13Avoid calling virtual functions from constructors and destructorsThis rule detects when you call virtual functions from constructors and destructors. These errors are reported as violations of Item MK-13.

Example//// Meyers-Klaus Item 13//

class Base{public: Base() { init(); } // MK item 13 violation virtual ~Base();

protected: virtual void init(); int _i;};

void Base::init(){ _i = 10;}

class Derived : public Base{public: Derived() { init(); } // MK item 13 violation ~Derived();

private: void init();};

Category Item Description Violation Enabled?

Constructors/ Destructors/ Assignment

13 Avoid calling virtual functions from con-structors and destructors

SV Y

Implementation 23 Avoid using “...” in function parameter lists

I N

130

Meyers-Klaus Items

void Derived::init(){ _i = 20;}

int main(){ return 0;}

Output[MK-item13.C:8] Avoid calling virtual functions fromconstructors and destructorsSevere violation: Meyers-Klaus item 13Virtual function init called.

[MK-item13.C:25] Avoid calling virtual functions fromconstructors and destructorsSevere violation: Meyers-Klaus item 13Virtual function init called.

131

Meyers-Klaus Items

Item MK-23Avoid using “...” in function parameter listsThis rule detects when you use “...” in function parameter lists. These errors are reported as violations of Item MK-23.

Note: This item is suppressed by default.

Example//// Meyers-Klaus Item 23//

class A{public: A() { init(); } virtual ~A();

private: void init(...); int _i;};

void A::init(...){ _i = 10;}

int main(){ return 0;}

Output[MK-item23.C:17] Avoid using "..." in functionparameter listInformational: Meyers-Klaus item 23

132

Universal Coding Standard Items

Universal Coding Standard Items

Universal Coding Standard ItemsItem Description Violation Enabled?

2 Do not declare protected data members. V N

3 Do not declare the constructor or destructor to be inline. V N

4 Declare at least one constructor to prevent the compiler from doing so.

V N

5 Pointers to functions should use a typedef. V N

6 Never convert a const to a non-const. SV Y

7 Do not use the ?: operator. V N

8 Each class must declare the public, protected, and private sec-tions in that order.

V N

9 In the public section, entities shall be declared in the following order: Constructors, Destructors, Member functions, Member conversion functions, Enumerations, and other.

V N

10 In the protected section entities shall be declared in the following order: Constructors, Destructors, Member functions, Member conversion functions, Enumeration, and others.

V N

11 In the private section entities shall be declared in the following order: Constructors, Destructors, Member functions, Member conversion functions, Enumerations, and others.

V N

12 If a function has no parameters, use () instead of (void). V N

13 If, else, while, and do statements shall be followed by a block, even if it is empty.

V N

14 If a block is a single statement, enclose it in braces. V N

15 Whenever a global variable or function is used, use the :: opera-tor.

I N

16 Do not use public data members. V N

17 If a class has any virtual functions it shall have a virtual destruc-tor.

SV Y

18 Public member functions shall return const handles to member data.

SV Y

19 A class that has pointer members shall have an operator= and a copy constructor.

V N

20 If a subclass implements a virtual function, use the virtual key-word.

V N

21 Member functions shall not be defined in the class definition. V N

133

Universal Coding Standard Items

22 Ellipses shall not be used. V N

23 Functions shall explicitly declare their return types. V N

24 A pointer to a class shall not be converted to a pointer of a sec-ond class unless it inherits from the second.

SV Y

25 A pointer to an abstract class shall not be converted to a pointer that inherits from that class.

SV Y

26 Do not use the friend mechanism. V N

27 When working with float or double values, use <= and >= instead of ==.

SV Y

28 Do not overload functions within a template class. SV Y

29 Do not define structs that contain member functions. V N

30 Do not directly access global data from a constructor. SV Y

31 Do not use multiple inheritance. V N

32 Initialize all variables. V N

33 All pointers should be initialized to zero or to a legitimate address. V N

34 Always terminate a case statement with break. V N

35 Always provide a default branch for switch statements. V N

36 Do not use the goto statement. V N

37 Provide only one return statement in a function. I N

134

Universal Coding Standard Items

Item ucs-2Do not declare protected data membersDeclaring protected variables in a class results in the variables becoming visible to derived classes. This rule detects if you declare protected data members. These errors are reported as violations of Item ucs-02.

Reason for rule: When you declare data members protected instead of private, you expose members to derived classes that could be encapsulated in member functions.

Note: This item is suppressed by default.

Example/* * UCS item 02 - Do not declare protected data members */class A{protected:

int i; // UCS02 Violation};

Output[ucs02.C:6] Do not use protected data membersViolation: Universal Coding Standards item 2Class A declares the following protected data members: i

135

Universal Coding Standard Items

Item ucs-3Do not declare the constructor or destructor to be inlineInline functions that invoke other inline functions can be too complex for the compiler to make them inline. Because constructors always invoke the constructors of their base classes and member data, this rule reports use of inline constructors and destructors as violations of Item ucs-03.

Reason for rule: Portability. Functions that invoke other inline functions often become too complex for the compiler to be able to make them inline, despite the fact that they appear to be small. This problem is especially common with constructors and destructors. A constructor always invokes the constructors of its base classes and member data before executing its own code. If you avoid making constructors and destructors inline, you will make the code more portable to compilers that get confused when gen-erating complex nested inline functions.

Note: This item is suppressed by default.

Example /* * UCS item 03 - Do not declare the constructor or destructor * to be inline */class A{public:

A() {} // UCS03 Violation~A() {} // UCS03 Violation

};

Output[ucs03.C:6] Do not define any constructor to be inlineViolation: Universal Coding Standards item 3Class A defines an inline constructor

136

Universal Coding Standard Items

Item ucs-4Declare at least one constructor to prevent the compiler from doing soIf 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. This error is reported as a violation of Item ucs-04.

Reason for rule: Readability. If you follow this rule, you will make class initialization explicit and pre-vent the compiler from initializing members improperly, especially pointer members.

Note: This item is suppressed by default.

Example /* * UCS item 04 - Declare at least one constructor to * prevent the compiler from doing so */class A{}; // UCS04 Violation

Output[ucs04.C:7] Declare at least one constructor to prevent the compiler from doing soViolation: Universal Coding Standards item 4Class A does not define any constructors

Item ucs-5Pointers to functions should use a typedefThis rule detects when pointers to functions do not use a typedef. Using a typedef when writing pointers to functions results in more readable code that is easier to maintain and port. These errors are reported as violations of Item ucs-05.

Reason for rule: When you use a typedef, you provide greater readability for function pointers.

Note: This item is suppressed by default.

Example/* * UCS item 05 -Pointers to functions should use a typedef */void (*foo) (int); // UCS05 Violation

Output[ucs05.C:7] Pointers to functions shall be implemented with a typedefViolation: Universal Coding Standards item 5

137

Universal Coding Standard Items

Item ucs-6Never convert a const to a non-constUsing explicit type conversions to convert const member data to non-const will prevent the com-piler from allocating constants in ROM. This rule detects if you convert a const to a non-const. These errors are reported as violations of Item ucs-06.

Reason for rule: Converting const to non-const can undermine the data integrity by allowing val-ues to change that are assumed to be constant. This practice also reduces the readability of the code, since you cannot assume const variables to be constant.

Example/* * UCS item 06 - Never convert a const to a non-const */int main(){

const int a = 10;int b;

b = (int)a; // UCS06 Violation

return 0;}

Output[ucs06.C:10] Never convert a const to a non-constSevere violation: Universal Coding Standards item 6

Item ucs-7Do not use the ?: operatorThis rule detects if you use the ?: operator. This error is reported as a violation of Item ucs-07.

Reason for rule: The ?: operator is difficult to read and leads to code obfuscation.

Note: This item is suppressed by default.

Example/* * UCS item 07 - Do not use the ?: operator */int main(){

return (1 ? 1 : 0); // UCS07 Violation};

Output[ucs07.C:7] Avoid using the ?: operatorViolation: Universal Coding Standards item 7

138

Universal Coding Standard Items

Item ucs-8Each class must declare the public, protected, and private sections in that orderUsing the above convention, everything of general interest to a user (the public section) is gathered in the beginning of the class definition, with the protected items next, while items of the least general interest (the private section) are gathered last. This rule reports violations of this convention as viola-tions of Item ucs-08. Reason for rule: Readability. Note: This item is suppressed by default.

Example/* * UCS item 08 - Each class must declare the public, * protected, and private sections in that order */class A{public:

A();

private: // UCS08 Violationvoid foo();

protected:void bar();

};

Output[ucs08.C:7] Each class must declare the public, protected, and private sec-tions in that orderViolation: Universal Coding Standards item 8class A declares these sections out of order

139

Universal Coding Standard Items

Item ucs-9In the public section, entities shall be declared in the following order: Constructors, Destructors, Member functions, Member conversion functions, Enumerations, and otherFollowing the above ordering convention makes it easier for those unfamiliar with a class to figure out its functionality. This rule reports violations of this convention as violations of Item ucs-09.

Reason for rule: Readability. Note: This item is suppressed by default.

Example /* * UCS item 09 - In the public section entities shall be * declared in the following order: Constructors, * Destructors, Member functions, Member conversion * functions, Enumerations, and other. */class A{public:

A();int foo(); // UCS09 Violation~A();

};

Output[ucs09.C:9] In the public section of a class items shall be declared in the following order: Constructors, Destructor, Member Functions, Member Opera-tor Function, Enumerations, otherViolation: Universal Coding Standards item 9

140

Universal Coding Standard Items

Item ucs-10In the protected section entities shall be declared in the following order: Constructors, Destructors, Member functions, Member conversion functions, Enumeration, and otherFollowing the above ordering convention makes it easier for those unfamiliar with a class to figure out its functionality. This rule reports violations of this convention as violations of Item ucs-10.

Reason for rule: Readability. Note: This item is suppressed by default.

Example /* * UCS item 10 - In the protected section entities shall * be declared in the following order: Constructors, * Destructors, Member functions, Member conversion * functions, Enumerations, and other. */class A{protected:

A();int foo(); // UCS10 Violation~A();

};

Output[ucs10.C:9] In the protected section of a class items shall be declared in the following order: Constructors, Destructor, Member Functions, Member Operator Function, Enumerations, otherViolation: Universal Coding Standards item 10

141

Universal Coding Standard Items

Item ucs-11In the private section entities shall be declared in the following order: Constructors, Destructors, Member functions, Member conversion functions, Enumerations, and otherFollowing the above ordering convention makes it easier for those unfamiliar with a class to figure out its functionality. This rule reports violations of this convention as violations of Item ucs-11.

Reason for rule: Readability. Note: This item is suppressed by default.

Example /* * UCS item 11 - In the private section entities shall * be declared in the following order: Constructors, * Destructors, Member functions, Member conversion * functions, Enumerations, and other */class A{private:

A();int foo(); // UCS11 Violation~A();

};

Output[ucs11.C:9] In the private section of a class items shall be declared in the following order: Constructors, Destructor, Member Functions, Member Opera-tor Function, Enumerations, otherViolation: Universal Coding Standards item 11

142

Universal Coding Standard Items

Item ucs-12If a function has no parameters, use () instead of (void)This rule detects if you use (void) instead of () if a function has no parameters. Maintaining this con-sistency of declarations results in easier code readability. These errors are reported as violations of Item ucs-12.

Reason for rule: Readability. Note: This item is suppressed by default.

Example/* * UCS item 12 - If a function has no parameters use () * instead of (void) */int foo(void); // UCS12 Violation

Output[ucs12.C:5] If a function has no formal parameters, use () instead of (void)Violation: Universal Coding Standards item 12function foo uses (void).

143

Universal Coding Standard Items

Item ucs-13If, else, while, and do statements shall be followed by a block, even if it is emptyTo avoid confusion when reading a piece of code, you should follow loop statements with an empty block rather than with a semi-colon, which is easy to miss. This rule detects if you do not follow If, else, while, and do statements with a block. These errors are reported as violations of Item ucs-13.

Reasons for rule: Readability and maintainability. This rule also helps to prevent errors such as:

while(1); { // infinite loop do_something();}

Note: This item is suppressed by default. See also Item ucs_14.

Example /* * UCS item 13 - If, else, while, and do statements shall * be followed by a block, even if it is empty */int main(){

if (1) ; // UCS13 Violationreturn 0;

}

Output[ucs13.C:8] If, else, while, and do statements shall be followed by a block, even if it is emptyViolation: Universal Coding Standards item 13

144

Universal Coding Standard Items

Item ucs-14If a block is a single statement, enclose it in bracesTo avoid causing confusion for those reading your code, you should always enclose a single-statement block in braces. This rule can detect if single-statement blocks are not enclosed in braces. These errors are reported as violations of Item ucs-14.

Reasons for rule: Readability and maintainability. If you are maintaining the code and you see this:

if (condition) do_something();

you may be tempted to update it like this:

if (condition) do_preparation(); do_something();

instead of like this:

if (condition) { do_preparation(); do_something();}

If you write the original code like this:

if (condition) { do_something();}

there will be less room for error for the maintainer of the code.

Note: This item is suppressed by default.

Example /* * UCS item 14 - If a block is a single statement, * enclose it in braces */int main(){

if (1) return 1; // UCS14 Violation

}

Output[ucs14.C:7] If a block is a single statement, it shall be enclosed in bracesViolation: Universal Coding Standards item 14

145

Universal Coding Standard Items

Item ucs-15Whenever a global variable or function is used, use the :: operatorThis rule detects if you do not use the :: operator whenever a global variable or function is used. Using the :: operator in these situations will make it easier to determine which variable is being used. These errors are reported as violations of Item ucs-15.

Reasons for rule: Readability and maintainability. Using the :: operator helps the maintainer of code distinguish quickly between global variables and local variables; it also allows more freedom in naming local variables without the chance of clashing with global names.

Note: This item is suppressed by default.

Example /* * UCS item 15 - Whenever a global variable or function is * used, use the :: operator */int a = 10;int main(){

int b = a; // UCS15 Violation}

Output[ucs15.C:9] Whenever a global function or variable is referenced, use the :: operatorInformational: Universal Coding Standards item 15the following globals are referenced without the :: operator: a

146

Universal Coding Standard Items

Item ucs-16Do not use public data membersUsing public variables is contrary to the principle of data encapsulation and can allow the value of the variable to be changed by any user of the class. This rule detects if you use public data members. These errors are reported as violations of Item ucs-16.

Reason for rule: Data hiding. If you follow this rule, you will insulate the class interface from the class implementation. You will also provide consistency for users of the class to access data through mem-ber functions every time. Internally, the class may change which data types are used to store the data without breaking the interface.

Note: This item is suppressed by default.

Example /* * UCS item 16 - Do not use public data members */class A{public:

int a; // UCS16 Violation};

Output[ucs16.C:6] Do not specify public data membersViolation: Universal Coding Standards item 16Class A has the following public data members: a

147

Universal Coding Standard Items

Item ucs-17If a class has any virtual functions it shall have a virtual destructorDeclaring virtual destructors in classes that have virtual functions causes the compiler to call destruc-tors for each class from which the object inherits. This rule detects if you write a virtual function without also writing a virtual destructor. These errors are reported as violations of Item ucs-17.

Reason for rule: 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 /* * UCS item 17 - If a class has any virtual functions * it shall have a virtual destructor */class A // UCS17 Violation{public:

~A();virtual int foo();

};

Output[ucs17.C:7] If a class has virtual functions it shall have a virtual destructorSevere violation: Universal Coding Standards item 17class A has virtual functions without a virtual destructor.

148

Universal Coding Standard Items

Item ucs-18Public member functions shall return const handles to member dataThis rule helps avoid problems that point to deallocated memory. Any public member functions that do not return const handles to member data are reported as violations of Item ucs-18.

Reason for rule: When you provide non-const handles to member data, you undermine encapsula-tion by allowing callers to modify member data outside of member functions.

Example /* * UCS item 18 - Public member functions shall return const * handles to member data */class A{public:

int* foo();

private:int a;

};int* A::foo(){

return &a; // UCS18 Violation}

Output[ucs18.C:17] Public member functions shall always return const handles to member dataSevere violation: Universal Coding Standards item 18

149

Universal Coding Standard Items

Item ucs-19A class that has pointer members shall have an operator= and a copy constructorDefault memberwise initialization is generally insufficient for classes that contain pointer members because the destructor is invoked for every class object, which may result in dangling references and other program errors. This rule checks to see if classes that have pointer members also have an operator= and a copy constructor. These errors are reported as violations of Item ucs-19.

Reason for rule: Prevents memory leaks and data corruption. If you do not define a copy constructor, the default constructor will be used, which is usually not the desired behavior when a class has pointer members.

Note: This item is suppressed by default.

Example /* * UCS item 19 - A class that has pointer members shall have * an operator=and a copy constructor */

class A{public: A(); ~A();

private: int *a;}; // UCS19 Violation

Output[ucs19.C:7] If a class has pointer members it must define a copy constructor and op=Violation: Universal Coding Standards item 19

150

Universal Coding Standard Items

Item ucs-20If a subclass implements a virtual function, use the virtual keywordUsing 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. These errors are reported as violations of Item ucs-20.

Reasons for rule: 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.

Note: This item is suppressed by default.

Example /* * UCS item 20 - If a subclass implements a virtual * function, use the virtual keyword */class B{public: virtual int foo();};

class D : public B{public: int foo(); // UCS20 Violation};

Output[ucs20.C:12] If a subclass redefines a virtual function, use the keyword virtual in that function's declarationViolation: Universal Coding Standards item 20

151

Universal Coding Standard Items

Item ucs-21Member functions shall not be defined in the class definitionFunctions 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. These errors are reported as violations of Item ucs-21. Note: This item is suppressed by default.

Reason for rule: Encourages better data hiding by separating interface and implementation.

Example /* * UCS item 21 - Member functions shall not be defined in * the class definition */class A{public:

int foo() {}; // UCS21 Violation};

Output[ucs21.C:7] Member functions shall not be defined within the class defini-tionViolation: Universal Coding Standards item 21class A defines the following functions within the class definition foo

152

Universal Coding Standard Items

Item ucs-22Ellipses shall not be usedDevelopers should avoid using unspecified function arguments (...), as this deters the strong type checking provided by C++. This rule detects if ellipses are used. These errors are reported as viola-tions of Item ucs-22.

Reason for rule: Ellipses defeat the benefits of type safety. Use default arguments instead. Note: This item is suppressed by default.

Example /* * UCS item 22 - Ellipses shall not be used */class A{public:

int foo(int, ...); // UCS22 Violation};

Output[ucs22.C:8] Ellipses shall not be usedViolation: Universal Coding Standards item 22function foo uses ellipses.

153

Universal Coding Standard Items

Item ucs-23Functions shall explicitly declare their return typesIf return types are not explicitly declared, functions will implicitly receive int as the return type. How-ever, 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. These errors are reported as violations of Item ucs-23.

Reason for rule: Readability. If you do not specify a return type, the compiler will assume either void or int, depending on the compiler. You should explicitly declare the return type so that the result will be unambiguous. Note: This item is suppressed by default.

Example /* * UCS item 23 - Functions shall explicitly declare their * return types */

foo(); // UCS23 Violation

Output[ucs23.C:5] Functions shall explicitly declare their return typeViolation: Universal Coding Standards item 23

154

Universal Coding Standard Items

Item ucs-24A pointer to a class shall not be converted to a pointer of a second class unless it inherits from the secondThis 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. These errors are reported as violations of Item ucs-24.

Reason for rule: If you violate this rule, you make assumptions about member layout of classes that may be subject to change, producing memory and data corruption bugs.

Example/* * UCS item 24 - A pointer to a class shall not be converted * to a pointer of a second class unless it inherits from the * second */

class A { };

class B { };

class D : public B { };

int main() { A *a; B *b; D *d;

b = (B*)a; // UCS24 Violation d = (D*)b; // UCS24 Violation b = (B*)d; // OK

return 0; }

Output[ucs24.C:14] A pointer to a class may not be converted to a pointer of a second class unless the first class inherits from the secondSevere violation: Universal Coding Standards item 24

155

Universal Coding Standard Items

Item ucs-25A pointer to an abstract class shall not be converted to a pointer that inherits from that classDowncasting from a virtual base is always illegal. This rule detects pointers to abstract classes that are converted to pointers that inherit from that class. These errors are reported as violations of Item ucs-25.

Reason for rule: When appropriate functions are virtual, converting them is unnecessary and confus-ing.

Example /* * UCS item 25 - A pointer to an abstract class shall * not be converted to a pointer that inherits from * that class */class B{public: virtual int foo() = 0;};class D : public B{public: int foo();};

int main(){ B *b; D *d;

d = (D*)b; // UCS25 Violation}

Output[ucs25.C:23] A pointer to an abstract class shall not be converted to a pointer of a class that inherits from the abstract classSevere violation: Universal Coding Standards item 25

156

Universal Coding Standard Items

Item ucs-26Do not use the friend mechanismUsing friend functions is usually a sign of an inadequate interface. Fixing the interface, rather than granting friendship, is the best approach. This rule detects if you use the friend mechanism. These errors are reported as violations of Item ucs-26.

Reason for rule: Using the friend mechanism undermines data-hiding and encapsulation. Note: This item is suppressed by default.

Example /* * UCS item 26 - Do not use the friend mechanism */

int foo();

class A{

friend int foo(); // UCS26 Violation};

Output[ucs26.C:8] Avoid using the friend mechanismViolation: Universal Coding Standards item 26Class A has the following friends: foo

157

Universal Coding Standard Items

Item ucs-27When working with float or double values, use <= and >= instead of ==Two different paths to the same number will not always lead to the same number. For example, float-ing-point numbers that should be equal are not always equal. Using <= and >= instead of == is the rec-ommended solution to the problem.

This rule detects if you use == when working with float or double values. These errors are reported as violations of Item ucs-27.

Reason for rule: Using <= and >= helps prevent rounding errors.

Example /* * UCS item 27 - When working with float or double * values, use <= and >= instead of == */int main(){

float a = 1.0;float b = 2.0;

if (a == b) { // UCS27 Violationreturn 1;

}

return 0;}

Output[ucs27.C:11] When working with float or double expressions, use less than or equal to or greater than or equal to instead of ==Violation: Universal Coding Standards item 27

158

Universal Coding Standard Items

Item ucs-28Do not overload functions within a template classOverloading functions within a template class can lead to problems if the element type appears explic-itly in one of them. This rule detects if you overload functions within a template class. These errors are reported as violations of Item ucs-28.

Reason for rule: Overloading functions may indicate a design flaw in the template class.

Example /* * UCS item 28 - Do not overload functions within a template * class */template <class T> class A{public:

int foo(T);int foo(int); // UCS28 Violation

};

Output[ucs28.C:6] Do not overload functions within a template classSevere violation: Universal Coding Standards item 28The following member functions of class Afoohave potentially conflicting overloaded versions

159

Universal Coding Standard Items

Item ucs-29Do not define structs that contain member functionsMember functions should be contained in classes, not structs, because classes support both multiple instances and encapsulation. Structs are also often entirely public: whereas the default access level for members and base classes of a class is private.

This rule detects if you define structs that contain member functions. These errors are reported as vio-lations of Item ucs-29.

Reason for rule: 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.

Note: This item is suppressed by default.

Example /* * UCS item 29 - Do not define structs that contain member * functions */struct A{public:

int foo(); // UCS29 Violation};

Output[ucs29.C:6] Do not define structs that contain objects with member functionsViolation: Universal Coding Standards item 29struct A contains the following member functions: foo

160

Universal Coding Standard Items

Item ucs-30Do not directly access global data from a constructorDirectly accessing global data from a constructor is risky because the global object may not yet exist when the "other" static object is initialized. This rule detects if you directly access global data from a constructor. These errors are reported as violations of Item ucs-30.

Reason for rule: 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 /* * UCS item 30 - Do not directly access global data from a * constructor */int a;class A{public:

A();private:

int b;};A::A(){ b = a; // UCS30 Violation}

Output[ucs30.C:8] Do not directly access global data from a constructorSevere violation: Universal Coding Standards item 30Constructor accesses the following global variables: a

161

Universal Coding Standard Items

Item ucs-31Do not use multiple inheritanceUsing multiple inheritances can result in strange class hierarchies and less flexible code. Because in C++ there may be an arbitrary number of instances of a given type, it could be that direct inheritance from a class may only be used once (see the example below). This rule detects if you use multiple inheritances. These errors are reported as violations of Item ucs-31.

Reasons for rule: Clarity, maintainability. Following this rule prevents ambiguity when classes derive from one object through multiple objects as in the “diamond of death” illustrated in the example.

Note: This item is suppressed by default.

Example /* * UCS item 31 - Do not use multiple inheritance */class B {};class A : public B {};class C : public B {};class D : public A, public C {};// UCS31 Violation

Output[ucs31.C:8] Do not use multiple inheritanceViolation: Universal Coding Standards item 31class D inherits multiply from the following classes: A, C

162

Universal Coding Standard Items

Item ucs-32Initialize all variablesA variable must always be initialized before it is used. By always initializing all variables, rather than assigning values to them before they are first used, your code is faster and more efficient since no tem-porary objects are created for the initialization. This rule detects if you fail to initialize all variables. These errors are reported as violations of Item ucs-32.

Reason for rule: Following this rule prevents reading from uninitialized variables. Note: This item is suppressed by default.

Example /* * UCS item 32 - Initialize all variables */int main(){

int a; // UCS32 Violation};

Output[ucs32.C:6] Initialize all variablesViolation: Universal Coding Standards item 32The following variables were not initialized when declared: a

163

Universal Coding Standard Items

Item ucs-33All pointers should be initialized to zero or to a legitimate addressInitializing pointers to zero or to a legitimate address makes the code more efficient and helps you catch signals and exceptions. This rule detects if you do not initialize all pointers in this manner. These errors are reported as violations of Item ucs-33.

Reason for rule: Initializing pointers to zero or to a legitimate address makes it easier to check if a pointer is valid. Note: This item is suppressed by default.

Example /* * UCS item 33 - All pointers should be initialized to zero * or a legitimate address */int main(){

int *a; // UCS33 Violation };

Output[ucs33.C:6] All pointers should be initialized to zero or a legitimate addressViolation: Universal Coding Standards item 33The following pointers were not initialized when declared: a

164

Universal Coding Standard Items

Item ucs-34Always terminate a case statement with breakIf the code following a case statement is not terminated with break, execution continues after the next case statement, meaning poorly tested code can be erroneous and yet still appear viable. This rule detects if you fail to terminate a case statement with break. These errors are reported as violations of Item ucs-34.

Reasons for rule: Readability, maintainability. Note: This item is suppressed by default.

Example /* * UCS item 34 - Always terminate a case statement with break */int main(){

int a = 0;

switch (a) {case 0:

return 0;case 1:

a = 1; // UCS34 Violation}

}

Output[ucs34.C:13] Always terminate a case statement with breakViolation: Universal Coding Standards item 34

165

Universal Coding Standard Items

Item ucs-35Always provide a default branch for switch statementsSwitch statements must always provide a default branch that handles unexpected cases. This rule detects if you fail to provide a default branch for switch statements. These errors are reported as vio-lations of Item ucs-35.

Reason for rule: Maintainability. If all desired cases are handled outside of default, then default can be used for error checking. Note: This item is suppressed by default.

Example /* * UCS item 35 - Always provide a default branch for switch * statements */int main(){

int a = 0;

switch (a) {case 0:

return 0;case 1:

return 1;} // UCS35 Violation

}

Output[ucs35.C:9] Always provide a default branch for switch statementsViolation: Universal Coding Standards item 35

166

Universal Coding Standard Items

Item ucs-36Do not use the goto statementThe goto statement interrupts the control flow, makes the code more difficult to understand, and has limits on when it can be used. This rule detects if you use the goto statement. These errors are reported as violations of Item ucs-36.

Reasons for rule: Readability, maintainability. Anything written with a goto statement can usually be written more clearly without a goto.

Note: This item is suppressed by default.

Example /* * UCS item 36 - Do not use the goto statement */int main(){

goto end; // UCS36 Violation

end:return 0;

}

Output[ucs36.C:7] Do not use the goto statementViolation: Universal Coding Standards item 36

167

Universal Coding Standard Items

Item ucs-37Provide only one return statement in a functionMinimizing the number of return statements in a function makes the function easier to understand. This rule detects if you provide more than one return statement in a function. These errors are reported as violations of Item ucs-37.

Reasons for rule: Readability, maintainability, debugging. It is easier to follow the program flow if there is only one return statement.

Note: This item is suppressed by default.

Example /* * UCS item 37 - Provide only one return statement in * a function */int main(){

if (0) {return 0;

} else {return 1; // UCS37 Violation

}}

Output[ucs37.C:6] Provide only one return statement in a functionInformational: Universal Coding Standards item 37

168

User Items

User ItemsUser ItemsUser items are C and C++ coding standards that you have created or that you can customize. Thereare two types of user items, coding standards that you have designed in RuleWizard and coding stan-dards written by Parasoft that can be modified/customized in RuleWizard. These rules are divided intoseveral categories, as shown in the following table:

Category Description

Naming Convention Identifiers in the 100-199 range are reserved for Naming Conventions and have names beginning with "Name." These rules do not represent code which is dangerous or incorrect; rather, they are schemes for naming vari-ables, functions, classes, and so on. When an entire development group agrees on a common convention, code becomes easier to read and more easily understood. Included in this category are the Hungarian naming con-ventions.

A common element in the Naming Conventions rules is the use of regular expressions. The regular expression format is based on that used in Perl. These regular expressions can be modified to enforce whatever Naming Convention your development group agrees upon.

Miscellaneous Identifiers in the 200-399 range are reserved for miscellaneous C and C++ coding standards that users can customize.

Text Rules Identifiers in the 400-499 range are reserved for Text rules. Rules in this section are used to check programming styles. They are derived from vari-ous coding standards, including Motorola's C and MISRA’s C coding stan-dards.

Metrics Identifiers in the 600-699 range are reserved for Metrics and have names beginning with "Metric."

These rules have a slightly different usage than other rules. Whereas most rules are designed to find patterns which represent bad programming prac-tices, the metrics rules are used primarily to produce numbers representing size and complexity of code. Because of this, most outputs in the metrics rules include a "$count" expression in the Output, which prints the number of occurrences found of that particular pattern. The collectors have count expressions which should be modified according to what cut-off point you are interested in seeing.

For example, MetricInheritance.rule reports the number of classes which a given class derives from directly or indirectly. The default is to report this number for classes where the ancestor count is greater than 10. If you want a report on the ancestors for every class, set the count expression to "$$>=0". Likewise, if you only want it to report on classes which derive from over 20 base classes, change the count expression to "$$>20". For a discussion of what metrics are and how to use them, see Mark Shroeder's article, "A Practical Guide to Object-Oriented Metrics" in IT Pro, November/December, 1999.

169

User Items

Violations of user items are labeled “user-<item number>.” You can suppress individual user rules or alluser rules as you would suppress rules in any other category. You can also enable/disable these rulesby checking or clearing options in the Control Panel’s Rules tab.

For more information on creating, modifying, and enforcing custom coding standards, open RuleWiz-ard by clicking the RuleWizard button in the Visual C++ Toolbar, then choose Help> View in theRuleWizard GUI to open the RuleWizard Users Guide.

Note: All rules are assumed to work for both C and C++ unless a specific language is otherwise notedwithin the rule itself. All rules are suppressed unless otherwise noted in the rule text.

C Rules Identifiers in the 700-799 range are reserved for C and C++ rules. They are derived from a variety of sources, including Motorola's C Coding Stan-dards.

32-bit to 64-bit Porting Rules

Identifiers in the 800-899 range are reserved for rules that flag coding con-structs that are dangerous when you are migrating from a 32-bit architec-ture to a 64-bit architecture.

Rule RuleID Description Violation

3264bit-32BitMultiplication 808 Do not assign the value 32-bit mul-tiplication to type long

V

3264bit-BinaryOverFlow 806 Operation will not resolve to 64 bits V

3264bit-CastPointerToUINT 811 Do not cast pointer to UINT type V

3264bit-HardCodeValueOffset 817 Do not use hard coded value of off-set in structures

PSV

3264bit-HardCodeValueOffset2 817 Do not use hard coded value of off-set in structures

PSV

3264bit-HexConstant 812 Do not use hex constants V

3264bit-ImplicitTruncation 802 Avoid writing code that will result in losing data

V

3264bit-ImplicitTruncation2 802 Avoid writing code that will result in losing data

V

3264bit-IntConstantToLongValue 809 Constant assignment to long should not involve int literals

V

3264bit-IntConstantToLongValue2 809 Constant assignment to long should not involve int literals

V

3264bit-IntLiteralToLongInit 807 Do not assign literal to type long V

3264bit-IntPointerCast 810 Do not cast pointer to int type V

3264bit-IntToLongPointerCast 805 Incompatible cast PSV

3264bit-LongDouble 816 Possible Truncation V

3264bit-LongToDoubleCast 816 Possible Truncation V

Category Description

170

User Items

3264bit-LongToDoubleCast2 816 Possible Truncation V

3264bit-LongToIntPointerCast 804 Do not cast long to int pointer PSV

3264bit-LongVariableSuffixes 818 Do not use i64 or L suffixes directly V

3264bit-OperandCast 803 Use explicit cast on operand of type long

V

3264bit-Union 813 Avoid union if possible V

3264bit-UsingLong 814 Avoid using long V

3264bit-VariableDefinition 815 Do not use a #define that the com-piler cannot type check

V

3264bit-VariableDefinition2 815 Do not use a #define that the com-piler cannot type check

PV

3264bit-VariableDefinition3 815 Do not use a #define that the com-piler cannot type check

V

3264bit-VariableDefinition4 815 Do not use a #define that the com-piler cannot type check

V

ArrayElementAccess 733 Array elements shall be accessed by the array operator [ ]

V

AssignAllMemberVar 302 Assign to all member variables in operator= functions

V

AssignCharTooHigh 707 Avoid assigning out-of-range value to char type

V

AssignCharTooLow 707 Avoid assigning out-of-range value to char type

V

AssignmentOperator 216 Declare an assignment operator for classes which have data members that are pointers

V

AssignUnCharTooHigh 706 Avoid assigning out-of-range value to unsigned char type

V

AssignUnCharTooLow 706 Avoid assigning out-of-range value to unsigned char type

V

BaseDestructors 218 Make destructors virtual for all base classes

V

BitwiseInCondition 742 Do not use the bitwise operator in conditional expressions

PV

BreakInForLoop 317 Do not use break in for loops SV

Rule RuleID Description Violation

171

User Items

CastFuncPtrToPrimPtr 717 Do not type cast pointers to primi-tive types for variables that have been declared as pointers to func-tions

V

CastPointer 207 Do not cast pointers to non-pointers V

CastUnsigned 205 Do not cast an unsigned char to an unsigned int

V

CharacterTest 721 Use the ctype.h facilities for charac-ter test

PV

CharCompareLeft 213 Do not compare chars to constants out of char range

SV

CharCompareRight 214 Do not compare chars to constants out of char range

SV

CommaOperator 734 The comma operator shall only be used in for statements and variable declarations

V

ConditionCurlyBraces 436 All conditional statements shall use { and } to identify the body of code associated with the condition

PSV

ConditionCurlyBraces2 437 All conditional statements shall use { and } to identify the body of code associated with the condition

PSV

ConditionCurlyBraces3 438 All conditional statements shall use { and } to identify the body of code associated with the condition

PSV

ConstParam 306 Declare reference parameters as const references whenever possi-ble

V

ConstPointerFunctionCall 737 Const data type should be used for pointers in function calls if the pointer is not to be changed

V

DeclareArrayMagnitude 726 Do not declare the size of an array when the array is passed into a function as a parameter

V

DeclareBitfield 710 Do not declare member variables as bitfields

I

DeclareExplicitConstructor 319 Do not use the keyword 'explicit' for a constructor

I

DeclareMutable 320 Do not declare member variables with the 'mutable' keyword

I

Rule RuleID Description Violation

172

User Items

DeclareRegister 709 Do not declare local variables with the 'register' keyword

I

DeclareStaticLocal 711 Do not declare local variables with the 'static' keyword

I

DeclDimArray 725 Do not declare the size of an array when the array is initialized

PV

DefineNamingConvention 407 All "#define" constants shall be in uppercase

I

DeleteIfNew 212 Write operator delete if you write operator new

V

DeleteNonPointer 206 Do not call delete on non-pointers SV

DoNotUseTabs 442 Tabs that do not use ASCII spaces should not be used

I

DoWhile 200 Prefer while statements over do statements

I

EnumKeyword 201 Do not use the ‘enum’ keyword to declare a variable in C++

I

EnumNamingConvention 729 In an enumerated list, list members (elements) shall be in uppercase and names or tags for the list shall be in lowercase

PV

EOSDefinition 415 Incorrect End-Of-String (EOS) defi-nition

PV

EOSUsage 401 EOS shall be used to terminate a string rather than using backslash-zero '\0'

PSV

EqualityFloatLeft 208 Do not check floats for equality; check for greater than or less than

SV

EqualityFloatRight 208 Do not check floats for equality; check for greater than or less than

SV

ExplicitEnumValues 740 When using enum, the values of each member should be explicitly declared

PV

ExplicitLogicalTest 738 Use explicit logical tests in condi-tional expressions

V

ExplicitLogicalTests 402 An explicit logical comparison should be used in conditional expression

V

ExprInSizeof 743 Avoid passing expressions like assignment to sizeof() operators

V

Rule RuleID Description Violation

173

User Items

FalseDefinition 411 If FALSE is to be defined, and is not already defined, FALSE should be 0

I

FalseTypeDef 413 If FALSE is to be defined, and is not already defined, FALSE should be 0

I

FileNameConvention 735 Use lowercase for file names PV

ForLoopVarAssign 300 Do not assign to loop control vari-ables in the body of a for loop

V

FractionLoss 211 Do not assign the dividend of two ints to a float

V

FuncModifyGlobalVar 701 Avoid functions that modify the glo-bal variable

V

FunctionCurlyBraces 435 All curly braces "{ }" shall appear on a line by themselves

V

FunctionCurlyBraces2 435 All curly braces "{ }" shall appear on a line by themselves

V

FunctionSize 724 Avoid functions with over 50 lines I

GlobalPrefixExclude 703 Global prefixes should only be used for global variables

I

GlobalVarFound 702 Avoid global variables I

HardCodeValue 406 "#define" or enum constants should be used instead of hard coded val-ues whenever possible

V

HardCodeValueWithZero 406 "#define" or enum constants should be used instead of hard coded val-ues whenever possible

V

HeaderInitialization 722 Headers should not contain any ini-tialization

PV

IfAssign 202 Avoid assignment in if statement condition

SV

IfElse 316 All if statements should have an else clause

I

ImplicitUnsignedInit 741 Do not initialize unsigned integer variables with signed constants

V

InitCharOutOfRange 707 Avoid assigning out-of-range value to char type

V

InitPointerVar 318 Initialize all pointer variables V

Rule RuleID Description Violation

174

User Items

InitUnCharOutOfRange 706 Avoid assigning out-of-range value to unsigned char type

V

LineLength 403 Physical lines shall be less than eighty characters

PSV

LocalVariableNames 731 Local variable names shall be low-ercase

PV

LongConst 210 Use capital 'L' instead of lowercase 'l' to indicate long

SV

MacroSize 404 The length of a macro should not exceed 10 lines

V

MacroWithinInclude 446 Do not use macros in the include statement

PSV

ManyCases 305 Avoid switch statements with many cases

I

MetricBlockofCode 604 Number of blocks of code per func-tion

V

MetricBreakEncap 600 Avoid using global in member func-tions

V

MetricFuncCall 602 Number of function calls V

MetricInheritance 601 Class inheritance level V

MetricMembers 607 Number of data member(s) per class

V

MetricMethod 605 Number of method(s) per class V

MetricParam 603 Number of parameter(s) per method

V

MetricPrivateMembers 608 Number of private data member(s) per class

V

MetricPrivateMethod 606 Number of private methods per class

V

MetricProtectedMembers 608 Number of protect data member(s) per class

V

MetricProtectedMethod 606 Number of protected method(s) per class

V

MetricPublicMembers 608 Number of public data member(s) per class

V

MetricPublicMethod 606 Number of public method(s) per class

V

Rule RuleID Description Violation

175

User Items

ModifyInCondition 708 Do not use operator ++ or -- in the conditional expression of if, while, or switch

PV

NameBool 110 Begin all boolean type variables with 'b'

I

NameClass 100 Begin class names with an upper-case letter

I

NameConflict 705 Avoid internal or external name conflict

V

NameConstantVar 101 Begin constant variables with ‘c’ I

NameDataMember 102 Begin class data member names with ‘its’

I

NameDouble 110 Begin all double type variable with 'd'

I

NameEnumType 103 Enumerated type name shall begin with an uppercase letter prefixed by the software element and suffixed by ‘_t’

I

NameFloat 110 Begin all float type variables with 'f' I

NameFunction 108 Begin function names with upper-case letter

I

NameGlobalVar 104 Begin global variable names with ‘the’

I

NameInt 110 Begin all integer type variable with 'i'

I

NameIsFunction 109 'is' functions should return bool val-ues

V

NameLongInt 110 Begin all long integer variables with 'li'

I

NamePointerVar 105 Prefix a variable type 'pointer' with a 'p' character

I

NameShortInt 110 Begin all short integer variables with 'si'

I

NameSignedChar 110 Begin all signed character variables with 'c'

I

NameString 110 Begin all terminated characters string variables with 'sz'

I

Rule RuleID Description Violation

176

User Items

NameStructType 106 Struct type name shall begin with an uppercase letter prefixed by software element and suffixed by '_t'

I

NameUnsignedChar 110 Begin all unsigned character type variables with 'uc'

I

NameUnsignedInt 110 Begin all unsigned integer type vari-ables with ‘ui’

I

NameVariable 107 Begin all variables with a lowercase letter

I

NamingStructUnionMembers 730 Use lowercase letters for structure and union member names

PV

NoInputParamsInMacros 450 No input parameters in macros V

NonScalarTypedefs 728 Append names of non-scalar type-defs with "_t".

PV

NullDefinition 414 Incorrect NULL definition I

NumberFunctionParam 736 Avoid functions with more than 5 parameters

V

NumberMacroParams 405 Macros should not use more than 5 parameters

V

OneStatementPerLine 443 Only one statement shall be allowed per line

V

OpEqualThis 219 Return reference to *this in opera-tor= functions

SV

ParenthesesInConditional 433 Logical parts of a conditional expression shall be grouped with parentheses even if not logically required

V

ParenthesesInConditional2 434 Logical parts of a conditional expression shall be grouped with parentheses even if not logically required

V

PartialStatementDefinition 448 Do not define part of statement PV

PassByValue 303 Pass built-in types by value unless you are modifying them

V

PointerParamDereference 715 Do not pass possibly null pointers as parameters

PV

PublicInterface 203 Avoid declaring class data member to be public

I

Rule RuleID Description Violation

177

User Items

RedefControlStatements 445 Do not redefine control statements PSV

RedefPrimitiveTypes 444 Do not redefine primitive types PV

RedefTypes 447 Do not redefine primitive types. Use typedef.

PV

ReferenceInitialization 720 Do not initialize a reference to an object whose address can be changed

PV

SingularSwitchStatement 745 Avoid switch statements with only one case

PV

SourceFileSize 723 Avoid source files that are longer than 500 lines

I

SourceNamingConvention 727 Use the ".c" extension for names of source files

I

SpaceInAssignmentOp 418 There shall be a single ASCII space character preceding and following assignment operators

V

SpaceInAssignmentOp2 419 There shall be a single ASCII space character preceding and following assignment operators

V

SpaceInBitwiseOp 424 There shall be a single ASCII space character preceding and following bitwise operators

V

SpaceInBitwiseOp2 425 There shall be a single ASCII space character preceding and following bitwise operators

V

SpaceInConditional 416 There shall be a single ASCII space character between a conditional statement and its opening paren-thesis

V

SpaceInConditional2 417 There shall be a maximum of 1 ASCII space character following the opening parenthesis

V

SpaceInConditionalOp 420 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInConditionalOp2 421 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInLogicalOp 423 There shall be a single ASCII space character preceding and following logical operators

V

Rule RuleID Description Violation

178

User Items

SpaceInRelationalOp 422 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInRelationalOp2 422 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInRelationalOp3 422 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInRelationalOp4 422 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInRelationalOp5 422 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInRelationalOp6 422 There shall be a single ASCII space character preceding and following conditional operators

V

SpaceInSelector 431 There shall be no white space pre-ceding or following a primary opera-tor

V

SpaceInSelector2 432 There shall be no white space pre-ceding or following a primary opera-tor

V

SpacesAfterComma 428 There shall be a single ASCII space character following all commas

V

SpacesAfterSemicolon 427 There shall be a single ASCII space character following all semicolons

V

SpacesAfterUnaryOperator 430 There should be no white space between a unary operator and its operand

V

SpacesBeforeComma 426 There shall be a single ASCII space character following all commas

V

SpacesBeforeUnaryOperator 429 There shall be no white space between a unary operator and its operand

V

StatementParenthesis 439 There shall be no white spaces between the "return" or "sizeof" statements and its opening paren-thesis

V

Rule RuleID Description Violation

179

User Items

StatementParenthesis2 440 There shall be no white spaces between the "return" or "sizeof" statements, arguments, or expres-sions

V

StatementParenthesis3 441 Parentheses shall be used with the "return" and "sizeof" statements

V

StructKeyword 204 Do not use the ‘struct’ keyword to declare a variable in C++

I

ThrowDestructor 215 Do not throw from within destructor V

TooManyFields 714 Avoid structs, unions, or classes with more than 20 fields

I

TrueDefinition 410 If TRUE is to be defined, & is not already defined, TRUE should be 1

I

TrueTypedef 412 If TRUE is to be defined, & is not already defined, TRUE should be 1.

I

TypeModifiersAfterType 408 Storage type modifiers shall be associated with the type, not the variable

V

TypeModifiersAfterValue 409 Storage type modifiers shall be associated with the type, not the variable

V

UnionFieldNotDefined 712 Define fields for union declarations I

UnnecessaryCast 308 Avoid unnecessary type casting V

Unnecessary Equal 304 Remove unnecessary “==true” in Boolean functions

I

UnreachableCode 744 Do not write unreachable code PV

UnreachableCode2 744 Do not write unreachable code PV

UnusedLocalVariable 311 Avoid unused local variables PV

UnusedParameter 310 Eliminate unused parameters PSV

UnusedPrivateMember 309 Eliminate unused private member variables

V

UseParenthesesInMacros 449 In a function such as macros, before multiplication or division, use parentheses

SV

UsePositiveLogic 739 Use positive logic rather than nega-tive logic whenever practical

PV

Rule RuleID Description Violation

180

User Items

3264bit-32bitMultiplication.ruleDo not assign the value 32-bit multiplication to type longThis rule checks whether a 32-bit multiplication rule is assigned a long value.

Reason for rule: Bit multiplication assigned a long value may result in truncation.

Examplevoid foo() {

long longValuelongValue = 2000000 * 3000000;longValue = 2000000L * 3000000

3264bit-BinaryOverflow.ruleOperation will not resolve to 64 bitsThis rule checks whether an int is cast to a long before an operation.

Reason for rule: 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.

Examplevoid foo() {

int a = 72int b = 55;long result = 0; result = (long)(a*b);// Violation. result = (long)((long)a*b); //Ok

}

3264bit-CastPointerToUINT.ruleDo not cast pointer to UINT typeThis rule checks whether you are casting a pointer to a UINT type

Reason for rule: In a 32-bit architecture, UINT and pointer have the same size: 32-bits. In a 64-bit architecture, UINT still has 32-bits, but pointer has size 64-bits, allowing for a possible loss if pointer is cast to UINT.

ExampleUINT foo{ char *buf; return (UINT)buf; //Violation}

181

User Items

3264bit-HardCodeValueOffset.ruleDo not use hard coded value of offset in structuresThis rule checks whether you are using the hardcoded value of offset in structures.

Reason for rule: On a 32-bit architecture, offset has 4 bytes (4*8bit=32 bit), but if the architecture is changed to 64-bit, the offset will increase to 8 bytes (*8*bit=64bit). Let compiler calculate field.

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#endifstruct myStruct { void *ptr; int i;};

void foo() { myStruct *ps = new myStruct(); int j; ps->i = 22; j= *(int *)((unsigned __int3264)ps + sizeof(void*)); //Violation j= *(int *)((unsigned __int3264)ps + 4); //Violation j= *(int *)((unsigned __int3264)ps->i + 0); //Violation j= *(int *)((unsigned __int3264)ps + offsetof(myStruct,i)); //Ok}

182

User Items

3264bit-HardCodeValueOffset2.ruleDo not use hard coded value of offset in structuresThis rule checks whether you are using the hardcoded value of offset in structures.

Reason for rule: On a 32-bit architecture, offset has 4 bytes (4*8bit=32 bit), but if the architecture is changed to 64-bit, the offset will increase to 8 bytes (*8*bit=64bit). Let compiler calculate field.

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; int j; s.i = 22;j= *(int *)((unsigned __int3264)&s + sizeof(void*)); //Violation j= *(int *)((unsigned __int3264)&s + 4 ); //Violation j= *(int *)((unsigned __int3264)&s.i + 0 ); //Violation j= *(int *)((unsigned __int3264)&s + offsetof(myStruct,i)); //Ok }

183

User Items

3264bit-HexConstants.ruleDo not use hex constantsThis rule checks whether you are using hex constants to declare a value.

Reason for rule: You should not declare a value in hex constant because in a 32-bit architecture 0xFFFFFFFF is -1, while in a 64-bit architecture 0xFFFFFFFF is +4294967295.

Example#ifdef _WIN64 #define CONST3264(a) (a##i64) #else // unix64/32 & win32#define CONST3264(a) (a##L) #endif

void foo() {long Val1 = 0xFFFFFFFF; //Violationlong Val2 = CONST3264(-1); //Ok

}

3264bit-ImplicitTruncation.ruleAvoid writing code that will result in losing dataThis rule checks whether you use implicit truncation.

Reason for rule: Assigning a long int to an int may result in truncation when porting from 32-bit to 64-bit applications.

Examplevoid foo(){

int iVal = 72;long lVal = 6; iVal = lVal; //Violation iVal = (int)lVal; //Violation too

}

184

User Items

3264bit-ImplicitTruncation2.ruleAvoid writing code that will result in losing dataThis rule checks whether you use implicit truncation.

Reason for rule: Assigning a long int to an int may result in truncation when porting from 32-bit to 64-bit applications.

Examplevoid foo(int iVal){

long lVal ; //.. set big value for lValfoo(lVal); //Violationfoo((int)lVal); //Violation too }void foo()

}

3264bit-IntConstantToLongValue.ruleConstant assignment to long should not involve int literalsThis rule checks whether constant assignments to long involve int literals.

Reason for rule: Constant assignment to long should not involve literals because when you try to copy a 32-bit value to a 64-bit value without previous conversion (without L), it is not possible to set all 8 bytes (you can only set 4 bytes). The other 4 bytes are not set, so they may contain an accidental value.

Examplevoid foo(){

long longValue; long Value &= ~(0x00000000008000000000); // Violation: leading zeros not significant.

}

185

User Items

3264bit-IntConstantToLongValue2.ruleConstant assignment to long should not involve int literalsThis rule checks whether constant assignments to long involve int literals.

Reason for rule: Constant assignment to long should not involve literals because when you try to copy a 32-bit value to a 64-bit value without previous conversion (without L), it is not possible to set all 8 bytes (you can only set 4 bytes). The other 4 bytes are not set, so they may contain an accidental value.

Note: In the following example, the line break after longValue = should be ignored. This break is due to width restrictions on this manual page.

Examplevoid foo() {

long longValue; longValue = 0x00000000008000000000; // Violation: leading zeros not significant.

}

3264bit-IntLiteralToLongInit.ruleDo not assign literal to type longThis rule checks whether constant assignments to long involve int literals.

Reason for rule: An int literal is 32 bits in length. Assignment of int literal to long data value could lead to corruption in the upper 32 bits, or truncation if the int literal takes up more than 32 bits.

Note: In the following example, the line break after longValue = should be ignored. This break is due to width restrictions on this manual page.

Examplevoid foo() {

long longValue; longValue = 0x00000000008000000000; // Violation: leading zeros not significant.

}

186

User Items

3264bit-IntPointrCast.ruleDo not cast pointer to int typeThis rule checks whether constant assignments to long involve int literals.

Reason for rule: An int literal is 32 bits in length. Assignment of int literal to long data value could lead to corruption in the upper 32 bits, or truncation if the int literal takes up more than 32 bits.

Examplevoid foo(){

char *p;int g=(int)p; // Violation } // not significant.

}

3264bit-IntToLongPointerCast.ruleIncompatible castThis rule checks whether you cast int to long pointer cast.

Reason for rule: int and long pointer are not compatible in 64 bit, even though in 32 bit they would have been interchangeable.

Examplevoid f2005() {

int *intPointer;long *longPointer;longPointer = (long *)intPointer; // Violation

}

3264bit-LongDouble.rulePossible TruncationThis rule checks for possible truncation.

Reason for rule: Under the 32 bit platform, double can hold all significant bits. Under the 64 bit plat-form, double has 52 significant bits, and bits can be lost.

Examplevoid foo() {

double doubleValue;long longValue = 1L;doubleValue = longValue; // Violation

}

187

User Items

3264bit-LongToDoubleCast.rulePossible TruncationThis rule checks for possible truncation.

Reason for rule: Under the 32 bit platform, double can hold all significant bits. Under the 64 bit plat-form, double has 52 significant bits, and bits can be lost.

Examplevoid foo() {

long longValue = 1L; (double)longValue; // Violation

}

3264bit-LongToDoubleCast2.rulePossible TruncationThis rule checks for possible truncation.

Reason for rule: Under the 32 bit platform, double can hold all significant bits. Under the 64 bit plat-form, double has 52 significant bits, and bits can be lost.

Examplevoid moo (double) {}

void foo () {long longValue = 1L;moo(longValue); // Violation

}

3264bit-LongToIntPointerCast.ruleDo not cast long to int pointer This rule checks whether you pass long to int pointer.

Reason for rule: A pointer long should not be passed to a pointer int. It is an incompatible pass.

Examplevoid foo() {

int *intPointer;long *longPointer; intPointer = (int *)longPointer; // Violation

}

188

User Items

3264bit-LongVariableSuffixes.ruleDo not use i64 or L suffixes directlyThis rule checks whether you use i64 or L suffixes directly.

Reason for rule: Do not use i64 or L suffixes directly because it generally does not work well. Try using Macros for compatibility.

Example#ifdef _WIN64 #define CONST3264(a) (a##i64)#else#define CONST3264(a) (a##L) #endif

#define V1 0x000000000000000cL //Violation const long V2 CONST3264(3015); //Ok

3264bit-OperandCast.ruleUse explicit cast on operand of type longThis rule checks whether you use explicit cast on operands of type long.

Reason for rule: Explicit narrowing casts of type long should be used on expressions, not operands.

Examplevoid foo() {

int int1, int2, int3;long longValue; int2 = (int)longValue/int1;

// Violation: longValue is truncated to 32 bits before divide int3 = (int)(longValue/int1);

// the result of the division is truncated // to 32 bits. }

3264bit-Union.ruleAvoid union if possibleThis rule checks whether you avoid union.

Reason for rule: Unions are not portable because they are used in different ways by different sys-tems.

Exampleunion myUnion { //Violation

long l;char bytes[4];

};

189

User Items

3264bit-UsingLong.ruleAvoid using longThis rule checks whether you avoid using long.

Reason for rule: On win32/unix32/win64, long has 32-bit. On unix64, long has 64-bit. Instead of long, use your own type or specific variable definition.

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 __int3264 newlVal; //Ok

3264bit-VariableDefinition.ruleDo not use a #define that the compiler cannot type checkThis rule checks whether you use a #define that the compiler cannot type check.

Reason for rule: Using a #define prevents the compiler from checking the type.

Example#define V1 20 //Violationconst int V2 = 20; //Ok #define ARCH32 true

190

User Items

3264bit-VariableDefinition2.ruleDo not use a #define that the compiler cannot type checkThis rule checks whether you use a #define that the compiler cannot type check.

Reason for rule: Using a #define prevents the compiler from checking the type.

Example#define V 20000L //Violation

void foo() { int i = V; // possible overflow

}

3264bit-VariableDefinition3.ruleDo not use a #define that the compiler cannot type checkThis rule checks whether you use a #define that the compiler cannot type check.

Reason for rule: Using a #define prevents the compiler from checking the type .

Example#define INDEX_STR_LEN 10#define MACHINE_NAME_LEN MAX_COMPUTERNAME_LENGTH+2 //violation

3264bit-VariableDefinition4.ruleDo not use a #define that the compiler cannot type checkThis rule checks whether you use a #define that the compiler cannot type check.

Reason for rule: Using a #define prevents the compiler from checking the type.

Exampledefine INDEX_STR_LEN 10 #define MACHINE_NAME_LEN 2+MAX_COMPUTERNAME_LENGTH //violation

191

User Items

ArrayElementAccess.ruleArray elements shall be accessed by the array operator [ ]This rule checks whether array elements are accessed by the array operator [].

Reason for rule: Array elements should be accessed by the array operator [] rather than the derefer-ence operator '*'. Access to array by the dereference operator '*' is cryptic and hides the real intention.

Examplevoid foo(){

int array[2]; array[1] = 0; //OK *(array+1) = 0; //Violation*array = 0; //Violation

}

AssignAllMemberVar.rule Assign to all member variables in operator= functionsThis rule checks whether you assign to all member variables in operator= functions. This rule applies only to the C++ programming language.

Reason for rule: Assigning to all member variables in operator= functions prevents data corruption.

Exampleclass Foo {public: Foo& operator=(const Foo& rhs) { if (&rhs == this) { return *this; } x = f.x; y = f.y; // violation, z is not assigned return *this; }private: int x; int y; int z;};

192

User Items

AssignCharTooHigh.ruleAvoid assigning out-of-range value to char typeThis rule checks whether constants are greater than the char type’s legal range.

Reason for rule: The range of legal values for the char type is -128 to 127.

Example/*Range of values of char type is -128 to 127.*/

void Foo(){

char c1 = 0;c1 = 145; // hit// ...return;

}

AssignCharTooLow.ruleAvoid assigning out-of-range value to char typeThis rule checks whether constants are less than the char type’s legal range.

Reason for rule: The range of legal values for char type is -128 to 127.

Example/*Range of values of char type is -128 to 127.Violation if value is less than -128.*/void Foo(){

char uVal = 0;uVal = -133; // hit// ...return;

}

193

User Items

AssignmentOperator.ruleDeclare an assignment operator for classes which have data members that are pointersThis rule checks whether you declare an assignment operator for classes with pointer member vari-ables. This rule applies only to the C++ programming language.

Reason for rule: Declaring an assignment operator for each class with pointer member variables pre-vents memory leaks and data corruption.

Note: This rule is similar to item ecpp_11.

Example// See also ECPP 11class A // Violation{public: A() {} ~A() {}private: char *cptr1;};

AssignUnCharTooHigh.ruleAvoid assigning out-of-range value to unsigned char typeThis rule checks whether constants are greater than the unsigned char type’s legal range.

Reason for rule: The range of legal values for char type is 0 to 255.

Example/*Range of values of unsigned char type is 0 to 255.Violation if assignment is too high.*/

void Foo(){

unsigned char uVal = 0;uVal = 289;// ...return;

}

194

User Items

AssignUnCharTooLow.ruleAvoid assigning out-of-range value to unsigned char typeThis rule checks whether constants are less than the unsigned char type’s legal range.

Reason for rule: The range of legal values for the char type is 0 to 255.

Example/*Range of values of unsigned char type is 0 to 255.Violation if assignment is too low.*/

void Foo(){

unsigned char uVal = 0;uVal = -1;// ...return;

}

/*

BaseDestructors.ruleMake destructors virtual for all base classesThis rule checks whether destructors in base classes are virtual. This rule applies only to the C++ pro-gramming language.

Reason for rule: Making all destructors for base classes virtual prevents memory leaks and improper object destruction.

Note: This rule is similar to item ecpp_14.

Example// See ECPP 14

class Base{public: Base() {} ~Base() {} // Violation};

class Derived: public Base{public: Derived() {}; ~Derived() {};};

195

User Items

BitwiseInCondition.ruleDo not use the bitwise operator in conditional expressionsThis rule checks whether bitwise operators are inside conditionals.

Reason for rule: Using bitwise logical operators (&, |, or ~) in the conditional part of if, while or switch can make code difficult-to-read and error-prone.

Exampleint Foo (int iVar){

if (iVar & 0x01) { // hitiVar += 10;

} else {iVar -= 10;

}return iVar;

}

BreakInForLoop.ruleDo not use break in for loopsThis rule checks if there are breaks in your for loops.

Reason for rule: Avoiding breaks in the for loop makes your code easier to follow.

Note: This rule is similar to item ecpp_14.

Example// Avoid break in for loop to make the code easier to follow.

void func() { for (int i = 0; i < 10; i++) { // Okay } for (int i = 0; i < 10; i++) { // Violation if (true) { break; } }}

196

User Items

CastFuncPtrToPrimPtr.ruleDo not type cast pointers to primitive types for variables that have been declared as pointers to functionsThis rule checks whether pointers to functions are cast to pointers of primitive types.

Reason for rule: Casting pointers to functions to pointers of primitive types can make code error prone.

Examplevoid Foo(char *ptrC){ *ptrC = 0; return;}void f(){ void *ptrV = 0; void (*funPtr) (char*) = 0; funPtr = &Foo; ptrV = (void*)funPtr; // violation // ... return;}

CastPointer.ruleDo not cast pointers to non-pointersThis rule checks whether you cast a pointer to a non-pointer.

Reason for rule: Casting a pointer to a non-pointer results in a loss of typechecking.

Note: This rule is enabled by default.

Examplevoid func(){ int i; char * pchar = "hello"; i = (int)pchar; // Violation}

197

User Items

CastUnsigned.ruleDo not cast an unsigned char to an unsigned intThis rule checks whether you cast an unsigned char to an unsigned int.

Reason for rule: Casting an unsigned char to an unsigned int can result in loss of precision.

Note: This rule is enabled by default.

Examplebool foo( char ch ){ if( (unsigned) ch == 0xFF ) { // Violation return true; } return false;}

CharacterTest.ruleUse the ctype.h facilities for character testThis rule checks whether you use the ctype.h facilities for character test.

Reason for rule: The ctype.h facilities for character tests and upper-lower conversions (isalnum, isal-pha, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper) are por-table across different character code sets, are usually very efficient, and promote international flexibility. However, other similarly named functions (such as _tolower, _toupper, _isascii) are not uni-versally portable.

Example#include

void test(char c) { if( 'a' <= c && c <= 'z') { //Violation } if( islower(c) ) { //OK } while( 'A' <= c && c <= 'Z') { //Violation } while( isupper(c) ) { //OK } }

198

User Items

CharCompareLeft.ruleDo not compare chars to constants out of char rangeThis rule checks whether you compare chars to constants out of char range

Reason for rule: Comparing chars to constants out of char range can result in a constant out of range for the comparison operator.

Note: This rule is enabled by default.

Exampleint foobar(char c){ if (c > 300) { return 3;} // Violation if (c > 25) { return 2;} // OK return 0;}

CharCompareRight.ruleDo not compare chars to constants out of char rangeThis rule checks whether you compare chars to constants out of char range

Reason for rule: Comparing chars to constants out of char range can result in a constant out of range for the comparison operator.

Note: This rule is enabled by default.

Exampleint foobar(char c){ if (c > 300) { return 3;} // Violation if (c > 25) { return 2;} // OK return 0;}

199

User Items

CommaOperator.ruleThe comma operator shall only be used in for statements and variable declarationsThis rule checks whether you use the comma operator in for statements and variable declarations.

Reason for rule: The comma operator shall only be used in for statements, variable declaration(s)/ definitions(s), and multi-statement preprocessor macro definition(s). Extensive use of the comma oper-ator reduces readability.

Examplevoid foo(int i)

{

int dVal,count; //OK

foo((dVal=i,count=dVal+1)); //Violation}

ConditionCurlyBraces.ruleAll conditional statements shall use { and } to identify the body of code associated with the conditionThis rule checks whether you use curly braces in conditional statements.

Reason for rule: Promotes readability by explicitly identifying the code block associated with a condi-tional expression. This also reduces the risk of error if a programmer must add statements to a condi-tional code block which previously had no lines of code associated with it, or perhaps had only a single line of code.

Examplevoid foo(char *str) {

/*Violation*/ if ((*str) != 0) str++;

/*Ok*/ if ((*str) != 0) { str++; }}

200

User Items

ConditionCurlyBraces2.ruleAll conditional statements shall use { and } to identify the body of code associated with the conditionThis rule checks whether you use curly braces in conditional statements.

Reason for rule: Promotes readability by explicitly identifying the code block associated with a condi-tional expression. This also reduces the risk of error if a programmer must add statements to a condi-tional code block which previously had no lines of code associated with it, or perhaps had only a single line of code.

Examplevoid foo(char *str) {

/*Violation*/ do str++; while(*str!=0) /*Ok*/ do { str++; } while(*str!=0)}

ConditionCurlyBraces3.ruleAll conditional statements shall use { and } to identify the body of code associated with the conditionThis rule checks whether you use curly braces in conditional statements.

Reason for rule: Promotes readability by explicitly identifying the code block associated with a condi-tional expression. This also reduces the risk of error if a programmer must add statements to a condi-tional code block which previously had no lines of code associated with it, or perhaps had only a single line of code.

Examplevoid foo(char *str) {

/*Violation*/ while ((*str) != 0) str++;

/*Ok*/ while ((*str) != 0) { str++; }}

201

User Items

ConstParam.ruleDeclare reference parameters as const references whenever possibleThis rule checks if you declared your reference parameters as const references.

Reason for rule: When your function is not going to modify the argument it is referencing, you should use const to protect variables from unintended modifications when the function returns.

Examplestruct Foo { int x; int y;};

int Bar(Foo &f) { // Violation return f.x;}

int FooBar(Foo &f) { // Okay return f.y++;}

ConstPointerFunctionCall.ruleConst data type should be used for pointers in function calls if the pointer is not to be changedThis rule checks whether you use const data types for pointers in function calls when the pointer will not be modified.

Reason for rule: The const specifier guarantees that the value of the variable cannot be changed. If the value is changed, the compiler will report an error.

Exampleint foo( int *j) { // Violation return *j;}

int bar( const int *j) { // Okay return *j;}

202

User Items

DeclareArrayMagnitude.ruleDo not declare the size of an array when the array is passed into a function as a parameterThis rule checks if you declare the magnitude of a single dimensional array in the parameters declara-tion.

Reason for rule: You should not declare the magnitude of a single dimensional array in the argument declaration. If you do, the 'C' language will pass an array argument as a pointer to the first element in the array; in fact, a different invocation of the function may pass array arguments with different magni-tudes. Therefore, specifying the magnitude of an array in a function argument definition could hinder software maintenance.

Examplevoid foo1(int ii[]) { //OK}

void foo2(int ii[30]) { //Violation}

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

void foo4(char a,int ii[][30][30]) { //OK}

DeclareBitfield.ruleDo not declare member variables as bitfieldsThis rule checks if you declare member variables as bitfields.

Reason for rule: Informational.

Examplestruct A{ int iVarBitField : 8; int iVar;};

203

User Items

DeclareExplicitConstructor.ruleDo not use the keyword 'explicit' for a constructorThis rule checks if you use the keyword ‘explicit’ for a constructor.

Reason for rule: Informational.

Exampleclass X {public: explicit X(int); explicit X(double) {}};

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

Reason for rule: Informational.

Example/* This rule is purely informational and will report a message when a variable declaration with the 'mutable' keyword is found.*/

class Date{public: int getMonth() const; // A read-only function private:

mutable int month;int year;int day;

};

int Date::getMonth() const{

month++; // Doesn't modify anything if not mutablereturn month;

}

204

User Items

DeclareRegister.ruleDo not declare local variables with the 'register' keywordThis rule checks if you declare local variables with the 'register' keyword.

Reason for rule: Informational.

Examplevoid Foo(){ register int i = 0; // hit return;}

DeclareStaticLocal.ruleDo not declare local variables with the 'static' keywordThis rule checks if you declare local variables with the 'static' keyword.

Reason for rule: Informational.

Examplevoid Foo(){ int static iVar = 9; // hit return;}

DeclDimArray.ruleDo not declare the size of an array when the array is initializedThis rule checks if you declare the magnitude of an array declaration.

Reason for rule: When arrays are initialized in the definition, their magnitude should be set by initial-ization. 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.

Example#define SIZE 4

int tab1[SIZE] = {1,2,3}; //Violationint tab2[]={1,2,3}; //OKint tab3[SIZE] = {1,2,3}; //Violation

205

User Items

DefineNamingConvention.ruleAll "#define" constants shall be in uppercase This rule checks that all “#define” constants are in uppercase.

Reason for rule: This convention will make the recognition of constants easier and support future maintenance efforts.

Example#define max_value 255 /*Violation*/#define MAX_VALUE 255 /*Ok*/

DeleteIfNew.ruleWrite operator delete if you write operator newThis rule checks whether you write operator delete when you write operator new. This rule applies only to the C++ programming language.

Reason for rule: Writing operator delete and operator new in concert helps prevent memory corrup-tion and memory leaks.

Note: This rule is similar to item ecpp10.

Example// See ECPP 10

class A{ // Violation public: A() {} void* operator new(size_t size) { return new int[size]; }};

206

User Items

DeleteNonPointer.ruleDo not call delete on non-pointersThis rule checks whether you call delete on a non-pointer.

Reason for rule: Calling delete on a non-pointer results in an invalid operand.

Note: This rule is enabled by default.

Exampleclass Rhino {public: Rhino(); Rhino (char *); Rhino (const char *); operator char *();};

void func(){ Rhino r; delete(r); // Violation}

DoNotUseTabs.ruleTabs that do not use ASCII spaces should not be usedThis rule checks whether you are using only ASCII white spaces as tabs.

Reason for rule: 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.

Examplevoid foo(){

int i; /*Violation*/ int j; /*Ok*/}

207

User Items

DoWhile.rulePrefer while statements over do statementsThis rule checks whether your code prefers while statements over do statements.

Reason for rule: Using do statements can lead to errors and confusion. Using while statements instead of do statements can make code clearer and help prevent errors.

Note: This rule is enabled by default.

Exampledo { i++;} while ( i < 10); // Violation

while (i < 10) { // OK i++;}

EnumKeyword.ruleDo not use the ‘enum’ keyword to declare a variable in C++This rule checks whether your C++ code uses enum keywords to declare variables. This rule applies only to the C++ programming language.

Reason for rule: Readability.

Example// enum keyword is unnecessary in C++ when declaring a variable.enum Colors { RED, BLUE, GREEN };enum Colors c; // Violation, enum keyword is unnecessaryColors C; // OK

208

User Items

EnumNamingConvention.ruleIn an enumerated list, list members (elements) shall be in uppercase and names or tags for the list shall be in lowercaseThis rule checks naming conventions in enumerated lists; it checks that list members (elements) are in uppercase and that tags for the list are in lowercase.

Reason for rule: The members of a list are equivalent to a defined constant; only the compiler is per-forming the definition.

Example//OKenum color { RED, BLUE, GREEN};//Violationenum Color { red, blue, green};

EOSDefinition.ruleIncorrect End-Of-String (EOS) definitionThis rule check whether you are using EOS to terminate a string.

Reason for rule: EOS should be used to terminate a string rather than NULL, since NULL is not guar-anteed to be defined as zero. This also promotes the use of defined constants rather than hard coded values.

Example#define EOS 0 /*Violation*/#undef EOS#define EOS NULL /*Violation*/#undef EOS#define EOS '\0' /*Ok*/

209

User Items

EOSUsage.ruleEOS shall be used to terminate a string rather than using backslash-zero '\0' This rule checks that EOS is used to terminate a string.

Reason for rule: EOS should be used to terminate a string rather than NULL, since NULL is not guar-anteed to be defined as zero. This also promotes the use of defined constants rather than hard coded values.

Example#define EOS '\0';

void foo() {

char str[30] = "Sample text.";str[7] = '\0'; /*Violation*/

str[7] = EOS; /*OK*/}

EqualityFloatLeft.ruleDo not check floats for equality; check for greater than or less thanThis rule checks whether you check floats for equality instead of checking for greater than or less than.

Reason for rule: If you check floats for equality, you make your code more susceptible to rounding errors.

Note: This rule is enabled by default.

Examplevoid func(float a, float b){ if (a==b) { } // Violation while (a!=b) { } // Violation if (a>b) { } // OK}

210

User Items

EqualityFloatRight.ruleDo not check floats for equality; check for greater than or less thanThis rule checks whether you check floats for equality instead of checking for greater than or less than.

Reason for rule: If you check floats for equality, you make your code more susceptible to rounding errors.

Note: This rule is enabled by default.

Examplevoid func(float a, float b){ if (a==b) { } // Violation while (a!=b) { } // Violation if (a>b) { } // OK}

ExplicitEnumValues.ruleWhen using enum, the values of each member should be explicitly declaredThis rule checks if the values of each member are explicitly declared when you are using enum.

Reason for rule: Declaring values is useful as a documenting feature. Documenting is valuable when using an emulator, logic analyzer, or other debugging device.

Exampleenum my_enum { a, //Violation b = 3 //OK};

ExplicitLogicalTest.ruleUse explicit logical tests in conditional expressionsThis rule checks whether you use explicit logical tests in conditional expressions.

Reason for rule: Using explicit logical tests in conditional expressions improves code readability.

Examplevoid foo( int *j){ if(!j){ // Violation } if(j == 0){ // OK }}

211

User Items

ExplicitLogicalTests.ruleAn explicit logical comparison should be used in conditional expressionThis rule checks that explicit logical tests are used in conditional expressions.

Reason for rule: Using explicit logical tests in conditional expressions improves code readability.

Examplevoid foo() { int isvisible = 1; if (isvisible) /*Violation*/ { ; } if (isvisible == 1) /*Ok*/ { ; } if (!isvisible) /*Violation*/ { ; } if (isvisible != 1) /*Ok*/ { ; }}

ExprInSizeof.ruleAvoid passing expressions like assignment to sizeof() operatorsThis rule checks for expressions in the sizeof operator.

Reason for rule: Expressions in the sizeof operator will not be executed.

Examplevoid foo (){ int iVar1 = 0; int iVar2 = 0; iVar1 = sizeof(iVar2 = 1); /* Violation */

return;}

212

User Items

FalseDefinition.ruleIf FALSE is to be defined, and is not already defined, FALSE should be 0This rule checks whether you defined FALSE as 0.

Reason for rule: Any other use of FALSE is misleading and will not be guaranteed to work predictably.

Example#define FALSE 1 /*Violation*/#undef FALSE#define FALSE /*Violation*/#undef FALSE#define FALSE 0 /*Ok*/

FalseTypedef.ruleIf FALSE is to be defined, and is not already defined, FALSE should be 0This rule checks if FALSE is defined as 0.

Reason for rule: Any other use of Fxsave falsetypedef.fmALSE is misleading and will not be guaran-teed to work predictably.

Example#ifndef TRUEtypedef enum { FALSE = 0,TRUE = 3 /*Violation*/} BOOL ;#endif

FileNameConvention.ruleUse lowercase for file namesThis rule checks whether your file names are in lowercase.

Reason for rule: When an entire development group agrees on a common convention, code becomes easier to read and more easily understood.

213

User Items

ForLoopVarAssign.ruleDo not assign to loop control variables in the body of a for loopThis rule checks whether you assign to loop control variables in the body of a for loop.

Reason for rule: For loop control variables should only be modified in the initialization and condition expressions of the for loop statement. Modifying them inside the body of the for loop makes the loop condition difficult to understand and points to a possible logical flaw in the code.

Examplevoid func() { for (int i = 0; i < 100; i++) { // Violation i += 3; } for (int i = 0; i < 100; i++) { // Violation i++; }}

FractionLoss.ruleDo not assign the dividend of two ints to a floatThis rule checks whether you assign the dividend of two ints to a float.

Reason for rule: Assigning a dividend of two ints to a float may cause a loss of fraction.

Note: This rule is enabled by default.

Examplevoid func(){ int a = 3; int b = 4; double d; d = a / b; // Violation d = ((double)a) / b; // OK}

214

User Items

FuncModifyGlobalVar.ruleAvoid functions that modify the global variableThis rule checks whether functions modify the global variable.

Reason for rule: Informational.

Exampleint theGlob;// ...void foo( int iVar ){ theGlob = -1; if (iVar == 0 )

{ theGlob = 0; } else { theGlob = 1; } return;}

FunctionCurlyBraces.ruleAll curly braces "{ }" shall appear on a line by themselvesThis rule checks that curly braces “{}” appear on a line by themselves.

Reason for rule: This rule promotes readability by clearly indicating the beginning and end points of a block of code. This also encourages block commenting.

Example#define true 1#define false 0

void foo() { int bVal = 1;

while ( bVal ) { bVal = false; /*Ok*/ } while ( bVal ) { bVal = false; /*Violation*/ } }

215

User Items

FunctionCurlyBraces2.ruleAll curly braces "{ }" shall appear on a line by themselvesThis rule checks that curly braces “{}” appear on a line by themselves.

Reason for rule: This rule promotes readability by clearly indicating the beginning and end points of a block of code. This also encourages block commenting.

Example#define true 1#define false 0

void foo() { int bVal = 1;

while ( bVal ) { bVal = false; /*Ok*/ } while ( bVal ) { bVal = false; } /* Violation */

}

FunctionSize.ruleAvoid functions with over 50 linesThis rule checks whether functions have over 50 lines.

Reason for rule: Programs should be designed so that most of the functions will be less than 50 lines of source listening. Algorithms are easier to create and to understand if they are built of pieces small enough to be grasped as one concept.

216

User Items

GlobalPrefixExclude.ruleGlobal prefixes should only be used for global variablesThis rule checks whether global prefixes are used with local variables.

Reason for rule: Using global prefixes for local variables reduces code readability.

Examplevoid foo(){ int theVar = 0; // ... theVar++; return; }

GlobalVarFound.ruleAvoid global variablesThis rule checks whether your code contains global variables.

Reason for rule: Informational.

Exampleint theVar; // hit// ...void foo(int iVar){ theVar = iVar; return; }

217

User Items

HardCodeValue.rule"#define" or enum constants should be used instead of hard coded values whenever possibleThis rule checks whether you are avoiding using hard coded values.

Reason for rule: Using #define or enum constants rather than hard coded values promotes the main-tainability of 'C' code by creating a localized area for changes.

Example#define buff 256#define OK 1

enum color{ RED = 0, BLUE = 1, GREEN = 2 /*...*/};

void foo() { int tabColorsNew[256]; /*Violation*/ int tabColors[buff]; /*Ok*/

if ( tabColors[0] == 1 ) /*Violation*/ { /*...*/ }

if ( tabColors[RED] == OK ) /*Ok*/ { /*...*/ } }

218

User Items

HardCodeValueWithZero.rule"#define" or enum constants should be used instead of hard coded values whenever possibleThis rule checks whether you are avoiding using hard coded values.

Reason for rule: Using #define or enum constants rather than hard coded values promotes the main-tainability of 'C' code by creating a localized area for changes.

Example/* NOTE: This rule expands rule HardCodeValue.rule about case Zero. */

#define buff 256#define OK 0

enum color{ RED = 0, BLUE = 1, GREEN = 2 /*...*/};

void foo() { int tabColorsNew[256]; /*Violation*/ int tabColors[buff]; /*Ok*/

if ( tabColors[0] == 0 ) /*Violation*/ { /*...*/ }

if ( tabColors[RED] == OK ) /*Ok*/ { /*...*/ } }

HeaderInitialization.ruleHeaders should not contain any initializationThis rule checks whether headers contain any initialization.

Reason for rule: Headers should not contain any initialization. When initialization is in the header, it is not clear which function "owns" the date (that is, the "defining instance" is not localized). Multiple source files each including a file containing initializations will generally produce "multiply defined" diag-nostics.

219

User Items

IfAssign.ruleAvoid assignment in if statement conditionThis rule checks whether your code has assignment within an if statement condition.

Reason for rule: Legibility and maintainability. Assignment in the context of an if statement is easily confused with equality.

Note: This rule is enabled by default.

Example// Assignment in the context of if statement is easily// confused with equality.void foo(int a, int b) { if ( a = b ) {} // Violation if ( a == b ) {} // OK}

IfElse.ruleAll if statements should have an else clauseThis rule checks if each of your if statements has an else clause.

Reason for rule: Writing if and else in concert improves readability and reliability.

Examplevoid Foo(bool b) { int i = 0; int j = 0; if (b) { // Informational, should have an else clause i += j; } if (b) { j += i; } else { // Okay, has an else clause i++; }}

220

User Items

ImplicitUnsignedInit.ruleDo not initialize unsigned integer variables with signed constantsThis rule checks if you initialize unsigned integer variables with signed constants.

Reason for rule: Numeric constants have a type. Use the appropriate suffix to avoid undesirable implicit cast.

Examplevoid foo(){ unsigned int x = 21; /* Violation */ unsigned int y = -21; /* Violation */ unsigned int z = 21u; /* OK */

return;}

InitCharOutOfRange.ruleAvoid assigning out-of-range value to char typeThis rule checks for constants out of the legal range for the char type.

Reason for rule: The legal range of values of char type is -128 to 127.

Examplevoid Foo(){ char uVal = 157; // hit // ... return;}

InitPointerVar.ruleInitialize all pointer variablesThis rule checks if all of your pointer variables are initialized.

Reason for rule: Initializing pointer variables prevents dereferencing of uninitialized pointers.

Examplevoid foo() { int *i; // Violation int *k = 0; // Okay}

221

User Items

InitUnCharOutOfRange.ruleAvoid assigning out-of-range value to unsigned char typeThis rule checks for constants out of the legal range for the unsigned char type.

Reason for rule: The legal range of values of the unsigned char type is 0 to 255.

Examplevoid Foo(){ unsigned char uVal = 259; // hit // ... return;}

LineLength.rulePhysical lines shall be less than eighty charactersThis rule checks that physical lines are less than eighty characters.

Reason for rule: This rule promotes readability across various editors. Additionally, some printers will not print columns greater than 80 columns.

LocalVariableNames.ruleLocal variable names shall be lowercaseThis rule checks whether local variable names are proper lowercase.

Reason for rule: By standardizing the appearance of variables, you can more easily differentiate user-defined variables from constants.

Examplevoid foo() { int Count; //Violation int date; //OK};

222

User Items

LongConst.ruleUse capital 'L' instead of lowercase 'l' to indicate longThis rule checks whether you use capital “L” instead of lowercase ‘l’ to indicate long.

Reason for rule: Using capital “L’ to indicate long increases readability and correctness.

Note: This rule is enabled by default.

Examplevoid func(){ int i = 0; i = 341; // OK i = 34l; // Violation i = 34L; // OK}

MacroSize.ruleThe length of a macro should not exceed 10 linesThis rule checks whether the length of a macro exceeds 10 lines.

Reason for rule: Macros over 10 lines are hard to read.

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);

}

223

User Items

MacroWithinInclude.ruleDo not use macros in the include statement This rule checks that macros are not used in the include statement.

Reason for rule: Including header files with “#define” predefined makes code hard to read and under-stand.

Example#define HEADER_FILE(nr) "myHeader" #nr ".h"#include HEADER_FILE(12) /*Violation*/

ManyCases.ruleAvoid switch statements with many casesThis rule checks whether your code contains switch statements with many cases.

Reason for rule: Using many case statements makes code difficult to follow. More importantly, switches with many cases often indicate places where polymorphic behavior could better be used to provide different behavior for different types. Note that although the general principle is to avoid many cases in a switch, the actual cutoff point is arbitrary.

Examplevoid foo(int i) { 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; }}

224

User Items

MetricBlockofCode.ruleNumber of blocks of code per functionThis metric measures the number of blocks of code in a function. This rule applies only to the C++ pro-gramming language.

Reason for rule: “Code with many paths will be harder to understand and more likely to contain errors” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/Decem-ber 1999, pg. 34).

Examplevoid func(int i} { if (1) { // do something; } else { // do another; } do { } while(1); switch(i) { case 1: break; default: break; }}

MetricBreakEncap.ruleAvoid using global in member functionsThis metric measures the number of global variables referenced in your code’s member functions. This rule applies only to the C++ programming language.

Reason for rule: “Global references tend to break encapsulation and inhibit reuse. While global refer-ences may be difficult to eliminate entirely, they should be used as sparingly as possible.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleint globalVar = 1;class Foo {public: void func() { memberVar = GlobalVar; // Violation, global var is used here }private: int memberVar;};

225

User Items

MetricFuncCall.ruleNumber of function callsThis metric measures the number of function calls in each function. This rule applies only to the C++ programming language.

Reason for rule: “TFC [Total Function Calls] tallies the number of calls to methods and system func-tions within the system, class, or method. This metric measures size in a way that is more independent of coding style than the LOC [Lines Of Code] metric.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 32).

Exampleclass Base {};class Dev1 : public Base {};class Dev2 : public Dev1 {};

MetricInheritance.ruleClass inheritance levelThis metric measures the class inheritance level by calculating the number of base classes. This rule applies only to the C++ programming language.

Reason for rule: “An unnecessarily deep class hierarchy adds to complexity and can represent a poor use of the inheritance mechanism.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Base {};class Dev1 : public Base {};class Dev2 : public Dev1 {};

226

User Items

MetricMembers.ruleNumber of data member(s) per classThis metric measures the number of data members per class. This rule applies only to the C++ pro-gramming language.

Reason for rule: “The number of attributes in a class indicates the amount of data the class must maintain in order to carry out its responsibilities.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {public: int i;protected: int j;private: int k;};

MetricMethod.ruleNumber of method(s) per classThis metric measures the number of methods per class. This rule applies only to the C++ programming language.

Reason for rule: “The number of methods per class indicates the total level of functionality imple-mented by a class.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {public: void method1();protected: void method2();private: void method3();};

227

User Items

MetricParam.ruleNumber of parameter(s) per methodThis metric measures the number of parameters in each method. This rule applies only to the C++ pro-gramming language.

Reason for rule: “A high number of parameters indicates a complex interface to calling objects, and should be avoided.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 34).

Exampleclass Foo {public: // Violation so many parameters void func(int i, double d, float f, char c, Foo &);};

MetricPrivateMembers.ruleNumber of private data member(s) per classThis metric measures the number of private data members per class. This rule applies only to the C++ programming language.

Reason for rule: “The number of attributes in a class indicates the amount of data the class must maintain in order to carry out its responsibilities.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {private: int k;};

MetricPrivateMethod.ruleNumber of private methods per classThis metric measures the number of private methods per class. This rule applies only to the C++ pro-gramming language.

Reason for rule: “The number of methods per class indicates the total level of functionality imple-mented by a class.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {private: void method();};

228

User Items

MetricProtectedMembers.ruleNumber of protect data member(s) per classThis metric measures the number of protected data members per class. This rule applies only to the C++ programming language.

Reason for rule: “The number of attributes in a class indicates the amount of data the class must maintain in order to carry out its responsibilities.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {protected: int j;};

MetricProtectedMethod.ruleNumber of protected method(s) per classThis metric measures the number of protected methods per class. This rule applies only to the C++ programming language.

Reason for rule: “The number of methods per class indicates the total level of functionality imple-mented by a class.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {protected: void method();};

MetricPublicMembers.ruleNumber of public data member(s) per classThis metric measures the number of public data members per class. This rule applies only to the C++ programming language.

Reason for rule: “The number of attributes in a class indicates the amount of data the class must maintain in order to carry out its responsibilities.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {public: int i;};

229

User Items

MetricPublicMethod.ruleNumber of public method(s) per classThis metric measures the number of public methods per class. This rule applies only to the C++ pro-gramming language.

Reason for rule: “The number of methods per class indicates the total level of functionality imple-mented by a class.” (A Practical Guide to Object-Oriented Metrics by Mark Schroeder, IT Professional, November/December 1999, pg. 33).

Exampleclass Foo {public: void method();};

ModifyInCondition.ruleDo not use operator ++ or -- in the conditional expression of if, while, or switchThis rule checks whether you use operator ++ or -- in the conditional part of if, while, or switch.

Reason for rule: Using the operator ++ or -- in the conditional part of if, while, or switch can make code difficult to read and error prone.

Exampleint Foo (int iVar){ if (iVar-- && iVar<10) { // hit iVar += 10; } else { iVar -= 10; } return iVar;}

230

User Items

NameBool.ruleBegin all boolean type variables with 'b'This rule checks whether all of your boolean type variables begin with ‘b’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { bool Var; // Violation bool bVar; // OK}

NameClass.ruleBegin class names with an uppercase letterThis rule checks whether each class name begins with an uppercase letter. This rule applies only to the C++ programming language.

Reason for rule: When an entire development group agrees on a common convention, code becomes easier to read and understand.

Exampleclass foo {}; // Violationclass Foo {}; // OK

231

User Items

NameConflict.ruleAvoid internal or external name conflictThis rule checks for internal or external name conflict. This rule applies only to the C programming lan-guage.

Reason for rule: Internal or external name conflicts with a C++ reserved word will cause problems if the program is compiled with a C compiler. Most C compilers do not detect naming conflicts, so name conflicts can can lead to unpredictable program behavior.

Exampleint bool = 0;int catch = 0;int class = 0;int const_cast = 0;int delete = 0;int dynamic_cast = 0;int explicit = 0;int export = 0;int false = 0;int friend = 0;int inline = 0;int mutable = 0;int namespace = 0;int new = 0;int operator = 0;int private = 0;int public = 0;int protected = 0;int reinterpret_cast = 0;int static_cast = 0;int template = 0;int this = 0;int throw = 0;int true = 0;int try = 0;int typeid = 0;int typename = 0;int using = 0;int virtual = 0;int wchar_t = 0;

232

User Items

NameConstantVar.ruleBegin constant variables with ‘c’This rule checks whether each constant variable begins with ‘c’.

Reason for rule: When an entire development group agrees on a common convention, code becomes easier to read and understand.

Example// Constant variable names begin with 'c'const int Foo = 0; // Violationconst int cFoo = 0; // OK

NameDataMember.ruleBegin class data member names with ‘its’This rule checks if your class data member names begin with ‘its’. This rule applies only to the C++ pro-gramming language.

Reason for rule: When an entire development group agrees on a common convention, code becomes easier to read and understand.

Exampleclass Foo {private: int bar; // Violation int itsBar // OK};

NameDouble.ruleBegin all double type variable with 'd'This rule checks whether all of your double type variables begin with ‘d’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { double Var; // Violation double dVar; // OK}

233

User Items

NameEnumType.ruleEnumerated type name shall begin with an uppercase letter prefixed by the software element and suffixed by ‘_t’This rule checks whether the name of each enumerated type begins with an uppercase letter, is pre-fixed by the software element, and is suffixed by '_t' .

Reason for rule: When an entire development group agrees on a common convention, code becomes easier to read and understand.

Example// The names of abstract data types shall begin with// an uppercase, prefixed by software element and // suffixed by // '_t'.

enum LOC_PossibleColors_t { RED, BLUE, GREEN }; // OK

enum LOC_PossibleColors { RED, BLUE, GREEN }; // Violation

NameFloat.ruleBegin all float type variables with 'f'This rule checks whether all of your float type variables begin with ‘f’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { float Var; // Violation float fVar; // OK}

NameFunction.ruleBegin function names with uppercase letterThis rule checks whether each function name begins with an uppercase letter.

Reason for rule: When an entire development group agrees on a common convention, code becomes easier to read and understand.

Examplevoid foo(); // Violationvoid Foo(); // OK

234

User Items

NameGlobalVar.ruleBegin global variable names with ‘the’This rule checks whether each global variable name begins with “the”.

Reason for rule: When an entire development group agrees on a common convention, code becomes easier to read and understand.

Exampleint global_var; // Violationint theWindows; // OK

NameInt.ruleBegin all integer type variable with 'i'This rule checks whether all of your integer type variables begin with ‘i’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { int Var; // Violation int iVar; // OK}

NameIsFunction.rule'is' functions should return bool valuesThis rule checks if your ‘is’ function names begin with bool values.

Reason for rule: Beginning ‘is’ function names with bool values improves legibility and clarifies what the return value means.

Exampleint isPos(int x) { // Violation return x > 0;}

bool isPositive(int x) { // Okay return x > 0;}

235

User Items

NameLongInt.ruleBegin all long integer variables with 'li'This rule checks whether all of your long integer variables begin with ‘li’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { long int Var; // Violation long int liVar; // OK}

NamePointerVar.rulePrefix a variable type 'pointer' with a 'p' characterThis rule checks if your variable type pointer names begin with ‘p’.

Reason for rule: The legibility of code is better, and bugs can be avoided, by adding a prefix of a type to a variable

Exampleint *Foo; // Violationint *pFoo; // OK

NameShortInt.ruleBegin all short integer variables with 'si'This rule checks whether all of your short integer variables begin with ‘si’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { short int Var; // Violation short int siVar; // OK short Violation; // Violation short siOkay; // OK}

236

User Items

NameSignedChar.ruleBegin all signed character variables with 'c'This rule checks whether all of your signed character variables begin with ‘c’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { unsigned char Var; // Violation unsigned char ucVar; // OK}

NameString.ruleBegin all terminated characters string variables with 'sz'This rule checks whether all of your terminated characters’ string variables begin with ‘sz’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { char Var[] = "\n"; // Violation char szVar[] = "\n"; // OK}

}

NameStructType.ruleStruct type name shall begin with an uppercase letter prefixed by software element and suffixed by '_t'This rule checks the prefixes, suffixes, and first letters of your struct type names.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplestruct LOC_Position { }; // Violationstruct LOC_Position_t {} // OK

237

User Items

NameUnsignedChar.ruleBegin all unsigned character type variables with 'uc'This rule checks whether all of your unsigned character type variables begin with ‘uc’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { unsigned char Var; // Violation unsigned char ucVar; // OK}

NameUnsignedInt.ruleBegin all unsigned integer type variables with ‘ui’This rule checks whether all of your unsigned integer type variables begin with ‘ui’.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { unsigned int Var; // Violation unsigned int uiVar; // OK}

NameVariable.ruleBegin all variables with a lowercase letterThis rule checks if your variable names begin with a lowercase letter.

Reason for rule: Hungarian notation. When an entire development group agrees on a common con-vention, code becomes easier to read and understand.

Examplevoid foo() { int Local_var; // Violation int local; // OK}

238

User Items

NamingStructUnionMembers.ruleUse lowercase letters for structure and union member namesThis rule checks whether you use lowercase letters for structure and union member names.

Reason for rule: Using lowercase letters for structure and union member names will make it easier to recognize structure/union members.

Example//OKstruct date_foo1 { int dateMonth; int dateDay; int dateYear;};

//Violationstruct date_foo2 { int datemonth; int DateDay; int Dateyear; };

NoInputParamsInMacros.ruleNo input parameters in macrosThis rule checks whether a function like macros has parameters.

Reason for rule: Without parameters a function like macros may work in unpredicable ways.

Example#define A_PLUS_B (a+b) /*Violation*/

NonScalarTypedefs.ruleAppend names of non-scalar typedefs with "_t".Reason for rule: Following this convention will make it easier to recognize user-defined data types and maintain the software. This rule applies only to the C++ programming language.

Exampleclass MyClass { int count;};

typedef MyClass My_t; //OKtypedef MyClass My; //Violation

239

User Items

NullDefinition.ruleIncorrect NULL definitionThis rule checks whether your definition of void is (void *)0.

Reason for rule: Any other usage of NULL is misleading and error prone.

Example#define NULL 0 /*Violation*/#undef NULL#define NULL /*Violation*/#undef NULL#define NULL (void*)0 /*OK*/

NumberFunctionParam.ruleAvoid functions with more than 5 parametersThis rule checks for functions with more than 5 parameters.

Reason for rule: Avoiding functions with more than 5 parameters will reduce the amount of coupling between functions. If more parameters are needed, a structure could be used to hold related data and a pointer could be passed.

Examplevoid foo(int a, int b, int c, int d, int e, int f) // Violation{ }

NumberMacroParams.ruleMacros should not use more than 5 parametersThis rule checks that macros do not use more than 5 parameters.

Reason for rule: If a large number of parameters are passed to a macro, it may become hard to read and understand. If this occurs, it may be beneficial to break the macro down into multiple macros or make it into a function.

Example#define PLUS(a,b,c,d,e,f) (a+b+c+d+e+f) /*Violation*/

240

User Items

OneStatementPerLine.ruleOnly one statement shall be allowed per lineThis rule checks that there is only one statement per line.

Reason for rule: This rule promotes readability and maintainability by reducing code complexity.

Examplevoid foo(){ int i; char c; /*Violation*/

int ii; /*OK*/ char cc; }

OpEqualThis.ruleReturn reference to *this in operator= functionsThis rule checks whether you return reference to *this in operator= functions. This rule applies only to the C++ programming language.

Reason for rule: Returning reference to *this in operator= functions protects you from not know-ing 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.

Note: This rule is similar to item ecpp_15.

Example// See ECPP 15

class A{public: explicit A(int i = 0) : _i(i) {} void operator=(const A& a) // violation { if (&a == this) { return; } int _i = a._i; return; }private: int _i;};

241

User Items

ParenthesesInConditional.ruleLogical parts of a conditional expression shall be grouped with parentheses even if not logically requiredThis rule checks whether you are using your parentheses in logical expressions.

Reason for rule: This promotes readability by explicitly indicating the logical groups being compared.

Examplevoid foo() { int x = 1; int y = 1;

if ((x == 0) || (y == 0)) /*Ok*/{}if (x == 0 || y == 0) /*Violation*/{}}

ParenthesesInConditional2.ruleLogical parts of a conditional expression shall be grouped with parentheses even if not logically requiredThis rule checks whether you are using your parentheses in logical expressions.

Reason for rule: This promotes readability by explicitly indicating the logical groups being compared.

Examplevoid foo() {

int x = 1;int y = 1;

if ((x == 0) && (y == 0)) /*Ok*/{}if (x == 0 && y == 0) /*Violation*/{}

}

242

User Items

PartialStatementDefinition.ruleDo not define part of statementThis rule checks whether you are defining part of a statement.

Reason for rule: Defining a part of a statement makes code unreadable and is extremely error prone.

Example#define PARTIAL(a) ((a) * /*Violation*/

PassByValue.rulePass built-in types by value unless you are modifying themThis rule checks if your code passes arguments of built-in types by value, unless they should be modi-fied by functions.

Reason for rule: Passing arguments of built-in types by value improves the efficiency of your code.

Exampleint Foo(int i, int &j) { // Violation return i + j;}

int Bar(int i, int &j) { // Okay j += i; return j;}

243

User Items

PointerParamDereference.ruleDo not pass possibly null pointers as parametersThis rule checks if you dereference possibly null pointer parameters.

Dereferences of possibly null pointers may be protected by conditional statements or assertions that check that the pointer is not NULL. This rule reports all functions which are passed pointers.

Reason for rule: A dereferenced null pointer is a common cause of program failures.

Examplevoid Foo (int *ptr1, char *ptr2, float *ptrF)

{

*ptr1 = 10; // possibly null pointer dereference

ptr2 = 0;

if( ptrF==0) {

return;

}

*ptrF = 0; // OK

return;}

PublicInterface.ruleAvoid declaring class data member to be publicThis rule checks whether the public interface of your code contains member variables. This rule applies only to the C++ programming language.

Reason for rule: Legibility and maintainability.

Exampleclass Foo { public: int i; // Violation};class Foo {private: int i; // OK};

244

User Items

RedefControlStatements.ruleDo not redefine control statementsThis rule checks whether you are redefining control statements.

Reason for rule: Redefining control statements may cause unpredictable results.

Example#define if while /*Violation*/#define for if /*Violation*/#define else try /*Violation*/

RedefPrimitiveTypes.ruleDo not redefine primitive typesThis rule checks whether you are redefining primitive types.

Reason for rule: This increases code readability by avoiding the creation of new unnecessary types.

Example#define T30 char /* Complain */#define T31 unsigned char /* OK */

RedefTypes.ruleDo not redefine primitive types. Use typedef.This rule checks whether you are using typedef instead of “#define.”

Reason for rule: Some compilers could have predefined types (INT, VOID). Using typedef instead of “#define”' guarantees that you will not redefine it.

Example#define INT int /*Violation*/

245

User Items

ReferenceInitialization.ruleDo not initialize a reference to an object whose address can be changedThis rule checks whether you initialize a reference to refer to an object whose address can be changed. This rule applies only to the C++ programming language.

Reason for rule: The reference to an object in the free store can be deleted via a pointer, and conse-quently can refer to an object with a null address.

Examplevoid foo(){ int *ptr = 0;

int &rptr = *ptr; //Violation // assignment through null rptr = 10;}

SingularSwitchStatement.ruleAvoid switch statements with only one caseThis rule checks for switch statements with only one case statement.

Reason for rule: switch statements with only one case statement could be described using an if statement.

Examplevoid foo (){ int i = 0; /* ... */ switch(i) /* Violation */ { case 0: break; default: break; }

return;}

246

User Items

SourceFileSize.ruleAvoid source files that are longer than 500 linesThis rule checks for source files that are longer than 500 lines.

Reason for rule: Larger files are more difficult to edit and maintain than smaller files.

SourceNamingConvention.ruleUse the ".c" extension for names of source filesThis rule checks whether C source files use the “.c” extension.

Reason for rule: This convention is common practice and is mandated by some compilers.

SpaceInAssignmentOp.ruleThere shall be a single ASCII space character preceding and following assignment operatorsThis rule checks whether there is a single ASCII space character preceding and following assignment operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Exampleint x = 1; /*Ok*/int y = 1; /*Violation*/int z=1; /*Violation*/

SpaceInAssignmentOp2.ruleThere shall be a single ASCII space character preceding and following assignment operatorsThis rule checks whether there is a single ASCII space character preceding and following assignment operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Exampleint x = 1; /*Ok*/int y = 1; /*Violation*/int z=1; /*Violation*/

247

User Items

SpaceInBitwiseOp.ruleThere shall be a single ASCII space character preceding and following bitwise operators This rule checks whether there is a single ASCII space character preceding and following bitwise oper-ators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() { int z = 73; int y=0; y=z | 0x0f; /*Ok*/ y=z|0x0f; /*Violation*/ y=z | 0x0f; /*Violation*/}

SpaceInBitwiseOp2.ruleThere shall be a single ASCII space character preceding and following bitwise operators This rule checks whether there is a single ASCII space character preceding and following bitwise oper-ators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() { int z = 73; int y=0; y=z | 0x0f; /*Ok*/ y=z|0x0f; /*Violation*/ y=z | 0x0f; /*Violation*/}

248

User Items

SpaceInConditional.ruleThere shall be a single ASCII space character between a conditional statement and its opening parenthesisThis rule checks whether there is a single space ASCII space character between a conditional state-ment and its opening parenthesis.

Reason for rule: This promotes readability by providing a clear indication that a statement is a condi-tional statement versus a function, and by providing a clear break between the conditional keyword and its associated expression.

Examplevoid foo(){ int x=1; int y=1; if (x == y) /*Ok*/ { }

while(x == y) /*Violation*/ { }}

249

User Items

SpaceInConditional2.ruleThere shall be a maximum of 1 ASCII space character following the opening parenthesisThis rule checks whether there is a maximum of 1 ASCII space character following the opening paren-thesis.

Reason for rule: A maximum of 1 ASCII space after the opening parenthesis improves readability.

Examplevoid foo(){ int x=1; int y=1;

if (x == y) /*Ok*/ { }

if ( x == y ) /*Ok*/ { } if( x == y ) /*Violation*/ { }}

SpaceInConditionalOp.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks that there is a single ASCII space character preceding and following conditional oper-ators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {int j=10;int i=1;

j = ( i < 0 ) ? ( -i ) : ( i ); /*Violation*/j = ( i < 0 )?( -i ) : ( i ); /*Violation*/j = ( i < 0 ) ? ( -i ) : ( i ); /*Ok*/

}

250

User Items

SpaceInConditionalOp2.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks whether there is a single ASCII space character preceding and following conditional operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {int j=10;int i=1;

j = ( i < 0 ) ? ( -i ) : ( i ); /*Violation*/j = ( i < 0 )?( -i ) : ( i ); /*Violation*/j = ( i < 0 ) ? ( -i ) : ( i ); /*Ok*/

}

SpaceInLogicalOp.ruleThere shall be a single ASCII space character preceding and following logical operators This rule checks whether there is a single ASCII space character preceding and following logical oper-ators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() { int x = 1; int y = 1;

if(x || y) /*OK*/ { } if(x||y) /*Violation*/ { }

if(x || y) /*Violation*/ { }}

251

User Items

SpaceInRelationalOp.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks whether there is a single ASCII space character preceding and following conditional operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {

int x = 1;

if(x == 1) /*OK*/ { }

if(x==1) /*Violation*/ { } if(x == 1) /*Violation*/ { }

}

252

User Items

SpaceInRelationalOp2.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks whether there is a single ASCII space character preceding and following conditional operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {

int x = 1;

if(x != 1) /*OK*/ { }

if(x!=1) /*Violation*/ { } if(x != 1) /*Violation*/ { }

}

253

User Items

SpaceInRelationalOp3.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks whether there is a single ASCII space character preceding and following conditional operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {

int x = 1;

if(x >= 1) /*OK*/ { }

if(x>=1) /*Violation*/ { }

if(x >= 1) /*Violation*/ { } }

254

User Items

SpaceInRelationalOp4.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks whether there is a single ASCII space character preceding and following conditional operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {

int x = 1;

if(x <= 1) /*OK*/ { }

if(x<=1) /*Violation*/ { } if(x <= 1) /*Violation*/ { }

}

255

User Items

SpaceInRelationalOp5.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks whether there is a single ASCII space character preceding and following conditional operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {

int x = 1;

if(x > 1) /*OK*/ { }

if(x>1) /*Violation*/ { } if(x > 1) /*Violation*/ { }

}

256

User Items

SpaceInRelationalOp6.ruleThere shall be a single ASCII space character preceding and following conditional operatorsThis rule checks whether there is a single ASCII space character preceding and following conditional operators.

Reason for rule: This convention promotes readability by clearly separating the operands from the operator.

Examplevoid foo() {

int x = 1;

if(x < 1) /*OK*/ { }

if(x<1) /*Violation*/ { } if(x < 1) /*Violation*/ { }

}

SpaceInSelector.ruleThere shall be no white space preceding or following a primary operatorThis rule checks whether there is no white space preceding or following a primary operator.

Reason for rule: 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.

Examplestruct MyStruct { int x;};

void foo(struct MyStruct* myObj) { // ... myObj->x; /*Ok*/ myObj-> x; /*Violation*/}

257

User Items

SpaceInSelector2.ruleThere shall be no white space preceding or following a primary operatorThis rule checks whether there is no white space preceding or following a primary operator.

Reason for rule: 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.

Examplechar tab1[20]; /*Ok*/char tab2 [20]; /*Violation*/

SpacesAfterComma.ruleThere shall be a single ASCII space character following all commasThis rule checks whether there is a single ASCII space character following all commas.

Reason for rule: Since commas delineate individual statements, a space shall be used to highlight this fact. This greatly improves the readability of 'C'.

Exampleint x, y; /*Ok*/int xx,yy; /*Violation*/int xxx, yyy; /*Violation*/

SpacesAfterSemicolon.ruleThere shall be a single ASCII space character following all semicolonsThis rule checks whether there is a single ASCII space character following all semicolons.

Reason for rule: Since semicolons delineate individual statements, a space shall be used to highlight this fact. This greatly improves the readability of 'C'.

Examplevoid foo() { int i;

for ( i = 0; i <= 10; i++) /*OK*/ { }

for ( i = 0;i <= 10;i++) /*Violation*/ { }}

258

User Items

SpacesAfterUnaryOperator.ruleThere should be no white space between a unary operator and its operandThis rule checks whether there is no white space between a unary operator and its operand.

Reason for rule: This promotes continuity in the relationship between the operators and their associ-ated operand. These operators act solely on their operand and cannot be considered separately from it.

Examplevoid foo(){

int i=0;--i; //OK-- i; //Violation

}

SpacesBeforeComma.ruleThere shall be a single ASCII space character following all commasThis rule checks whether there is a single ASCII space character following all commas.

Reason for rule: Since commas delineate individual statements, a space shall be used to highlight this fact. This greatly improves the readability of 'C'.

Example Onevoid foo() { int z = 73; int y=0; y=z | 0x0f; /*Ok*/ y=z|0x0f; /*Violation*/ y=z | 0x0f; /*Violation*/

Example Twovoid foo(){int i = 0;int j = 0;for(i = 0; i<5; i++,j++){} //violationfor(i = 0 ; i<5; i++, j++){} //OK

}

259

User Items

SpacesBeforeUnaryOperator.ruleThere shall be no white space between a unary operator and its operandThis rule checks whether there is no white space between a unary operator and its operand.

Reason for rule: This promotes continuity in the relationship between the operators and their associ-ated operand. These operators act solely on their operand and cannot be consider separately from it.

Examplevoid foo() { int y = 0; y++; /*Ok*/ y ++; /*Violation*/}

StatementParenthesis.ruleThere shall be no white spaces between the "return" or "sizeof" statements and its opening parenthesisThis rule checks for white spaces between the “return” and “sizeof” statements.

Reason for rule: This promotes the relationship between the statement and its argument.

Examplevoid foo() { sizeof(int); /*Ok*/ sizeof (int); /*Violation*/}

StatementParenthesis2.ruleThere shall be no white spaces between the "return" or "sizeof" statements, arguments, or expressionsThis rule checks whether there are no white spaces between the “return” and “sizeof” statements, argu-ments, or expressions.

Reason for rule: This promotes the relationship between the statement and its argument.

Examplevoid foo() { sizeof(int); /*Ok*/ sizeof( int ); /*Violation*/}

260

User Items

StatementParenthesis3.ruleParentheses shall be used with the "return" and "sizeof" statementsThis rule checks whether parentheses are used with the “return” and “sizeof” statements.

Reason for rule: This promotes the relationship between the statement and its argument.

Example#define true 1#define false 0

int foo() { return true; /*Violation*/}

int goo() { return(true); /*Ok*/}

StructKeyword.ruleDo not use the ‘struct’ keyword to declare a variable in C++This rule checks whether your C++ code uses struct keywords to declare a variable. This rule applies only to the C++ programming language.

Reason for rule: Using the struct keyword to declare a variable improves code readability.

Example// struct keyword is unnecessary in C++ when declaring // a variable.struct Position_t {}struct Position_t Pos1; // ViolationPosition_t Pos2; // OK

261

User Items

ThrowDestructor.ruleDo not throw from within destructorThis rule checks if you throw from within a destructor. This rule is for C++ programming language only.

Reason for rule: Throwing from within a destructor may lead to memory leaks and improper object destruction. Note: This rule is enabled by default.

Exampleclass Foo{public: Foo() {} ~Foo() { // Violation throw; }};

TooManyFields.ruleAvoid structs, unions, or classes with more than 20 fieldsThis rule checks whether structs, unions, or classes have more than 20 fields. Reason for rule: Infor-mational.

Examplestruct _tA{ int i0; int i1; int i2; int i3; int i4; int i5; int i6; int i7; int i8; int i9; int i10; int i11; int i12; int i13; int i14; int i15; int i16; int i17; int i18; int i19; int i20; // more than 20 int i21;};

262

User Items

TrueDefinition.ruleIf TRUE is to be defined, & is not already defined, TRUE should be 1This rule checks whether TRUE is defined as 1.

Reason for rule: Any other use of TRUE is misleading and cannot be guaranteed to work predictably.

Example#define TRUE 0 /*Violation*/#undef TRUE#define TRUE /*Violation*/#undef TRUE#define TRUE 1 /*Ok*/

TrueTypedef.ruleIf TRUE is to be defined, & is not already defined, TRUE should be 1.This rule checks whether you defined TRUE as 1.

Reason for rule: Any other use of TRUE is misleading and cannot be guaranteed to work predictably.

Example#ifndef TRUEtypedef enum { FALSE = 0,TRUE = 3 /*Violation*/} BOOL ;#endif

TypeModifiersAfterTypes.ruleStorage type modifiers shall be associated with the type, not the variableThis rule checks whether storage type modifiers are associated with the type, not the variable.

Reason for rule: Following this convention increases readability and makes code easier to under-stand.

Exampleint static i; /*Violation*/static char j; /*Ok*/

263

User Items

TypeModifiersAfterValue.ruleStorage type modifiers shall be associated with the type, not the variableThis rule checks whether storage type modifiers are associated with the type, not with the variable.

Reason for rule: Following this convention increases readability and makes code easier to under-stand.

Examplestatic char j; /*Ok*/static i; /*Violation*/

UnionFieldNotDefined.ruleDefine fields for union declarationsThis rule checks for union declarations that do not have any defined fields.

Reason for rule: Informational.

Exampleunion UNKNOWN // hit{};

UnnecessaryCast.ruleAvoid unnecessary type castingThis rule checks if your code contains unnecessary casts. This rule applies only to the C++ program-ming language.

Reason for rule: It is not necessary to explicitly upcast to a base class. Removing unnecessary casts makes code easier to read.

Exampleclass Base { /* ... */ };class Derived : public Base { /* ... */ };void Func() { Derived *d = new Derived(); Base *b = (Base *)d; // Violation Base *b1 = d; // Okay}

264

User Items

UnnecessaryEqual.ruleRemove unnecessary “==true” in Boolean functionsThis rule checks if your code contains unnecessary “==true”s.

Reason for rule: Checking bool expression equality with true is unnecessary. Removing unneces-sary "== true"s increases legibility and efficiency.

Examplebool ret() { return true;}

bool ret2() { return ret() == true; // Violation == is unnecessary.}

UnreachableCode.ruleDo not write unreachable codeThis rule checks for unreachable code in an if statement.

Reason for rule: Informational.

Examplevoid foo (){ int i = 0;

/* ... */

if(1) /* Violation */ { i = 1; } else { i = 2; }

return;}

265

User Items

UnreachableCode2.ruleDo not write unreachable codeThis rule checks for unreachable code in an if statement.

Reason for rule: Informational.

Examplevoid foo (){ int i = 0;

/* ... */

if(1) /* Violation */ { i = 1; } else { i = 2; }

return;}

UnusedLocalVariable.ruleAvoid unused local variablesThis rule checks whether any of the declared local variables were not used.

Reason for rule: Eliminating unused local variables increases efficiency and legibility.

Examplevoid func() { int i = 0; // Possible violation i is declared but not used}

266

User Items

UnusedParameter.ruleEliminate unused parametersThis rule checks for unused parameters.

Reason for rule: Eliminating unused parameters improves legibility and increases efficiency.

Exampleint Foo(int i, int k) { // Violation, k is not used. i = 5; return i;}

int Bar(int i, int j) { // Okay i += j; return i;}

UnusedPrivateMember.ruleEliminate unused private member variablesThis rule checks for unused private member variables. This rule applies only to the C++ programming language.

Reason for rule: Eliminating unused private member variables improves legibility and increases effi-ciency.

Exampleclass Foo {public: Foo(): x(0), y(0) { } int getX() { return x; }private: int x; int y; // Violation, y is declared but not used.};

267

User Items

UseParenthesesInMacros.ruleIn a function such as macros, before multiplication or division, use parenthesesThis rule checks whether parentheses are used before division or multiplication in macros.

Reason for rule: This promotes readability by highlighting the arguments of macros.

Example#define MULTI_2(x) (x*2) /*Violation*/

UsePositiveLogic.ruleUse positive logic rather than negative logic whenever practicalThis rule checks for use of negative logic. Reason for rule: The use of many logical nots "!" within an expression makes the expression difficult to understand and maintain.

Examplevoid foo( int *j) { if(j!=0){ //Violation (*j)++; } if(j==0){ } else { //OK (*j)++; }}

268

Ellemtel (Telecom Industry) Items

Rule

Access(Acces

Assign(Assign

ith a

Assign(Assign

umer-

Assign(Assign

aged

Assign(Assign

er-

Classe(Classe

m-

Classe(Classe

m-

Classe(Classe

lass

Comme(Comm

.

Comme(Comm

Comme(Comm s

Comme(Comm

is, a

Ellemtel (Telecom Industry) ItemsEllemtel (Telecom Industry) ItemsThis is a set of rules based on a C++ style guide originated by Ellemtel Telecom Systems, StockholmSweden. It is used widely in the telecommunications industry.

Notes• All Ellemtel rules are disabled by default.

• All rules are for C and C++ unless otherwise noted in the rule itself.

• The Severity Level for all Ellemtel rules is Violation unless otherwise noted in the rule text.

• In the left-hand column in the following table, the Ellemtel name is given in parentheses below the Parasoft name for the rule.

• The abbreviation “Rec” stands for Recommended.

RuleID Description

Rightss_Rights_Rule_22)

4027 Never specify public or protected member data in aclass.

ingNames1ing_Names_Rule_13)

4012 The names of variables and functions must begin wlowercase letter.

ingNames2ing_Names_Rule_14)

4013 The names of classes, structures, typedef, and enated types are to begin with an uppercase letter.

mentOperators1ment_Operators_Rule_27)

4035 A class which uses new to allocate instances manby that class must define an assignment operator.

mentOperators2ment_Operators_Rec_34)

4036 An assignment operator ought to return a const refence to the assigning object.

s1s_Rule_20_1)

4014 In class definition, public, protected and private mebers must be declared in that order.

s2s_Rule_20_2)

4015 In class definition, public, protected and private mebers must be declared in that order.

s3s_Rule_21)

4016 No member functions are to be defined within the cdefinition.

nts1ents_Rec_8)

4006 Each function should be preceeded by a comment

nts2ents_Rec_9)

4007 Use // for comments. Do not use /* and */

nts3ents_Rule_4)

4004 Every file that contains source code must be docu-mented with an introductory comment that provideinformation on the file name and its contents.

nts4ents_Rule_5)

4005 All files must include copyright information — that line starting with // Copyright

269

Ellemtel (Telecom Industry) Items

Compo(Comp

the after

Consta(Const

ever

Consta(Const

olic

Constr(Const

Constr(Const

Constr(Const

ed by

Constr(Const

ich tor.

DataAb(Data_A

clara-

FlowCo(Flow_

FlowCo(Flow_

FlowCo(Flow_

FlowCo(Flow_

FlowCo(Flow_

FlowCo(Flow_

FlowCo(Flow_

or

FlowCo(Flow_

rmi-

FlowCo(Flow_

ranch

FlowCo(Flow_

Formal(Forma

n the be

undStatementsound_Statements_Rec_24)

4020 Braces which enclose a block are to be placed on same column, on separate lines directly before andthe block.

nts1ants_Rule_36)

4060 Constants are to be defined using const or enum; nusing #define.

nts2ants_Rule_37)

4061 Avoid the use of numeric values in code; use symbvalues instead.

uctors&Destructors1ructors_and_Destructors_Rec_33_1)

4033 Avoid the use of global objects in constructors.

uctors&Destructors2ructors_and_Destructors_Rec_33_2)

4034 Avoid the use of global objects in destructors.

uctors&Destructors3ructors_and_Destructors_Rule_25)

4031 A class which uses new to allocate instances mnagthat class must define a copy constructor.

uctors&Destructors4ructors_and_Destructors_Rule_26)

4032 All classes which are used as base classes and whhave virtual functions must define a virtual destruc

stractionPortbstraction_Port_Rec_1)

4072 Do not directly use the pre-defined data types in detions

ntrolStatements1Control_Statements_Rec_25_1)

4021 Always use curly brackets after if construction.

ntrolStatements2Control_Statements_Rec_25_2)

4022 Always use curly brackets after else construction.

ntrolStatements3Control_Statements_Rec_25_3)

4023 Always use curly braces after for construction.

ntrolStatements4Control_Statements_Rec_25_4)

4024 Always use curly brackets after while construction.

ntrolStatements5Control_Statements_Rec_25_5)

4025 Always use curly brackets after do construction.

ntrolStructure1Control_Structures_Rec_53)

4067 Avoid the use of continue.

ntrolStructure2Control_Structures_Rec_55)

4068 Do not write logical expressions of the type if(test) if(!test) when test is a pointer.

ntrolStructure3Control_Structures_Rule_47)

4064 The code following a case label must always be tenated by a break statement.

ntrolStructure4Control_Structures_Rule_48)

4065 A switch statement must always contain a default bwhich handles unexpected cases.

ntrolStructure5Control_Structures_Rule_49)

4066 Never use goto.

Argumentsl_Arguments_Rule_32)

4054 If identifiers are given for any of the parameters, theidentifiers used in declaration and definition shouldidentical.

270

Ellemtel (Telecom Industry) Items

Functio(Functi

Functio(Functi

nota-

Functio(Functi

.

Functio(Functi

the

Functio(Functi

ction

Genera(Gener

Genera(Gener

Include(Includ

n-

Include(Includ

Include(Includ

irec-

Include(Includ

re-

InlineF(Inline_

InlineF(Inline_

InlineF(Inline_

btain

Membe(Memb

const

Memor(Memo

Memor(Memo

Memor(Memo

en

Miscell(Miscel

nArguments1on_Arguments_Rec_41)

4053 Avoid functions with many arguments.

nArguments2on_Arguments_Rule_31)

4052 Do not use unspecified function arguments (ellipsistion).

ns1ons_Rec_20)

4017 Always provide the return type of function explicitly

ns2ons_Rec_22)

4018 In function definition, the return type of the functionshould be written on a separate line directly abovefunction name.

ns3ons_Rec_23)

4019 Always write the left parenthesis directly after a funname.

l1al_Rec_47_1)

4058 Long functions have disadvantages

l2al_Rec_47_2)

4059 Avoid long and complex functions.

Files1e_Files_Rec_12)

4010 Every implementation file should declare a local costant string that describes the file.

Files2e_Files_Rec_13)

4011 Never include other files in an .icc file.

Files3e_Files_Rule_10)

4009 Never specify relative Unix file names in #include dtives.

Files4e_Files_Rule_7)

4008 Every include file must contain a mechanism that pvents multiple inclusion of the file.

unctions1Functions_Rec_31_1)

4029 Constructors must not be inline

unctions2Functions_Rec_31_2)

4030 Destructors must not be inline

unctions3Functions_Rule_35)

4057 Do not use the preprocessor directive #define to omore efficient code; instead use inline functions.

rFunctionsReturnTypeser_Function_Return_Types_Rule_29)

4051 A public member function must never return a non-reference or pointer to member data.

yAllocation1ry_Allocation_Rec_57)

4071 Avoid global data if at all possible.

yAllocation2ry_Allocation_Rule_50)

4069 Do not use malloc, realloc, or free.

yAllocation3ry_Allocation_Rule_51)

4070 Always provide empty brackets ("[ ]") for delete whdeallocating arrays.

aneouslaneous_Rec_27)

4026 Do not use spaces around '.' or '->'.

271

Ellemtel (Telecom Industry) Items

Naming(Namin

of the

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Operat(Opera

Pointer(Pointe

pera-

Pointer(Pointe

Pointer(Pointe

pera-es in

Pointer(Pointe

ossi-

FilesgFiles_Rec_7)

4004 An include file for a class should have a file name form <class name> + extension.

orOverloading1tor_Overloading_Rec_36_1)

4037 Do not overload operator+=

orOverloading2tor_Overloading_Rec_36_2)

4038 Do not overload operator-=

orOverloading3tor_Overloading_Rec_36_3)

4039 Overload operator != if you overload operator ==.

orOverloading4tor_Overloading_Rec_36_4)

4040 Overload operator == if you overload operator !=.

orOverloading5tor_Overloading_Rec_36_5)

4041 Overload operator || if you overload operator &&.

orOverloading6tor_Overloading_Rec_36_6)

4042 Overload operator && if you overload operator ||.

orOverloading7tor_Overloading_Rec_36_7)

4043 Overload operator > if you overload operator <.

orOverloading8tor_Overloading_Rec_36_8)

4044 Overload operator < if you overload operator >.

orOverloading9tor_Overloading_Rec_36_9)

4045 Overload operator >= if you overload operator <=.

orOverloading10tor_Overloading_Rec_36_10)

4046 Overload operator <= if you overload operator >=.

orOverloading11tor_Overloading_Rec_36_11)

4047 Overload operator -- if you overload operator ++.

orOverloading12tor_Overloading_Rec_36_12)

4048 Overload operator ++ if you overload operator --.

orOverloading13tor_Overloading_Rec_36_13)

4049 Overload operator - if you overload operator +.

orOverloading14tor_Overloading_Rec_36_14)

4050 Overload operator + if you overload operator -.

ArithmeticPort1r_Arithmetic_Port_Rec_17)

4085 Avoid using shift operations instead of arithmetic otions.

ArithmeticPort2r_Arithmetic_Port_Rec_18)

4086 Avoid pointer arithmetic

s&References1rs_and_References_Rec_26)

4087 The dereference operator * and the "address-of" otor & should be directly connected to the type namdeclaration and definition.

s&References2rs_and_References_Rec_48)

4063 Pointers to pointers should be avoided whenever pble.

272

Ellemtel (Telecom Industry) Items

Return(Return

Return(Return

to a

SizeOfT(Size_o

SizeOfT(Size_o

SizeOfT(Size_o

SizeOfT(Size_o

SizeOfT(Size_o

SizeOfT(Size_o

SizeOfT(Size_o

SizeOfT(Size_o

Structu(Struct

lass

Structu(Struct

Structu(Struct

e file

Structu(Struct

".icc"

TypeCo(Type_

ter

TypeCo(Type_

orter

TypeCo(Type_

TypeCo(Type_

Variabl(Variab

ration

Types&Values1_Types_and_Values_Rule_33)

4055 Every function shall have an explicit return type.

Types&Values2_Types_and_Values_Rule_34)

4056 A function must never return a pointer or referencelocal variable.

ypesPort1f_Types_Port_Rec_2_1)

4073 Attempt to cast long pointer to int pointer.

ypesPort2f_Types_Port_Rec_2_2)

4074 Attempt to assign long value to int.

ypesPort3f_Types_Port_Rec_2_3)

4075 Function cast long to int

ypesPort4f_Types_Port_Rec_2_4)

4076 Constant is an unsigned int

ypesPort5f_Types_Port_Rec_2_5)

4077 Constant is an unsigned int

ypesPort6f_Types_Port_Rec_2_6)

4078 Assign an int literal to long.

ypesPort7f_Types_Port_Rec_2_7)

4079 Attempt to cast an int pointer as a long pointer.

ypesPort8f_Types_Port_Rec_2_8)

4080 32-bit multiplication

reOfCode1ure_of_Code_Rec_3)

4002 An include file should not contain more than one cdefinition.

reOfCode2ure_of_Code_Rule_1)

4000 User include files should have the extension ".hh"

reOfCode3ure_of_Code_Rule_2)

4001 Implementation files in C++ should always have thname extension ".cc".

reOfCode4ure_of_Code_Rule_3)

4003 Inline definition files always have the file extension

nversionsPort1Conversions_Port_Rec_6_1)

4081 Be careful not to make type conversions from shortype to longer type.

nversionsPort2Conversions_Port_Rec_6_2)

4082 Be careful not to make type conversions from a shtype to a longer one.

nversionsPort3Conversions_Port_Rec_6_3)

4083 Attempt to cast long value to double.

nversionsPort4Conversions_Port_Rec_7)

4084 Do not cast a pointer as an int.

esles_Rule_39)

4062 Each variable is to be declared in a separate declastatement.

273

Ellemtel (Telecom Industry) Items

AccessRights.ruleNever specify public or protected member data in a class.The use of public variables is discouraged because a public variable represents a violation of one of the basic principles of object-oriented programming, namely, encapsulation of data.

For example, if there is a class of the type BankAccount, in which account_balance is a public variable, the value of this variable may be changed by any user of the class.

However, if the variable has been declared private, its value may be changed only by the member func-tions of the class. An arbitrary function in a program can change public data which may lead to errors that are difficult to locate. If public data is avoided, its internal representation may be changed without users of the class having to modify their code.

A principle of class design is to maintain the stability of the public interface of the class. The implemen-tation of a class should not be a concern for its users. The use of protected variables in a class are not recommended, since its variables become visible to its derived classes.

The names of types or variables in a base class may then not be changed since the derived classes may depend on them. If a derived class, for some reason, must access data in its base class, one solu-tion may be to make a special protected interface in the base class, containing functions which return private data. This solution would not imply any degradation of performance if the functions are defined inline.

Reason for rule: A public variable represents a violation of one of the basic principles of object-ori-ented programming, namely, encapsulation of data.

274

Ellemtel (Telecom Industry) Items

Exampleclass Test1{public: int i; // Violation};

class Test2{protected: int i; // Violation};

class Test3{private: int i; // Ok };

class Test4{public: int getI(); // Ok};

class Test5{protected: int getI(); // Ok};

class Test6{private: int getI(); // Ok};

OutputUse only private member variable.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.1 Considerations regarding Access Rights - Rule 22

275

Ellemtel (Telecom Industry) Items

AssigningNames1.ruleThe names of variables and functions must begin with a lowercase letter.

Examplevoid Foo(); // violationvoid foo2(); // ok

void test() {

int I; // violation int j; // ok

}

OutputThe names of variables and functions must begin with a lowercase letter.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 5 Assigning Names - Rule 13

AssigningNames2.ruleThe names of classes, structures, typedef, and enumerated types are to begin with an uppercase letter.

Example

class Test1{}; // OK class badClass{}; // Violation

OutputThe names of classes, structures, typedef, and enumerated types are to begin with an uppercase letter.

ReferenceOrigin: Ellemtel Coding Standards

http:www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 5 Assigning Names - Rule 14

276

Ellemtel (Telecom Industry) Items

AssignmentOperators1.ruleA class which uses new to allocate instances managed by that class must define an assignment operator.

Example// Violationclass Test1{public: Test1();private: int *p;

};

Test1::Test1() { p = new int;}

// Ok

class Test2{public: Test2(); Test2(Test2&);private: int *p;

};

Test2::Test2() { p = new int;

}

OutputA class which uses new must define an assignment operator.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.6 Asignments Operators - Rule 27

277

Ellemtel (Telecom Industry) Items

AssignmentOperators2.ruleAn assignment operator ought to return a const reference to the assigning object.

Example

// Okclass TestOk {public: const TestOk& operator=(const TestOk&);

};

// Violationclass Test1 {public: void operator=(const Test1&);

};

// Violationclass Test2 {public: Test2& operator=(const Test2&);

};

OutputAn assignment operator ought to return a const reference to the assigning object.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.6 Assignment Operators - Rec. 34

278

Ellemtel (Telecom Industry) Items

Classes1.ruleIn class definition, public, protected and private members must be declared in that order.

Exampleclass Test1 { // Violation

protected: void foo2();

private: void foo3();

public: void foo4();

};

OutputPublic section must be before protected and private sections.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.1 Classes - Rule 20

279

Ellemtel (Telecom Industry) Items

Classes2.ruleIn class definition, public, protected and private members must be declared in that order.

Exampleclass Test1 { // Violation

public: void foo4();

private: void foo3();

protected: void foo2();

};

OutputProtected section must be before private section.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.1 Classes - Rule 20

280

Ellemtel (Telecom Industry) Items

Classes3.ruleNo member functions are to be defined within the class definition.

Exampleclass TestClass1{public: void foo() {}; // Violation void foo2(); // Ok };

void TestClass1::foo2() { // Ok}

OutputNo member functions are to be defined within the class definition.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.1 Classes - Rule 21

281

Ellemtel (Telecom Industry) Items

Comments1.ruleEach function should be preceeded by a comment.

Example

// comment with description for foo() function.void foo(); //Ok

void foo2(); //Violation

// comment with description for foo() function.void foo() //Ok{}

void foo2() //Violation{}

OutputThere is no comment before function.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.3 Comments - Rec. 8

Comments2.ruleUse // for comments. Do not use /* and */Reason for rule: 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 debug-ging phases. C++, however, does not allow comments to be nested using /* */.

Example

// good comment/* do not use this comment style */

OutputUse // comments only.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.3 Comments - Rec. 9

282

Ellemtel (Telecom Industry) Items

Comments3.ruleEvery file that contains source code must be documented with an introductory comment that provides information on the file name and its contents.

Example

// File: <short description of the file>

OutputDocument filename with some introductory comment.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.3 Comments - Rule 4

Comments4.ruleAll files must include copyright information — that is, a line starting with // Copyright

OutputAdd copyright information to filename.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.3 Comments - Rule 5

283

Ellemtel (Telecom Industry) Items

CompoundStatements.ruleBraces which enclose a block are to be placed on the same column, on separate lines directly before and after the block.

Example

// Badvoid foo1(){}

// Okvoid foo2(){}

// Badvoid foo3(){}

// Badvoid foo4() {

int i; // Bad if (i>0) { } else { }}

class Test { // Bad};

// Goodvoid foo5() {

int i; if (i>0) { // ... } else {

// ... } }

284

Ellemtel (Telecom Industry) Items

// badclass Test2 { private:

};

// Okclass Test3 { // ...

};

// okclass Test4 { // ...

}; // ...

// bad class Test5 { // ...

int k;}; // ...

OutputOutput 1Opening { and closing } should be on the same column.

Output 2Opening { should be alone on the line.

Output 3Closing } should be alone on the line.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style Classes - 6.3 Compound Statements- Rec. 24

285

Ellemtel (Telecom Industry) Items

Constants1.ruleConstants are to be defined using const or enum; never using #define.Reason for rule: The preprocessor performs a textual substitution for macros in the source code which is then compiled. This has a number of negative consequences.

For example, if a constant has been defined using #define, the name of the constant is not recog-nized in many debuggers. If the constant is represented by an expression, this expression may be evaluated differently for different instantiations, depending on the scope of the name. In addition, mac-ros are, at times, incorrectly written.

Example// Violation#define PI 3.1416

OutputConstats are to be defined using const or enum; never using #define.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 10 Constants - Rule 36

Constants2.ruleAvoid the use of numeric values in code; use symbolic values instead.

Example#define buff 256#define OK 1

enum color{ RED = 0, BLUE = 1, GREEN = 2 /*...*/};

void foo() { int tabColorsNew[256]; /*Violation*/ int tabColors[buff]; /*Ok*/

if ( tabColors[0] == 1 ) /*Violation*/ { /*...*/

286

Ellemtel (Telecom Industry) Items

}

if ( tabColors[RED] == OK ) /*Ok*/ { /*...*/ } }

OutputHard coded value: $name

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 10 Constants - Rule 37

287

Ellemtel (Telecom Industry) Items

Constructors&Destructors1.ruleAvoid the use of global objects in constructors.

Exampleint globalvar=0;bool alreadyUsed=false;

class Test{ public: Test(); ~Test();};

Test::Test() { // Violation globalvar++; alreadyUsed=true;}

Test::~Test() { // Violation globalvar--; alreadyUsed=false;}

OutputAvoid the use of global objects in constructors: LIST(A).

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.5 Constructors and Destructors - Rec. 33

288

Ellemtel (Telecom Industry) Items

Constructors&Destructors2.ruleAvoid the use of global objects in destructors.

Exampleint globalvar=0;bool alreadyUsed=false;

class Test{ public: Test(); ~Test();};

Test::Test() { // Violation globalvar++; alreadyUsed=true;}

Test::~Test() { // Violation globalvar--; alreadyUsed=false;}

OutputAvoid the use of global objects in destructors: LIST(A).

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.5 Constructors and Destructors - Rec. 33

289

Ellemtel (Telecom Industry) Items

Constructors&Destructors3.ruleA class which uses new to allocate instances mnaged by that class must define a copy constructor.

Example

// Violationclass Test1{public: Test1();private: int *p;

};

Test1::Test1() { p = new int;

}

// Okclass Test2{public: Test2(); Test2(Test2&);private: int *p;

};

Test2::Test2() { p = new int;

}

OutputA class which uses new must define a copy constructor: $name.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.5 Constructors and destructors - Rule 25

290

Ellemtel (Telecom Industry) Items

Constructors&Destructors4.ruleAll classes which are used as base classes and which have virtual functions must define a virtual destructor.Reason for rule: 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.

Example// violation in this example// one should add ~Base in Base class

class Base{ public: virtual void foo();};

class Derived : public Base {};

OutputAll classes which are used as base classes and which have virtual functions must define a virtual destructor.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.5 Constructors and Destructors - Rule 26

291

Ellemtel (Telecom Industry) Items

DataAbstractionPort.ruleDo not directly use the pre-defined data types in declarationsReason for rule: An excellent way of transforming your world to a "vale of tears" is to directly use thepre-defined data types in declarations.

If it is later necessary, due to portability problems, to change the return type of a function, it may be necessary to make change at a large number of places in the code.

One way to avoid this is to declare a new type name using classes or typedefs to represent the types of variables used. In this way, changes can be more easily made.

This may be used to give data a physical unit, such as kilogram or meter. Such code is more easily reviewed.

For example, when the code is functioning poorly, it may be noticed that a variable representing meters has been assigned to a variable representing kilograms.

It should be noted that a typedef does not create a new type, only an alternative name for a type. This means that if you have declared typedef int Error, a variable of the type Error may be used anywhere where an int may be used.

Exampletypedef int MyInt ;

int main() { int a; // Violation short int b; // Violation float c; // Violation char d; // Violation unsigned int a2; // Violation

MyInt a1; // Ok }

void foo(signed int bb) {} // violation - parameter type

int bar() { // violation - function return type return 0;

}

OutputAvoid the direct use of pre-defined data types in declaration: $name

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.1 Data Abstraction - Port. Rec. 1

292

Ellemtel (Telecom Industry) Items

FlowControlStatements1.ruleAlways use curly brackets after if construction.

Examplevoid foo2();

void foo(int x) {

if (x>0) {} // Ok // violation if (x>0) foo2();

// violation if (x>0) foo2(); else if (x < -1) { // ok } }

OutputAlways use curly brackets after if construction.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 style - 6.4 Flow Control Statements - Rec. 25

293

Ellemtel (Telecom Industry) Items

FlowControlStatements2.ruleAlways use curly brackets after else construction.

Examplevoid foo2();

void foo(int x) {

if (x>0) foo2(); else if (x < -1) { // ok } // violation if (x >0) { } else foo2();}

OutputAlways use curly brace after else construction.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 style - 6.4 Flow Control Statements - Rec. 25

294

Ellemtel (Telecom Industry) Items

FlowControlStatements3.ruleAlways use curly braces after for construction.

Examplevoid foo2();

void foo(int x) {

// violation for (int i=0; i< 10; i++) foo2();

// ok for (int j=0; j< 10; j++) {}

}

OutputAlways use curly braces after for construction.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 style - 6.4 Flow Control Statements - Rec. 25

295

Ellemtel (Telecom Industry) Items

FlowControlStatements4.ruleAlways use curly brackets after while construction.

Examplevoid foo2();

void foo(int x) {

// ok while (x > 10) { }

// violation while (1) foo2();

}

OutputAlways use curly braces after while construction.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 style - 6.4 Flow Control Statements - Rec. 25

296

Ellemtel (Telecom Industry) Items

FlowControlStatements5.ruleAlways use curly brackets after do construction.

Examplevoid foo2();

void foo(int x) { // violation do foo2(); while(1);

// Ok do { } while (1);

}

OutputAlways use curly brackets after do construction.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 style - 6.4 Flow Control Statements - Rec. 25

297

Ellemtel (Telecom Industry) Items

FlowControlStructure1.ruleAvoid the use of continue.Reason for rule: continue can be used to exit from loops. However, code may be more comprehensi-ble by using an else clause instead.

Examplevoid foo() {

for(int i=0;i<100;i++) { continue; // Violation here }

}

OutputAvoid the use of continue.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 14 Flow Control Structures - Rec. 53

298

Ellemtel (Telecom Industry) Items

FlowControlStructure2.ruleDo not write logical expressions of the type if(test) or if(!test) when test is a pointer.Reason for rule: We do not recommend logical tests such as if(pointer) if pointer is a variable of pointer-type. The only reason is readablity; many programmers find it difficult to read such code.

Examplevoid foo() {

int* ptr;

if (ptr) { // Violation }

if (!ptr) { // Violation } if (ptr==0) { // Ok } }

OutputDo not write logical expressions of the type if(test) or if(!test) when test is a pointer.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 14 Flow Control Structures - Rec. 55

299

Ellemtel (Telecom Industry) Items

FlowControlStructure3.ruleThe code following a case label must always be terminated by a break statement. Reason for rule: If the code which follows a case label is not terminated by break, the execution con-tinues after the next case label. This means that poorly tested code can be erroneous and still seem to work.

Examplevoid foo() {

int tag;

switch ( tag ) { // violation here case 0: { // Do something // Next statement is a call to foo() inside next case }

case 1: { foo(); // Do something else break; // Now we leave the switch-statement }

}

}

OutputThe code following a case label must always be terminated by a break state-ment.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 14 Flow Control Structures - Rule 47

300

Ellemtel (Telecom Industry) Items

FlowControlStructure4.ruleA switch statement must always contain a default branch which handles unexpected cases.

Example

void foo() {

int tag;

// violation here switch ( tag ) { case 0: { // Do something // Next statement is a call to foo() inside next case }

case 1: { foo(); // Do something else break; // Now we leave the switch-statement }

}

}

OutputA switch statement must always contain a default branch which handles unex-pected cases.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 14 Flow Control Structures - Rule 48

301

Ellemtel (Telecom Industry) Items

FlowControlStructure5.ruleNever use goto.

Example

void foo() {

int j; for(int i=0;i<10;i++) { goto alabel; // Violation - Never use goto }

alabel: j=0;

}

OutputNever use goto.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 14 Flow Control Structures - Rule 49

FormalArguments.ruleIf identifiers are given for any of the parameters, then the identifiers used in declaration and definition should be identical.

Examplevoid foo1(); // Okvoid foo2(int a, int b); // Okvoid foo2(int a, int b) {} void foo4(int , int ); // Okvoid foo4(int x, int y ) {}void foo5(int a, int b); // Violationvoid foo5(int x, int y ) {}

OutputIdentifiers given in declaration and definition of $function should be iden-tical.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Function - 9.3 Formal Arguments - Rule 32

302

Ellemtel (Telecom Industry) Items

FunctionArguments1.ruleAvoid functions with many arguments.Reason for rule: Functions having long lists of arguments look complicated, are difficult to read, and can indicate poor design. In addition, they are difficult to use and to maintain.

Examplevoid foo(int a,int b,int c,int d,int e,int f); //Violation

OutputAvoid functions with many arguments.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Function - 9.1 Function Arguments - Rec. 41

FunctionArguments2.ruleDo not use unspecified function arguments (ellipsis notation).Reason for rule: The best known function which uses unspecified arguments is printf(). The use of such functions is not advised since the strong type checking provided by C++ is thereby avoided. Some of the possibilities provided by unspecified function arguments can be attained by overloading functions and by using default arguments.

Examplevoid foo(int, ...) { // Violation

}

OutputDo not use unspecified function arguments (ellipsis notation).

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Functions - 9.1 Function Arguments - Rule 31

303

Ellemtel (Telecom Industry) Items

Functions1.ruleAlways provide the return type of function explicitly.

Examplefoo() { //violation}

int foo2() { //ok}

OutputAlways provide the return type of function explicitly.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.2 Functions - Rec. 20

Functions2.ruleIn function definition, the return type of the function should be written on a separate line directly above the function name.

Examplesint foo() { //Violation return 0; }

int foo2() { //Ok return 0; }

OutputIn function definition, the return type of the function should be written on a separate line directly above the function name.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.2 Functions - Rec. 22

304

Ellemtel (Telecom Industry) Items

Functions3.ruleAlways write the left parenthesis directly after a function name.

Examplevoidfoo2() { //Ok}

void foo () { //Violation}

OutputAlways write the left parenthesis directly after a function name.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.2 Functions - Rec. 23

General1.ruleLong functions have disadvantagesReason for rule: If a function is too long, it can be difficult to comprehend. Generally, it can be said that a function should not be longer than two pages, since that is about how much that can be compre-hended at one time.

If an error situation is discovered at the end of an extremely long function, it may be difficult for the function to clean up after itself and to "undo" as much as possible before reporting the error to the call-ing function.

By always using short functions, such an error can be more exactly localized.

Examplevoid too_long_function() { 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 a13; int a14;

305

Ellemtel (Telecom Industry) Items

int a15; int a16; int a17; int a18; int a19; int a20; int a21; int a22; int a23; int a24; int a25; int a26; int a27; int a28; int a29; int a30; int a31; int a32; int a33; int a34; int a35; int a36; int a37; int a38; int a39; int a40; int a41; int a42; int a43; int a44; int a45; int a46; int a47; int a48; int a49; int a50; int a51; int a52; int a53; int a54;

}

OutputFunction is too large.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Functions - 9.7 General - Rec 47

306

Ellemtel (Telecom Industry) Items

General2.ruleAvoid long and complex functions.Reason for rule: Complex functions are difficult to test. If a function consists of 15 nested if state-ments, then there are 2**15 (or 32768) different branches to test in a single function.

Example

void func(int i) { if (1) { // do something; } else { // do another; } do { } while(1); switch(i) { case 1: break; default: break; }

if (1) { // do something; } else { // do another; }

if (2) { // do something; } else { // do another; }

if (3) { // do something; } else { // do another; }

}

OutputNumber of block in a function: $count

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Functions - 9.7 General - Rec. 47

307

Ellemtel (Telecom Industry) Items

IncludeFiles1.ruleEvery implementation file should declare a local constant string that describes the file.Reason for rule: This allows the UNIX command 'what' to be used to obtain information on the file revision.

Example

// Okstatic const char* sccsid = "@(#) Exception.cc ; rev. A, Copyright ... ";

OutputEvery implementation file should declare a local constant string.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.4 include Files - Rec 12

IncludeFiles2.ruleNever include other files in an .icc file.

Example

// some.icc: #include <stdio.h>

OutputNever include other files in an .icc file.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.4 Include Files - Rec. 13

308

Ellemtel (Telecom Industry) Items

IncludeFiles3.ruleNever specify relative Unix file names in #include directives.

Example#include "foo.hh"

// violation#include "./foo.hh"

OutputNever specify relative UNIX names in #include directives: $name

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

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

IncludeFiles4.ruleEvery include file must contain a mechanism that prevents multiple inclusion of the file.

Example// OKfile foo.hh:#ifndef FOO_HH#define FOO_HH

int i;#endif

Output1$defname should appear in first #ifndef preprocessor directive.

Output2$defname should appear in first #define preprocessor directive.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

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

309

Ellemtel (Telecom Industry) Items

InlineFunctions1.ruleConstructors must not be inlineReason for rule: Functions which invoke other inline functions often become too complex for the com-piler to be able to make them inline despite their apparent smallness.

This problem is especially common with constructors and destructors. A constructor always invokes the constructors of its base classes and member data before executing its own code. Always avoid inline constructors and destructors!

Example

class Test1{ public: Test1(){} // Violation};

class Test2{ public: Test2(); // Ok};

Test2::Test2() { // Ok}

class Test3{ public: Test3();};

inline Test3::Test3() { // Violation}

OutputConstructors must not be inline.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.2 Inline Functions - Rec. 31

310

Ellemtel (Telecom Industry) Items

InlineFunctions2.ruleDestructors must not be inlineReason for rule: Functions which invoke other inline functions often become too complex for the com-piler to be able to make them inline despite their apparent smallness.

This problem is especially common with constructors and destructors. A constructor always invokes the constructors of its base classes and member data before executing its own code. Always avoid inline constructors and destructors!

Exampleclass Test1{ public: ~Test1(){} // Violation};

class Test2{ public: ~Test2();};

Test2::~Test2() { // Ok}

class Test3{ public: ~Test3();};

inline Test3::~Test3() { // Violation}

OutputDestructors must not be inline.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.2 Inline Functions - Rec. 31

311

Ellemtel (Telecom Industry) Items

InlineFunctions3.ruleDo not use the preprocessor directive #define to obtain more efficient code; instead use inline functions.

Example

// Violation#define SUM(A,B) ((A)+(B))

OutputDo not use the preprocessor directive #define to obtain more efficient code; instead use inline functions.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Functions - 9.5 Inline Functions - Rule 35

MemberFunctionsReturnTypes.ruleA public member function must never return a non-const reference or pointer to member data.Reason for rule: By allowing a user direct access to the private member data of an object, this data may be changed in ways not intended by the class designer. This may lead to reduced confidence in the designer's code: a situation to be avoided.

Exampleclass Test {public: int* GetI1(); // Violation int& GetI2(); // Violation const int* GetI3() ; const int& GetI4() ; private: int _i;};

int* Test::GetI1() { return &_i;}

int& Test::GetI2() { return _i;}

312

Ellemtel (Telecom Industry) Items

const int* Test::GetI3() { return &_i;}

const int& Test::GetI4() { return _i;}

OutputA public member function must never return a non-const reference or pointer to member data: LIST(A)

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.8 Member Function Return Types - Rule 29

MemoryAllocation1.ruleAvoid global data if at all possible.

Exampleint someGlobalVariable;

OutputAvoid global data if at all possible.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 16 Memory allocation - Rec. 57

313

Ellemtel (Telecom Industry) Items

MemoryAllocation2.ruleDo not use malloc, realloc, or free.Reason for rule: In C, malloc, realloc, and free are used to allocate memory dynamically on the heap. This may lead to conflicts with the use of the new and delete operators in C++. It is dangerous to invoke delete for a pointer obtained via malloc/realloc, invoke malloc/realloc for objects having con-structors, and invoke free for anything allocated using new. Because of these dangers, avoid the use of malloc, realloc, and free whenever possible.

Example#include <stdlib.h> #include <stdio.h>#include <malloc.h>

void foo() {

char *string; char* string2;

string = (char *)malloc(10); // violation string2 = (char*)realloc(string,12); // violation

free(string); // violation free(string2); // violation

}

OutputDo not use malloc, realloc or free.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 16 Memory Allocation - Rule 50

314

Ellemtel (Telecom Industry) Items

MemoryAllocation3.ruleAlways provide empty brackets ("[ ]") for delete when deallocating arrays.

Examplevoid foo(char **p) { delete [] p; //OK delete p[0]; //Violation

}

OutputAlways provide empty brackets ("[]") for delete when deallocating arrays.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 16 Memory Allocation - Rule 51

315

Ellemtel (Telecom Industry) Items

Miscellaneous.ruleDo not use spaces around '.' or '->'.

Exampleclass Test {public: Test(); void test();};

void foo() { Test t=Test();

t.test(); // ok t. test(); // violation t .test(); // violation

Test* t2 = new Test(); t2->test(); // ok t2 ->test(); // violation t2-> test(); // violation}

OutputDo not use spaces around '.' or '->'.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.2 Functions - Rec. 22

316

Ellemtel (Telecom Industry) Items

NamingFiles.ruleAn include file for a class should have a file name of the form <class name> + extension. Reason for Rule: Use uppercase and lowercase letters in the same way as in the source code. Sinceclass names must generally be unique within a large context, it is appropriate to utilize this characteris-tic when naming its include file. This convention makes it easy to locate a class definition using afile-based tool.

Example

//OKMyClass2.hh:class MyClass2 { };

//ViolationMyClass.hh:class MyClass2 { };

OutputHeader file has name: $headerName.h but should have a name: $className.h

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.2 Naming Files - Rec. 7

317

Ellemtel (Telecom Industry) Items

OperatorOverloading1.ruleDo not overload operator+=

Exampleclass A { //Violation public: A& operator + (A& a);};

class B { //Ok public: B& operator + (B& b); B& operator += (B& b);};

OutputNo overload operator+=

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

OperatorOverloading2.ruleDo not overload operator-=

Exampleclass C { //Violation public: C& operator - (C& c);};

class D { //Ok public: D& operator - (D& d); D& operator -= (D& d);};

OutputNo overload operator-=

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

318

Ellemtel (Telecom Industry) Items

OperatorOverloading3.ruleOverload operator != if you overload operator ==.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass C { //Violation public: bool operator == (C& c);};

class D { //Ok public: bool operator == (D& d); bool operator != (D& d);};

OutputOverload operator != if you overload operator ==.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

319

Ellemtel (Telecom Industry) Items

OperatorOverloading4.ruleOverload operator == if you overload operator !=.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass C { //Violation public: bool operator != (C& c);};

class D { //Ok public: bool operator == (D& d); bool operator != (D& d);};

OutputOverload operator == if you overload operator !=.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

320

Ellemtel (Telecom Industry) Items

OperatorOverloading5.ruleOverload operator || if you overload operator &&.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass C { //Violation public: bool operator && (C& c);};

class D { //Ok public: bool operator && (D& d); bool operator || (D& d);};

OutputOverload operator || if you overload operator &&.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

321

Ellemtel (Telecom Industry) Items

OperatorOverloading6.ruleOverload operator && if you overload operator ||.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass C { //Violation public: bool operator || (C& c);};

class D { //Ok public: bool operator && (D& d); bool operator || (D& d);};

OutputOverload operator && if you overload operator ||.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

322

Ellemtel (Telecom Industry) Items

OperatorOverloading7.ruleOverload operator > if you overload operator <.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass C { //Violation public: bool operator < (C& c);};

class D { //Ok public: bool operator < (D& d); bool operator > (D& d);};

OutputOverload operator > if you overload operator <.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

323

Ellemtel (Telecom Industry) Items

OperatorOverloading8.ruleOverload operator < if you overload operator >.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass C { //Violation public: bool operator > (C& c);};

class D { //Ok public: bool operator < (D& d); bool operator > (D& d);};

OutputOverload operator < if you overload operator >.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

324

Ellemtel (Telecom Industry) Items

OperatorOverloading9.ruleOverload operator >= if you overload operator <=.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

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

class D { //Ok public: bool operator <= (D& d); bool operator >= (D& d);};

OutputOverload operator >= if you overload operator <=.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

325

Ellemtel (Telecom Industry) Items

OperatorOverloading10.ruleOverload operator <= if you overload operator >=.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Examplesclass C { //Violation public: bool operator >= (C& c);};

class D { //Ok public: bool operator <= (D& d); bool operator >= (D& d);};

OutputOverload operator <= if you overload operator >=.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

326

Ellemtel (Telecom Industry) Items

OperatorOverloading11.ruleOverload operator -- if you overload operator ++.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Examplesclass A { //Violation public: A& operator ++ ();};

class B { //Ok public: B& operator ++ (); B& operator -- ();};

OutputOverload operator -- if you overload operator ++.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

327

Ellemtel (Telecom Industry) Items

OperatorOverloading12.ruleOverload operator ++ if you overload operator --.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass A { //Violation public: A& operator -- ();};

class B { //Ok public: B& operator ++ (); B& operator -- ();};

OutputOverload operator ++ if you overload operator --.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

328

Ellemtel (Telecom Industry) Items

OperatorOverloading13.ruleOverload operator - if you overload operator +.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass A { //Violation public: A& operator + (A& a);};

class B { //Ok public: B& operator + (B& b); B& operator - (B& b);};

OutputOverload operator - if you overload operator +.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

329

Ellemtel (Telecom Industry) Items

OperatorOverloading14.ruleOverload operator + if you overload operator -.Reason for rule: 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 opera-tor==; its semantic opposite is the operator!=, which should also be defined if operator== was defined.

Note: This rule is for C++ only. The Severity Level for this rule is Possible Violation.

Exampleclass A { //Violation public: A& operator - (A& a);};

class B { //Ok public: B& operator + (B& b); B& operator - (B& b);};

OutputOverload operator + if you overload operator -.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 7 Classes - 7.7 Operator Overloading - Rec. 36

PointerArithmeticPort1.ruleAvoid using shift operations instead of arithmetic operations.

Examplevoid foo() { int c =8 << 2; // Violation}

OutputAvoid using shift operations instead of arithmetic operations.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.8 Pointer Arithmetic - Port. Rec. 17

330

Ellemtel (Telecom Industry) Items

PointerArithmeticPort2.ruleAvoid pointer arithmeticReason for rule: Pointer arithmetic can be portable. The operators == and != are defined for all point-ers of the same type, while the use of the operators <, >, <=, >= are portable only if they are usedbetween pointers which point into the same array.

Exampleint* returnptr();

void foo() {

int* a; int* b;

if (a==b) {} // Violation

if (returnptr()>=b) {} // Violation if (b<returnptr()) {} // Violation

}

OutputAvoid pointer arithmetic.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.8 Pointer Arithmetic - Port. Rec. 18

331

Ellemtel (Telecom Industry) Items

Pointers&References1.ruleThe dereference operator * and the "address-of" operator & should be directly connected to the type names in declaration and definition.

Examplevoid foo() { int k=42; int *p1; // violation int* p2; // ok

int &r1 = k; // violation int& r2 = k; // Ok}

Output* and & should be connected to type name and not variable: $name

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 6 Style - 6.5 Pointers and references - Rec. 26

332

Ellemtel (Telecom Industry) Items

Pointers&References2.rulePointers to pointers should be avoided whenever possible.Reason for rule: Pointers to pointers normally ought not be used. Instead, a class should be declared, which has a member variable of the pointer type. This improves the readability of the code and encour-ages data abstraction. By improving the readability of code, the probability of failure is reduced.

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 inter-face, in which case pointers to pointers are needed. Another example is the second argument to the main function, which must have the type char*[].

Examplevoid foo() {

int** a; // Violation

}

OutputPointers to pointers should be avoided whenever possible.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 12 Pointers and References - Rec. 48

ReturnTypes&Values1.ruleEvery function shall have an explicit return type.

Exampleint goo(void); /*Ok*/foo(void); /*Violation*/

OutputEvery function shall have an explicit return type.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Function - 9.4 return Type ans Values - Rule 33

333

Ellemtel (Telecom Industry) Items

ReturnTypes&Values2.ruleA function must never return a pointer or reference to a local variable.Reason for rule: If a function returns a reference or a pointer to a local variable, the memory to which it refers will already have been deallocated, when this reference or pointer is used. The compiler may or may not give a warning for this.

Exampleint* foo() { // violation int i; return &i; }

int& bar() { // violation int i; return i; }

int bar2() { int i=0; return i; }

OutputA function must never return a pointer or reference to a local variable.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 9 Functions - 94. Return Types and Values - Rule 34

334

Ellemtel (Telecom Industry) Items

SizeOfTypesPort1.ruleAttempt to cast long pointer to int pointer.Reason for rule: Do not assume that int and long have the same size. A pointer to a long should not be cast to an int pointer.

Note: The Severity Level for this rule is Possible Severe Violation.

Examplevoid foo() { int *intPointer; long *longPointer; intPointer = (int *)longPointer; // Violation}

OutputAttempt to cast long pointer to int pointer.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

SizeOfTypesPort2.ruleAttempt to assign long value to int.Reason for rule: Do not assume that int and long have the same size. Assigning a long int to an int may result in truncation when porting from 32 bit to 64 bit applications.

Examplevoid foo(){ int iVal = 72; long lVal = 6; iVal = lVal; //Violation iVal = (int)lVal; //Violation too}

OutputAttempt to assign long value to int.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

335

Ellemtel (Telecom Industry) Items

SizeOfTypesPort3.ruleFunction cast long to intReason for rule: Do not assume that int and long have the same size. Assigning a long int to an int may result in truncation when porting from 32 bit to 64 bit applications.

Examplevoid foo(int iVal){ long lVal ; //.. set big value for lVal foo(lVal); //Violation foo((int)lVal); //Violation too}

Outputfunction cast long to int

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

SizeOfTypesPort4.ruleConstant is an unsigned intReason for rule: Do not assume that int and long have the same size. Constant assignment to long should not involve int literals.

Examplevoid foo(){ long longValue; longValue &= ~(0x00000000008000000000);

// Violation: leading zeros not significant.}

OutputConstant is an unsigned int

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

336

Ellemtel (Telecom Industry) Items

SizeOfTypesPort5.ruleConstant is an unsigned intReason for rule: Do not assume that int and long have the same size. Constant assignment to long should not involve int literals.

Example

void foo() {long longValue;longValue = 0x00000000008000000000;

// Violation: leading zeros not significant.}

OutputConstant is an unsigned int.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

SizeOfTypesPort6.ruleAssign an int literal to long.Reason for rule: Do not assume that int and long have the same size. An int literal is 32 bits in length. Assignment of int literal to long data value could lead to garbage in the upper 32 bits, or truncation if the int literal takes up more than 32 bits.

Examplevoid foo(){ long lVal = 1; //Violation}

OutputAssign an int literal to long.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

337

Ellemtel (Telecom Industry) Items

SizeOfTypesPort7.ruleAttempt to cast an int pointer as a long pointer.Reason for rule: Do not assume that int and long have the same size. Do not cast an int pointer to a long pointer. These are not compatible in 64 bit, even though in 32 bit they would have been inter-changeable.

Note: The Severity Level for this rule is Possible Severe Violation.

Examplevoid f2005() { int *intPointer; long *longPointer; longPointer = (long *)intPointer; // Violation}

OutputAttempt to cast an int pointer as a long pointer.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

SizeOfTypesPort8.rule32-bit multiplicationReason for rule: Do not assume that int and long have the same size. 32-bit multiplication assigned to long value may result in truncation.

Example

void foo() { long longValue; longValue = 2000000 * 3000000; // Violation - 32 bit multiplication longValue = 2000000L * 3000000; // Ok - 64 bit multiplication}

Output32-bit multiplication.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code - 18.2 Size of Types - Port. Rec. 2

338

Ellemtel (Telecom Industry) Items

StructureOfCode1.ruleAn include file should not contain more than one class definition.

ExampleIn header file:// violationclass testClass1{};class testClass2{};

OutputAn include file should not contain more than one class definition.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.1 Structure of Code - Rec. 3

StructureOfCode2.ruleUser include files should have the extension ".hh"

Example

#include "MyClass.h" //Violation#include "MyClass2.hh" //Ok

OutputUser include files should have the extension ".hh"

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.1 Structure of Code - Rule 1

339

Ellemtel (Telecom Industry) Items

StructureOfCode3.ruleImplementation files in C++ should always have the file name extension ".cc".

OutputImplementation files in C++ should have the file name extension ".cc"

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.1 Structure of Code - Rule 2

StructureOfCode4.ruleInline definition files always have the file extension ".icc"Reason for rule: Inline definition files - files which contain definitions of inline functions - should always have the file extension ".icc"

OutputInline definition files always have the file extension ".icc"

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 4 Source Code in Files - 4.1 Structure of Code - Rule 3

340

Ellemtel (Telecom Industry) Items

TypeConversionsPort1.ruleBe careful not to make type conversions from shorter type to longer type.

Examplevoid foo1() { int intValue; long longValue = 1L; longValue = intValue; // Violation}

void foo2() { int intValue=1; float floatValue; floatValue = intValue; // Violation}

OutputBe careful not to make type conversions from shorter type to longer type.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code- 18.3 Type Conversions - Port. Rec. 6

TypeConversionsPort2.ruleBe careful not to make type conversions from a shorter type to a longer one.

Examplevoid foo3() {

int longValue = 1L;(double)longValue; // Violation

}

OutputBe careful not to make type conversions from a shorter type to a longer one.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code- 18.3 Type Conversions - Port. Rec. 6

341

Ellemtel (Telecom Industry) Items

TypeConversionsPort3.ruleAttempt to cast long value to double.Reason for rule: Under 32 bit platform double can hold all significant bits. Under 64 bit platform double has 52 significant bits, and bits can be lost.

Examplevoid moo (double) {}

void foo () { long longValue = 1L; moo(longValue); // Violation}

OutputAttempt to cast long value to double.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code- 18.3 Type Conversions - Port. Rec. 6

TypeConversionsPort4.ruleDo not cast a pointer as an int.Reason for rule: Do not assume that pointers and integers have the same size. All pointer casts to integer types should be either long or unsigned long.

Examplevoid foo(){ char *p; int g=(int)p; //Violation}

OutputDo not cast a pointer as an int.

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 18 Portable Code- 18.3 Type Conversions - Port. Rec. 7

342

Ellemtel (Telecom Industry) Items

Variables.ruleEach variable is to be declared in a separate declaration statement.Reason for rule: This rule checks for each function that the number of lines where a variable is declared is equal to the number of variables declared in that function. So it will trigger if some variables are declared on the same line.

Examplevoid foo() { // violation

int a,b;

}

void bar() { // Ok

int a; int b;

}

OutputEach variable is to be declared in a separate declaration statement.Variables : COUNT(A) Lines : COUNT(B)

ReferenceOrigin: Ellemtel Coding Standards

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules-mm.html

From: 11 Variables - Rule 39

343

User MISRA Guidelines

Rule

ArrayIn eck-

AvoidA or

AvoidA s

AvoidD not ject

AvoidE y or

MISRA GuidelinesUser MISRA GuidelinesCodeWizard 4.3 includes a suite of rules to enforce requirements imposed by the Motor Industry Soft-ware Reliability Association (MISRA). These requirements can be found in the MISRA document "Guidelines For The Use Of The C Language In Vehicle Based Software.”

Note: All statically enforceable rules from the MISRA Guidelines document were implemented. These rules are implemented as:

• Built-in rules. Built-in MISRA rules are grouped under common prefix "misra.” For example "misra-20," "misra-112," and so on. The number corresponds to a number given to the rule in the original MISRA document. See “Built-in MISRA Guidelines” on page 89 for more informa-tion on the MISRA built-in rules included in CodeWizard.

• User rules. In this case the rules are prefixed with "user.” These rules are described in the fol-lowing table and rule sections. All these MISRA rules have numbers between 5001 and 5127; they were created by adding 5000 to the rule number taken from the original MISRA docu-ment. Therefore, MISRA rule 7 is identified by "user-5007.”

Important! What is the difference between Built-in MISRA rules and User MISRA rules?

• User MISRA rules, like all rules in the User category (including the Ellemtel rules), can be cus-tomized using RuleWizard.

• Built-in MISRA rules, along with the Effective C++, More Effective C++, Meyer-Klaus, and Uni-versal Coding Standard rules, cannot be altered using RuleWizard.

Some of the rules will need symbol information collected across multiple source files. For example, to verify that given symbol has only one definition, CodeWizard can analyze information collected from multiple sources, and issue a violation if more than a single definition was detected. To facilitate static analysis preformed on multiple files, a new command line tool (cwmfs) was introduced. See “CodeWiz-ard's cwmfs Utility” on page 127 for a detailed description of this new utility.

Since the MISRA guidelines focus on programs written in C, all MISRA rules are active for C code only. The ISO/IEC 9899:1999(E) standard for the C programming language was used as a reference when implementing the MISRA rules.

Tip! The MISRA Guidelines classify rules as "required" or "advisory." CodeWizard uses "Violation" and "Informational" severity levels for rules classified as "required" and "advisory," respectively.

RuleID Description

dexOutOfBounds 5004 Provisions should be made for appropriate run-time ching.

mbiguitiesWithDefinedOp 5100 Use only non-ambiguous forms of defined pre-processoperator.

ssignmentsInBooleanExp 5035 Assignment operators shall not be used in expressionwhich return Boolean value.

anglingRefsToLocals 5106 The address of an object with automatic storage shall be assigned to an object which may persist after the obhas ceased to exist.

xactEqualsNonEqualsOnFloats 5050 Floating point variables should not be tested for equalitinequality.

344

User MISRA Guidelines

AvoidK nc-cifi-

AvoidN

AvoidN

AvoidR

AvoidS con-

AvoidS s

AvoidS

AvoidT

AvoidU

AvoidU age

AvoidU

BitWise te-

Boolea lue.

Casting -

Charac d

Confor e-

Consta t

Declare har

Declare

Declare less

Docum

Docum d

eyWordsAndTypesInMacros 5090 C macros shall only be used for symbolic constants, fution-like macros, type qualifiers and storage class speers.

onConstFunctionPointers 5104 Non-constant pointers to functions shall not be used.

onStandardCharsInInclude 5088 Non-standard characters shall not occur in header filenames in #include directives.

edundantExplicitCasts 5044 Redundant explicit casts should not be used.

ideEffectsInLogicalOp 5033 The right hand operand of a && or || operator shall not tain side effects.

izeofOnExpWithSideEffects 5040 The sizeof operator should not be used on expressionthat contain side effects.

witchWithNoCase 5064 Every switch statement shall have at least one case.

ooManyPPOpsInMacro 5098 There shall be at most one occurence of the # or ## pre-processor operators in a single macro definition.

naryMinusForUnsignedExp 5039 The unary minus operator shall not be applied to an unsigned expression.

nreachableCode1 5052 This rule is purely informational and will report a messwhen unreachable code in an if statement has been detected.

nreachableCode2 5052 There shall be no unreachable code.

OperationOnSignedInteger 5037 Bitwise operations shall not be performed on signed inger types.

nInSwitchExpression 5063 A switch expression should not represent a Boolean va

IntegralToFloat 5016 The underlying bit representations of floating point numbers shall not be used.

terMapping 5006 Values of character types shall be restricted to a defineand documented subset of ISO 10646-1.

mToIncludeDirectiveFormat 5089 The #include directive shall be followed by either a <filname> or "filename" sequence.

ntUnSignedExpression 5051 Evaluation of constant unsigned expression should nolead to wrap-around.

CharTypeExplicitly 5014 The type char shall always be declared as unsigned cor signed char.

FunctionsAtFileScope 5068 Functions shall always be declared at file scope.

ObjectsAtFunctionScope 5022 Declarations of objects should be at function scope una wider scope is necessary.

entIntegerDivision 5041 Document integer division

entUseOfPragmas 5099 All uses of #pragma directive shall be documented anexplained.

345

User MISRA Guidelines

DoNotC

DoNotD ock.

DoNotH

DoNotI all

DoNotM not

DoNotM tion .

DoNotN

DoNotR hall

DoNotR hall

DoNotR

DoNotU m

DoNotU

DoNotU i-

DoNotU

DoNotU

DoNotU ters.

DoNotU

DoNotU s.

DoNotU eck-

DoNotU .

DoNotU .

DoNotU

DoNotU

DoNotU sed.

onfuseBitwise&LogicalOps 5036 Logical operators should not be confused with bitwise operators.

efineUndefineMacroInBlock 5091 Macros shall not be #define'd and #undef'd within a bl

ideGlobalVariables 5021 Do not hide names of global variables.

nitializeEnumMembers 5032 In enumerator list, the '=' construct shall not be used toexplicitly initialise members other than the first, unlessitems are explicitly initialized.

ixAssemblyAndC 5003 Assembly language functions that are called from C should be written as C functions containing only in-lineassembly language. In-line assembly language shouldbe embedded in normal C code.

odifyCounterInForLoopBody 5067 Numeric variables being used within a for loop for iteracounting should not be modified in the body of the loop

estComments 5009 Comments shall not be nested.

edefineReservedNames1 5114 Reserved words and standard library function names snot be redefined or undefined.

edefineReservedNames2 5114 Reserved words and standard library function names snot be redefined or undefined.

euseTypedefNames 5017 Typedef names shall not be reused.

seAbortExitGetenvSystem 5126 The library functions abort, exit, getenv and system frolibrary <stdlib.h> shall not be used.

seAtofAtoiAtol 5125 The library functions atof, atoi and atol from library <stdlib.h> shall not be used.

seBreakStatement 5058 The break statement shall not be used (except to termnate the case of a switch statement).

seContinueStatement 5057 The continue statement shall not be used.

seErrno 5119 The error indicator errno shall not be used.

seFloatsAsLoopCounters 5065 Floating point variables shall not be used as loop coun

seGotoStatement 5056 The goto statement shall not be used.

seLabels 5055 Labels should not be used, except in switch statement

seLeftShifts 5004 Provisions should be made for appropriate run-time ching.

seLocaleHAndSetLocale1 5121 <locale.h> and the setlocale function shall not be used

seLocaleHAndSetLocale2 5121 <locale.h> and the setlocale function shall not be used

seLongIdentifiers 5011 Identifiers shall not have more than 31 characters.

seOclatConstants 5019 Octal constants (other than zero) shall not be used.

seOffsetof 5120 The macro offsetof, in library <stddef.h>, shall not be u

346

User MISRA Guidelines

DoNotU

DoNotU di-

DoNotU

DoNotU es.

DoNotU e

DoNotU

DoNotU pro-

DoNotU t be

DoNotU

DoNotU

DoNotU

DoNotU t be

DoNotU t be

DoNotU

Expres

Expres ny

Expres ny

Expres ny

Floatin -

Floatin -

FullySp fied.

Implici ma-

Implici ma-

sePointerArithmetic 5101 Pointer arithmetic should not be used.

seRecursion 5070 Functions shall not call themselves, either directly or inrectly.

seRegisterStorageClass 5028 The register storage class specifier shall not be used.

seRelationalOpsOnPointers 5103 Relational operators shall not be applied to pointer typ

seSetjmpAndLongjmp 5122 The setjmp macro and the longjmp function shall not bused.

seSignalH 5123 The signal handling facilities of <signal.h> shall not beused.

seStdioH 5124 The input/output library <stdio.h> shall not be used in duction code.

seTimeH 5127 The time handling functions of library <time.h> shall noused.

seTriGraphs 5007 Trigraphs shall not be used.

seUndef 5092 #undef should not be used.

seUnions 5109 Unions shall not be used.

seVariableNumberOfArgs1 5069 Functions with variable numbers of arguments shall noused.

seVariableNumberOfArgs2 5069 Functions with variable numbers of arguments shall noused.

seWideStringLiterals 5008 Wide string literals shall not be used.

sionEvaluation1 5046 Do not use the volatile keyword.

sionEvaluation2 5046 The value of an expression shall be the same under aorder of evaluation that the standard permits.

sionEvaluation3 5046 The value of an expression shall be the same under aorder of evaluation that the standard permits.

sionEvaluation4 5046 The value of an expression shall be the same under aorder of evaluation that the standard permits.

gInBitwiseExpressions1 5016 The underlying bit representations of floating point numbers shall not be used.

gInBitwiseExpressions2 5016 The underlying bit representations of floating point numbers shall not be used.

ecifyMembersOfStructOrUnion 5108 All members of structure or union should be fully speci

tConversionLosesInfo1 5043 Implicit conversions which may result in a loss of infortion shall not be used.

tConversionLosesInfo2 5043 Implicit conversions which may result in a loss of infortion shall not be used.

347

User MISRA Guidelines

Include

Initializ n.

Invalid left

MakeD ssi-

MixedP to

MixedP to

MixedP to

MixedP to

NameB ed.

NullPo

NullPo

Pointer t be

PreferC Dis-f

PreferF like

Provide s in

Provide

Provide use.

Provide use.

Provide se.

Provide

PutNul

PutNul

Statements 5087 #include statements in a file shall only be preceded byother preprocessor directives or comments.

eVariablesAtDeclaration 5030 All automatic variables shall be initialized at declaratio

RangeOfShiftOperand 5038 The right hand operand of a shift operator shall lie between zero and one less than the width in bits of thehand operand (inclusive).

eclarationsStaticAtFileScope 5023 All declarations at file scope should be static where poble.

recisionArithmetic1 5048 Mixed precision arithmetic should use explicit casting generate the desired result.

recisionArithmetic2 5048 Mixed precision arithmetic should use explicit casting generate the desired result.

recisionArithmetic3 5048 Mixed precision arithmetic should use explicit casting generate the desired result.

recisionArithmetic4 5048 Mixed precision arithmetic should use explicit casting generate the desired result.

itFields 5113 All the members of a structure (or union) shall be nam

interDereferenced1 5107 The NULL pointer shall not be dereferenced.

interDereferenced2 5107 The NULL pointer shall not be dereferenced.

NonPointerCast 5045 Type casting from any type to or from pointers shall noused.

onditionalCompilation 5010 Sections of old code should not be "commented out". abling of sections of code should be achieved by use oconditional compilation (e.g. #if or #ifdef constructs).

unctionsOverMacros 5093 A function should be used in preference to a function -macro.

AllOrNoneArgumentNames 5073 Identifiers shall either be given for all of the parametera function prototype declaration, or for none.

ExplicitReturnType 5075 Every function shall have an explicit return type.

FinalDefaultForSwitch1 5062 All switch statements should contain a final default cla

FinalDefaultForSwitch2 5062 All switch statements should contain a final default cla

FinalElseClause 5060 All if, else if constructs should contain a final else clau

SingleExitPointFromFunc 5082 A function should have a single point of exit.

lStatementsInTheirOwnLine1 5054 A null statement shall only occur on a line by itself, andshall not have any other text on the same line.

lStatementsInTheirOwnLine2 5054 A null statement shall only occur on a line by itself, andshall not have any other text on the same line.

348

User MISRA Guidelines

ReturnExpres

rn

ReturnExpres

hall

Return d.

Termin all

TestErr or-

TooMa

TypesS

TypesS

TypesS

TypesS

Unions ger

UseBra e in

UseCo on-

UseCo and

UseCo ters at

UseCu

UseCu

UseCu

UseCu

UseCu

UseEm ty

UseExp

OfNonVoidFunctionMustHavesion

5083 For each function with non-void return value, each retushall have an expression.

OfVoidFunctionMustNotHavesion

5084 For functions with void return type, return statements snot have an expression.

ValueVoidShallNotBeUsed 5079 The values returned by void functions shall not be use

ateCaseWithBreak 5061 Every non-empty case clause in a switch statement shbe terminated with a break statement.

orInformation 5086 If a function return error information, then that error infmation should be tested.

nyPointerIndirectionLevels 5102 No more than two levels of pointer indirection shall beused.

uffixForNumericConstants1 5018 Numeric constants should be suffixed to indicate type,where an appropriate suffix is available.

uffixForNumericConstants2 5018 Numeric constants should be suffixed to indicate type,where an appropriate suffix is available.

uffixForNumericConstants3 5018 Numeric constants should be suffixed to indicate type,where an appropriate suffix is available.

uffixForNumericConstants4 5018 Numeric constants should be suffixed to indicate type,where an appropriate suffix is available.

AccessSubParts 5110 Unions shall not be used to access the sub-parts of lardata types.

cesToMatchStructure 5031 Braces shall be used to indicate and match the structurthe non-zero initialization of arrays and structures.

mmaInForLoopOnly 5042 The comma operator shall not be used, except in the ctrol expression of a for loop.

nsistentLinkage 5024 Identifiers shall not simultaneously have both internal external linkage in the same translation unit.

nstForArgsPassedByRef 5081 const qualification should be used on function paramewhich are passed by reference, where it is intended ththe function will not modify the parameter.

rlyBraces1 5059 Always use curly brackets after if statements.

rlyBraces2 5059 Always use curly brackets after else statements.

rlyBraces3 5059 Always use curly braces after for statement.

rlyBraces4 5059 Always use curly brackets after while statements.

rlyBraces5 5059 Always use curly brackets after do statement.

ptyParensForNoArgFunc 5085 Functions called with no parameters should have empparentheses.

licitTestsAgainstZero 5049 Test of a value against zero should be made explicit.

349

User MISRA Guidelines

UseIde ara-es

UseIde ara-es

UseMin

UseOn t or

UsePar of a

UseThe the e

UseTyp le uld

UseVoi

VoidEx -

nticalTypesForDeclDef1 5072 For each function parameter the type given in the decltion and definition shall be identical, and the return typshall also be identical.

nticalTypesForDeclDef2 5072 For each function parameter the type given in the decltion and definition shall be identical, and the return typshall also be identical.

imalCharacterSet 5005 Only use characters defined in ISO C standard.

lyInstToDefineBit Fields 5111 Bit fields shall only be defined to be of type unsigned insigned int.

enthesesForMacroArgs 5096 In the definition of a function-like macro each instance parameter shall be enclosed in parentheses.

SameIdentifiersInDeclDef 5074 If identifiers are given for any of the parameters, then identifiers used in the declaration and definition shall bidentical.

edefsForBasicTypes 5013 The basic types of char, int, short, long, float and doubshould not be used, but specific-length equivalents shobe typedef'd for the specific compiler, and these type names used in the code.

dForFunctionsWith NoArgs 5076 Functions with no parameters shall be declared with parameter type void.

pressionsAsFunctionParameter 5080 Void expressions shall not be used as function parameters.

350

User MISRA Guidelines

ArrayIndexOutOfBounds.ruleProvisions should be made for appropriate run-time checking.

Exampleint foo(int i) { int j[10];

return j[i]; /* Violation */}

int moo(int i) { int j; int k[10]; int l = k[j]; /* Violation */ int m;

/* OK */ if ((j < 10) && (j >= 0)) {

m = k[j]; } return 0;}

OutputEnsure that array indices are within the bounds of the array size before using them to index the array.

ReferenceOrigin: Misra Guidelines - Rule 4

351

User MISRA Guidelines

AvoidAmbiguitiesWithDefinedOp.ruleUse only non-ambiguous forms of defined pre-processor operator.

Example// EXAMPLE.H - Example header file

#if defined TEST+1 // Violation#endif

#if defined TEST // OK#endif

#if defined EXAMPLE_H#endif

#if defined ( TEST ) // OK#endif

#if !defined ( EXAMPLE_H )#define EXAMPLE_H

class Example{};

#endif // !defined( EXAMPLE_H )

OutputThe defined pre-processor operator shall only be used in one of the two standards forms.

ReferenceOrigin: Misra Guidelines - Rule 100

352

User MISRA Guidelines

AvoidAssignmentsInBooleanExp.ruleAssignment operators shall not be used in expressions which return Boolean value.

Examplevoid foo() { int x; int y;

x=y; if ( x != 0) { // Ok // ... } if ( ( x=y) != 0) { // violation }

if ( x=y ) { // violation }

}

OutputAssignment operators shall not be used in expressions which return boolean value.

ReferenceOrigin: Misra Guidelines - Rule 35

353

User MISRA Guidelines

AvoidDanglingRefsToLocals.ruleThe address of an object with automatic storage shall not be assigned to an object which may persist after the object has ceased to exist.

Exampleint* globalvar;

int globalvar2;

void foo () { int x=0; globalvar=&x; // violation globalvar2=x; // ok}

OutputThe address of an object with automatic storage shall not be assigned to an object which may persist after the object has ceased to exist.

ReferenceOrigin: Misra Guidelines - Rule 106

354

User MISRA Guidelines

AvoidExactEqualsNonEqualsOnFloats.ruleFloating point variables should not be tested for equality or inequality.

Examplefloat bar1();double bar2();

void foo() { float f1,f2; double d1,d2;

if (f1==0) { // violation }

if (d1==0) { // violation }

if (f1!=0) { // violation }

if (d1!=0) { // violation }

if (f1==f2) { // violation }

if (f1!=f2) { // violation }

if (f1 >= 0) {} // ok if (d1 <= 0) {} // ok

if (bar1()==0) {} // violation if (bar2()!=0) {} // violation

if (bar1() > bar2()) {} // Ok

}

OutputFloating point variables should not be tested for equality or inequality.

ReferenceOrigin: Misra Guidelines - Rule 50

355

User MISRA Guidelines

AvoidKeyWords&TypesInMacros.ruleC macros shall only be used for symbolic constants, function-like macros, type qualifiers and storage class specifiers.In particular macros shall not be used to define statements or part of statements, nor to redefine the syntax of the language.

Example#define PI 3.1416 // Ok

#define PLUS2(X) ((X)+2) // Ok

#define SI_32 long // violation#define STARTIF if( // violation

OutputDo not redefine part of the language with macros.

ReferenceOrigin: Misra Guidelines - Rule 90

AvoidNonConstFunctionPointers.ruleNon-constant pointers to functions shall not be used.

Examplevoid foo();

typedef void (*PFUNC) (void);

const PFUNC pf = foo; // ok

int bar() {

PFUNC f1; // violation

return 0;}

OutputNon-constant pointers to function shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 104

356

User MISRA Guidelines

AvoidNonStandardCharsInInclude.ruleNon-standard characters shall not occur in header file names in #include directives.

Example

// incl\header.h:void foo();

// foo.cpp#include <sys\types.h>

#include "incl\header.h"

void foo(){}

OutputFilename $name should contain only standard characters.

ReferenceOrigin: Misra Guidelines - Rule 88

357

User MISRA Guidelines

AvoidRedundantExplicitCasts.ruleRedundant explicit casts should not be used.

Examplevoid foo44(){ char cVar = 1; cVar = (char) cVar; /* complain */ cVar = (char) (cVar+'e'); /* complain */ return;}

void foo44e(){ char cVar = 1; short sVar = 1; double dVar = 1.0;

dVar = (double) dVar; /* complain */ dVar = (double) (dVar * cVar + sVar); /* complain */ dVar = (double) (double)2/3; /* complain */ return;}

void foo44d(){ char cVar = 1; short sVar = 1; float fVar = 1.0;

fVar = (float) fVar; /* complain */ fVar = (float) (fVar * cVar + sVar); /* complain */ return;}

void foo44a(){ char cVar = 1; int iVar = 1; iVar = (int)iVar; /* complain */ iVar = (int)(iVar+60); /* complain */ iVar = (int)(iVar+cVar); /* complain */ return;}

358

User MISRA Guidelines

void foo44b(){ char cVar = 1; int iVar = 1; long lVar = 1L; lVar = (long)lVar; /* complain */ lVar = (long)(lVar+60); /* complain */ lVar = (long)(lVar+iVar+cVar); /* complain */ return;}

void foo44f(){ char cVar = 1; short sVar = 1; long double ldVar = 1.0;

ldVar = (long double) ldVar; /* complain */ ldVar = (long double) (ldVar * cVar + sVar); /* complain */ ldVar = (long double) (long double)2/3; /* complain */ return;}

void foo44c(){ char cVar = 1; short sVar = 1; sVar = (short)sVar;/* complain */ sVar = (short)(sVar+cVar);/* complain */ return;}

OutputRedundant explicit casts should not be used.

ReferenceOrigin: Misra Guidelines - Rule 44

359

User MISRA Guidelines

AvoidSideEffectsInLogicalOp.ruleThe right hand operand of a && or || operator shall not contain side effects.

Exampleint foo1(int);

void foo2() { int ishigh=1; int x,i;

if (ishigh && ( x == i++)) {} // violation if (ishigh || ( x == foo1(x))) {} // violation }

OutputThe right-hand operand of a && or || operator shall not contain side effects.

ReferenceOrigin: Misra Guidelines - Rule 33

AvoidSizeofOnExpWithSideEffects.ruleThe sizeof operator should not be used on expressions that contain side effects.Note: The Severity Level for this rule is Possible Violation.

Example

void foo() { int val = 1; sizeof(val); /*ok */ sizeof(val++); /* Violation */}

OutputThe sizeof operator should not be used on expressions that contain side effects.

ReferenceOrigin: Misra Guidelines - Rule 40

360

User MISRA Guidelines

AvoidSwitchWithNoCase.ruleEvery switch statement shall have at least one case.

Examplevoid foo(int i) { switch(i) /*Violation*/ { default: ; }}

OutputThere is no case clause in switch statement.

ReferenceOrigin: Misra Guidelines - Rule 64

AvoidTooManyPPOpsInMacro.ruleThere shall be at most one occurence of the # or ## pre-processor operators in a single macro definition.

Example// Ok#define TEST(A,B) A # B

// Ok#define TEST2(A,B) A ## B

// violation#define TEST3(A,B,C) A # B # C

// violation#define TEST4(A,B,C) A ## B # C

// violation#define TEST5(A,B,C) A ## B ## C

OutputThere shall be at most one occurence of the # or ## pre-processor operator.

ReferenceOrigin: Misra Guidelines - Rule 98

361

User MISRA Guidelines

AvoidUnaryMinusForUnsignedExp.ruleThe unary minus operator shall not be applied to an unsigned expression.Note: The Severity Level for this rule is Informational.

Examplevoid foo() {int x;unsigned int sx;long z;unsigned long sz;

int res;

res = -x; // Ok

res = -sx; // Violation

long zres;

zres = -z; // Okzres = -sz; // Violation

}

OutputThe unary minus operator shall not be applied to an unsigned expression.

ReferenceOrigin: Misra Guidelines - Rule 39

362

User MISRA Guidelines

AvoidUnionsInDataStructures.ruleUnions shall not be used to access the sub-parts of larger data types.

Exampleunion NumericType // violation { int iValue; long lValue; double dValue; };

typedef union { // Violation char *a, b; float f[20];} TheUnion;

OutputDo not use unions.

ReferenceOrigin: Misra Guidelines - Rule 110

363

User MISRA Guidelines

AvoidUnreachableCode1.ruleThis rule is purely informational and will report a message when unreachable code in an if statement has been detected.

Examplevoid foo (){ int i = 0;

/* ... */

if(1) /* Violation */ { i = 1; } else { i = 2; }

return;}

OutputUnreachable code detected.

ReferenceOrigin: Misra Guidelines - Rule 52

AvoidUnreachableCode2.ruleThere shall be no unreachable code.

Exampleint foo (){ int i = 0;

return(i);

i = 7; /* Violation */}

OutputUnreachable code detected.

ReferenceOrigin: Misra Guidelines - Rule 52

364

User MISRA Guidelines

BitWiseOperationOnSignedInteger.ruleBitwise operations shall not be performed on signed integer types.

Exampleint goo() { return 0;}

void foo() { int dVar = 1; signed int sdVar = 0; unsigned int udVar = 0u; udVar = udVar & udVar; /* Ok */ udVar = udVar & dVar; /* Violation */ udVar = udVar & sdVar; /* Violation */ udVar ^= udVar; /* Ok */ udVar ^= dVar; /* Violation */ udVar ^= sdVar; /* Violation */ udVar ^= goo(); /* Violation */

unsigned int udVar2 = ~udVar; /* Ok */ unsigned int udVar3 = ~sdVar; /* Violation */ }

OutputFor all output: Bitwise operations shall not be performed on signed integer types.

ReferenceOrigin: Misra Guidelines - Rule 37

365

User MISRA Guidelines

BooleanInSwitchExpression.ruleA switch expression should not represent a Boolean value.Note: The Severity Level for this rule is Informational.

Examplevoid foo(int i) { switch(i) { case 0 : break; default: ; }}

void foo2(bool b) { switch(b) //Violation { case true : break; default: ; }}

OutputAll switch expression should not represent a Boolean value.

ReferenceOrigin: Misra Guidelines - Rule 63

366

User MISRA Guidelines

CastingIntegralToFloat.ruleThe underlying bit representations of floating point numbers shall not be used.

Example

void foo() {

int* pi; float* pf; double* pd;

pi = (int*)pf; /* violation */ pi = (int*)pd; /* violation */ pf = (float*)pd; /* OK */

short int* ps = (short*)pf; /* violation */ ps = (short*)pi; /* OK */ long* pl = (long*)pf; /* violation */}

OutputThe underlying bit representations of floating point numbers shall not be used in any way by the programmer.

ReferenceOrigin: Misra Guidelines - Rule 16

367

User MISRA Guidelines

CharacterMapping.ruleValues of character types shall be restricted to a defined and documented subset of ISO 10646-1.

Examplevoid foo() { const char * s[] = {"a", "\012" /* violation */ };}

OutputThe chosen implementation of C shall conform to a subset of ISO 10646-1, and the chosen subset shall be documented. Explicitly specified numerc value of character may not conform to chosen subset of ISO 10646-1.

ReferenceOrigin: Misra Guidelines - Rule 006

ConformToIncludeDirectiveFormat.ruleThe #include directive shall be followed by either a <filename> or "filename" sequence.

Example

// Ok#include "misra89.h"

#define MISRA_HEADER "misra89.h"

// Violation:#include MISRA_HEADER

OutputThe #include directive shall be followed by either a <filename> or "file-name" sequence.

ReferenceOrigin: Misra Guidelines - Rule 89

368

User MISRA Guidelines

ConstantUnSignedExpression.ruleEvaluation of constant unsigned expression should not lead to wrap-around.

Example#if (1u - 2u)// ...#endif

OutputEvaluation of constant unsigned expressions should not lead to wrap-around. 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.

ReferenceOrigin: Misra Guidelines - Rule 51

DeclareCharTypeExplicitly.ruleThe type char shall always be declared as unsigned char or signed char.

Example

typedef signed char SC;typedef unsigned char UC;typedef char CH;

void foo() {

char a; // violation signed char b; // ok unsigned char c; // ok

CH aa; // violation SC bb; // Ok UC cc; // Ok

}

void bar(char d); // violation

SC bar2(); // Ok

char bar3(); // violation

369

User MISRA Guidelines

OutputFor $name, the type char shall always be declared as unsigned char or signed char.

ReferenceOrigin: Misra Guidelines - Rule 14

DeclareFunctionsAtFileScope.ruleFunctions shall always be declared at file scope.

Examplevoid foo1() {}

void foo2() { void foo3(); // violation

}

OutputFunctions shall always be declared at file scope:

ReferenceOrigin: Misra Guidelines - Rule 68

DeclareObjectsAtFunctionScope.ruleDeclarations of objects should be at function scope unless a wider scope is necessary.Note: The Severity Level for this rule is Informational.

Examplevoid foo() { int a; // OK}

int globalvar; // violation

OutputIf possible, do not use global variables.

ReferenceOrigin: Misra Guidelines - Rule 22

370

User MISRA Guidelines

DocumentIntegerDivision.ruleDocument integer division

Examplevoid foo1() { int i=2; int j=3; float f=4; float f2;

/* integer division */ f2=i/j; f2=j/i; /* Violation */ f2=f/i; /* OK - this is not integer division */}

OutputThe implementation of integer division in the chosen compiler should be determined, documented and taken into account. This rule checks that, wher-ever there is an integer division in the code, there must be comment on the previous line.

ReferenceOrigin: Misra Guidelines - Rule 3

DocumentUseOfPragmas.ruleAll uses of #pragma directive shall be documented and explained.

Example#pragma TEST

OutputAll use of #pragma shall be documented and explained.

ReferenceOrigin: Misra Guidelines - Rule 99

DoNotConfuseBitwise&LogicalOps.ruleLogical operators should not be confused with bitwise operators.To enforce this rule it is assumed that operands of logical operation must be of Boolean type. If the type is different, probably a bitwise operator should have been used in place the logical operator found.

Note: The Severity Level for this rule is Informational.

371

User MISRA Guidelines

Exampletypedef int MY_INT;

char getSpace() { return ' ';}

bool getTrue() { return true;}

void foo() { int x=0; int y=0; bool b=false; bool b2=true; MY_INT myInt;

if (x || y) { // Violation }

if (b || b2) { // Ok } if (y++ || b) { // Violation }

if (b || getSpace()) { // Violation } if (b || getTrue()) { // Ok }

bool b3 = !x; // Violation bool b4 = !myInt; //Violation bool b5 = !b2; // Ok

}

OutputFor all outputs: type of operand is different like Boolean.

ReferenceOrigin: Misra Guidelines - Rule 36

372

User MISRA Guidelines

DoNotDefineUndefineMacroInBlock.ruleMacros shall not be #define'd and #undef'd within a block.

Example#define SUM(A,B) ((A)+(B)) // Ok

void foo(int* x) {

#define CHECKPARAM(p) (p != 0) // Violation

if (CHECKPARAM(x)) {/* ... */

}

#undef SUM // Violation

}

OutputMacros shall not be #define'd and #undef'd within a block.

ReferenceOrigin: Misra Guidelines - Rule 91

DoNotHideGlobalVariables.ruleDo not hide names of global variables.

Exampleint x;

void foo(){ int x; /* Violation */ x = 3;}

OutputHid indentifier with identifier of the same name: LIST(C).

ReferenceOrigin: Misra Guidelines - Rule 21

373

User MISRA Guidelines

DoNotInitializeEnumMembers.ruleIn enumerator list, the '=' construct shall not be used to explicitly initialise members other than the first, unless all items are explicitly initialized.

Exampleenum TEST { /*Violation*/ X=5, Y, Z=9,};

enum TEST2 { /*Violation*/

X2, Y2=5, Z2,};

enum TEST3 { /*Ok*/ X3, Y3, Z3,};

enum TEST4 { /*Ok*/ X4=2, Y4, Z4,};

enum TEST5 { /*Ok*/

X5=2, Y5=4, Z5=8,};

OutputFor all outputs: incorrect members initialization.

ReferenceOrigin: Misra Guidelines - Rule 32

374

User MISRA Guidelines

DoNotMixAssemblyAndC.ruleAssembly language functions that are called from C should be written as C functions containing only in-line assembly language. In-line assembly language should not be embedded in normal C code.Note: The Severity Level for this rule is Informational.

Example/* compilable by cl.exe */

void asmCall(){ __asm{ mov eax, 01h int 10h }}

void asmCall2() /* complain */{ int g = 0; __asm{ mov eax, 01h int 10h }}

OutputDo not mix C code and assembler code in function body.

ReferenceOrigin: Misra Guidelines - Rule 3

375

User MISRA Guidelines

DoNotModifyCounterInForLoopBody.ruleNumeric variables being used within a for loop for iteration counting should not be modified in the body of the loop.Note: The Severity Level for this rule is Informational.

Examplevoid foo(){ int iVarA; int iVarB; char array[10]; for (iVarA=0; iVarA<=iVarB; iVarA++) { /* complain */ iVarA++; } for (array[iVarA]=0; array[iVarA] < 10; array[iVarA]++) { /* complain */ array[iVarB]--; } return;}

OutputModification of iterator in the loop's body.

ReferenceOrigin: Misra Guidelines - Rule 67

DoNotNestComments.ruleComments shall not be nested.

Example

// c++ comment ok

/* C style comment ok */

/* comment shall not be nested violation here /* */

OutputComments shall not be nested.

ReferenceOrigin: Misra Guidelines - Rule 9

376

User MISRA Guidelines

DoNotRedefineReservedNames1.ruleReserved words and standard library function names shall not be redefined or undefined.

Example

// violation#define __LINE__ 12

// Violation#define break 1

OutputDo not redefine or undefine reserved words and standard names.

ReferenceOrigin: Misra Guidelines - Rule 114

DoNotRedefineReservedNames2.ruleReserved words and standard library function names shall not be redefined or undefined.

Example

// ok#undef TEST

// violation:#undef __LINE__

// violation:#undef assert

OutputDo not redefine or undefine reserved words and standard names.

ReferenceOrigin: Misra Guidelines - Rule 114

377

User MISRA Guidelines

DoNotReuseTypedefNames.ruleTypedef names shall not be reused.

Example

// Violationtypedef char* Pchar;

typedef int MyInt;

void foo() { double MyInt;}

OutputTypedef names shall not be reused.

ReferenceOrigin: Misra Guidelines - Rule 17

378

User MISRA Guidelines

DoNotUseAbortExitGetenvSystem.ruleThe library functions abort, exit, getenv and system from library <stdlib.h> shall not be used.

Example#include <stdlib.h>

void foo( void ){ char *libvar;

libvar = getenv( "LIB" ); // violation

system("dir"); // violation

abort(); // violation

exit(0); // violation

}

OutputThe library functions abort, exit, getenv and system from library shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 126

379

User MISRA Guidelines

DoNotUseAtofAtoiAtol.ruleThe library functions atof, atoi and atol from library <stdlib.h> shall not be used.

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

}

OutputThe library functions atof, atoi and atol from the library <stdlib.h> shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 125

380

User MISRA Guidelines

DoNotUseBreakStatement.ruleThe break statement shall not be used (except to terminate the case of a switch statement).

Examplevoid foo(){ while(true) { int i=0; while (true) { i++; if (i==10) { break; /*Violation*/ } } switch( i ) { case -1: while (true) { i++; if (i==10) { break; /*Violation*/ } } break; /*Ok*/ case 0 : break; /*Ok*/ default: break; /*Ok*/ } }}

OutputThe break statement shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 58

381

User MISRA Guidelines

DoNotUseContinueStatement.ruleThe continue statement shall not be used.

Example

bool bar(int);void func(int i) { while(i--) { if (bar(i)) { continue; // Violation } }}

OutputThe continue statement shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 57

DoNotUseErrno.ruleThe error indicator errno shall not be used.

Example#include <errno.h>

void foo() {

errno=0; // violation

}

OutputThe error indicator errno shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 119

382

User MISRA Guidelines

DoNotUseFloatsAsLoopCounters.ruleFloating point variables shall not be used as loop counters.

Examplevoid foo() {

for (float i=0.;10.;i++) { // violation // does soemthing }}

OutputFloating point variables shall not be used as loop counters.

ReferenceOrigin: Misra Guidelines - Rule 65

DoNotUseGotoStatement.ruleThe goto statement shall not be used.

Examplevoid func(bool done) { if (done) { goto end; // violation} end: return; }

OutputThe goto statement shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 56

383

User MISRA Guidelines

DoNotUseLabels.ruleLabels should not be used, except in switch statements.Note: The Severity Level for this rule is Informational.

Examplevoid foo(int count) {

//.. goto stop_operation; //...

stop_operation: return; //Violation

//.. }

OutputLabels should not be used, except in switch statements.

ReferenceOrigin: Misra Guidelines - Rule 55

DoNotUseLeftShifts.ruleProvisions should be made for appropriate run-time checking.Note: The Severity Level for this rule is Informational.

Examplevoid main() { int i = 4; int j = 2; int k = j << i; /* Violation */}

OutputLeft shifting of an integer may cause the most significant bit(s) to be lost, effectively a kind of overflow.

ReferenceOrigin: Misra Guidelines - Rule 4

384

User MISRA Guidelines

DoNotUseLocaleHAndSetLocale1.rule<locale.h> and the setlocale function shall not be used.

Example#include <locale.h> // violation

void foo(void){

/* Set the locale back to the default environment */ setlocale(LC_ALL, "C"); // violation

}

OutputThe <locale.h> and the setlocale function shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 121

DoNotUseLocaleHAndSetLocale2.rule<locale.h> and the setlocale function shall not be used.

Example#include <locale.h> // violation

void foo(void){

/* Set the locale back to the default environment */ setlocale(LC_ALL, "C"); // violation

}

Output<locale.h> and the setlocale function shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 121

385

User MISRA Guidelines

DoNotUseLongIdentifiers.ruleIdentifiers shall not have more than 31 characters.

Examplevoid foo(); // okvoid this_is_not_ok_11111111111111111(); // violationclass ThisClassHasANameThatIsTooBig11111{}; // violation

OutputIdentifiers shall not have more than 31 characters.

ReferenceOrigin: Misra Guidelines - Rule 11

DoNotUseOclatConstants.ruleOctal constants (other than zero) shall not be used.

Examplevoid foo() { int code = 012; /*Violation*/ int code2 = 12; /*Ok*/

}

OutputOctal constants other than zero shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 19

386

User MISRA Guidelines

DoNotUseOffsetof.ruleThe macro offsetof, in library <stddef.h>, shall not be used. Note: The CodeWizard option 'pproanalyze off' must be set to be able to enforce this rule.

Example

#include <stddef.h>

struct S{ int x, y, z; char buffer [128];};

int main(){ int i= offsetof( S, buffer); // Violation return 0;}

OutputThe macro offsetof shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 120

387

User MISRA Guidelines

DoNotUsePointerArithmetic.rulePointer arithmetic should not be used.Note: The Severity Level for this rule is Informational.

Examplevoid foo() {

int* a; int* b;

int tab[10];

a=tab; a++; // violation --a; // violation

b = a+5; // violation

}

OutputFor all outputs: Pointer arithmetic shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 101

DoNotUseRecursion.ruleFunctions shall not call themselves, either directly or indirectly.Note: This rule only checks for direct recursion.

Examplevoid foo1(int l) { int x=l;

if (l > 0) { foo1(x-1); // violation }

}

void foo2() { // OK // empty}

388

User MISRA Guidelines

void foo3(); // OK

void foo5(int);

void foo4(int l) {

int x=l;

if (l > 0) { foo5(x-1); // OK - cannot check indirect recursion }

}

void foo5(int l) {

int x=l;

if (l > 0) { foo4(x-1); // OK - cannot check indirect recursion }

}

void foo6() { foo2(); // OK}

OutputDo not use recursion.

ReferenceOrigin: Misra Guidelines - Rule 70

389

User MISRA Guidelines

DoNotUseRegisterStorageClass.ruleThe register storage class specifier shall not be used.Note: The Severity Level for this rule is Informational.

Examplevoid foo() {int a; // okregister int b; // violation

}

OutputThe register storage class specifier shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 28

DoNotUseRelationalOpsOnPointers.ruleRelational operators shall not be applied to pointer types.

Examplevoid foo() {

int* a; int* b;

int tab[10];

a=tab;

b = a+5;

if (a > b) { // violation } if ( b <= a) { // violation }

}

OutputPointer arithmetic shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 103

390

User MISRA Guidelines

DoNotUseSetjmpAndLongjmp.ruleThe setjmp macro and the longjmp function shall not be used.

Example

#include <setjmp.h>

jmp_buf mark; /* Address for long jump to jump to */int fperr; /* Global error number */

void foo( void ){ int jmpret; jmpret = setjmp( mark ); // violation}

void fphandler( int sig, int num ){

longjmp( mark, -1 ); // violation}

Outputsetjmp macro and longjmp function shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 122

DoNotUseSignalH.ruleThe signal handling facilities of <signal.h> shall not be used.

Example#include <signal.h> // violation

OutputThe signal handling facilities of <signal.h> shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 123

391

User MISRA Guidelines

DoNotUseStdioH.ruleThe input/output library <stdio.h> shall not be used in production code.

Example#include <stdio.h> // violation

OutputThe input/output library <stdio.h> shall not be used in production code.

ReferenceOrigin: Misra Guidelines - Rule 124

DoNotUseTimeH.ruleThe time handling functions of library <time.h> shall not be used.

Example#include <time.h> // violation

OutputThe time handling functions of library <time.h> shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 127

392

User MISRA Guidelines

DoNotUseTriGraphs.ruleTrigraphs shall not be used.

Example??=define TEST 1

void foo() { const char * s1 = "(Date should be in the form ??-??-??)"; /* violation */ const char * s2 = "(Date should be in the form ~~]";}

OutputAll occurrences in a source file of the following sequences of three charac-ters (called trigraph sequences) are replaced with the corresponding single character.??= #??( [??/ \??) ]??' ^??< {??! |??> }??- ~If the compiler has a switch to ignore trigraphs then this option should be used, or alternatively ensure that two adjacent question marks are never used in the code.

ReferenceOrigin: Misra Guidelines - Rule 7

393

User MISRA Guidelines

DoNotUseUndef.rule#undef should not be used.Note: The Severity Level for this rule is Informational.

Example#undef TEST

Output#undef should not be used.

ReferenceOrigin: Misra Guidelines - Rule 92

DoNotUseUnions.ruleUnions shall not be used.

Exampleunion U1{ int _i; char _buf[sizeof(int)];};

OutputOverlapping variable storage shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 109

394

User MISRA Guidelines

DoNotUseVariableNumberOfArgs1.ruleFunctions with variable numbers of arguments shall not be used.

Examplevoid foo(int, ...) { // Violation

}

OutputFunctions with variable numbers of arguments shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 69

DoNotUseVariableNumberOfArgs2.ruleFunctions with variable numbers of arguments shall not be used.

Example/* VA.C: The program below illustrates passing * a variable number of arguments using the * following macros: * va_start va_arg va_end * va_list va_dcl (UNIX only) */

#include <stdio.h>#define ANSI /* Comment out for UNIX version */#ifdef ANSI /* ANSI compatible version */#include <stdarg.h>int average( int first, ... );#else /* UNIX compatible version */#include <varargs.h>int average( va_list );#endif

void main( void ){ /* Call with 3 integers (-1 is used as terminator). */ printf( "Average is: %d\n", average( 2, 3, 4, -1 ) );

/* Call with 4 integers. */ printf( "Average is: %d\n", average( 5, 7, 9, 11, -1 ) );

/* Call with just -1 terminator. */ printf( "Average is: %d\n", average( -1 ) );}

395

User MISRA Guidelines

/* Returns the average of a variable list of integers. */

#ifdef ANSI /* ANSI compatible version */int average( int first, ... ) // Violation{ int count = 0, sum = 0, i = first; va_list marker;

va_start( marker, first ); // Violation while( i != -1 ) { sum += i; count++; i = va_arg( marker, int); // Violation } va_end( marker ); // Violation return( sum ? (sum / count) : 0 );}

#else /* UNIX compatible version must use old-style definition. */int average( va_alist )va_dcl{ int i, count, sum; va_list marker;

va_start( marker ); // Violation for( sum = count = 0; (i = va_arg( marker, int)) != -1; count++ ) // Vio-lation sum += i; va_end( marker ); // Violation return( sum ? (sum / count) : 0 );}#endif

OutputFunctions with variable numbers of arguments shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 69

396

User MISRA Guidelines

DoNotUseWideStringLiterals.ruleWide string literals shall not be used.

Example#include <stddef.h>

void foo() {

wchar_t* x = L"Fred"; // Violation

}

OutputWide strings literals shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 8

ExpressionEvaluation1.ruleDo not use the volatile keyword.

Example

void foo1() {

volatile int v; // violation

}

OutputDo not use the volatile keyword.

ReferenceOrigin: Misra Guidelines - Rule 46

397

User MISRA Guidelines

ExpressionEvaluation2.ruleThe value of an expression shall be the same under any order of evaluation that the standard permits.

Examplevoid foo46b() { int a = 0; int b = 0; a = ++a + b++; /* complain */ return;}

OutputUsing of complex expression is error-prone.

ReferenceOrigin: Misra Guidelines - Rule 46

ExpressionEvaluation3.ruleThe value of an expression shall be the same under any order of evaluation that the standard permits.

Examplevoid foo46c(){ int array[3] = {0}; int iVar = 1; array[iVar++] = iVar; /* complain */ return;}

OutputUsing of increment the variable in the context of table indexing.

ReferenceOrigin: Misra Guidelines - Rule 46

398

User MISRA Guidelines

ExpressionEvaluation4.ruleThe value of an expression shall be the same under any order of evaluation that the standard permits.

Examplevoid foo46(){ int array[3] = {0}; int iVar = 1; array[iVar] = --iVar; /* complain */ return;}

OutputModification of the index in context of its using.

ReferenceOrigin: Misra Guidelines - Rule 46

FloatingInBitwiseExpressions1.ruleThe underlying bit representations of floating point numbers shall not be used.

Examplevoid moo(int i,float f) {

float x,y; double d; long j; float k = x|i; /* violation */ k=j&i; /* OK */ int l; l=~d; /* violation */}

OutputThe underlying bit representations of floating point numbers shall not be used in any way by the programmer.

ReferenceOrigin: Misra Guidelines - Rule 16

399

User MISRA Guidelines

FloatingInBitwiseExpressions2.ruleThe underlying bit representations of floating point numbers shall not be used.

Examplevoid moo(int i,float f) {

float x,y; double d; long j; float k = x|i; /* violation */ k=j&i; /* OK */ int l; l=~d; /* violation */}

OutputThe underlying bit representations of floating point numbers shall not be used in any way by the programmer.

ReferenceOrigin: Misra Guidelines - Rule 16

400

User MISRA Guidelines

FullySpecifyMembersOfStructOrUnion.ruleAll members of structure or union should be fully specified.

Examplestruct Z { int z;};

/* violation */struct Y1 { struct X* p; struct Z* z; int i;};

/* OK */struct Y2 { struct Z* z; int i;};

OutputIn the specification of a structure or union type, all members of the struc-ture or union shall be fully specified.

ReferenceOrigin: Misra Guidelines - Rule 108

401

User MISRA Guidelines

ImplicitConversionLosesInfo1.ruleImplicit conversions which may result in a loss of information shall not be used.

Examplevoid foo() {

int a1,b1; float a2,b2;

if (a1>b1) {} // ok if (a1==b2) {} // violation if (a2!=b2) {} // ok

if (a1+(a2*b2) > a2) {} // violation

}

OutputLIST(A) # LIST(B)

ReferenceOrigin: Misra Guidelines - Rule 43

402

User MISRA Guidelines

ImplicitConversionLosesInfo2.ruleImplicit conversions which may result in a loss of information shall not be used.

Examplevoid foo2() {

signed int si; unsigned int ui;

ui=si; // violation si=ui; // violation }

OutputImplicit conversion which may result in a loss of information shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 43

IncludeStatements.rule#include statements in a file shall only be preceded by other preprocessor directives or comments.

Examplevoid foo();

int g;

#include "test.h"

void main() { }

OutputAll the #include statements in a particular code file should be grouped together near the head of the file. It is important to prevent the situa-tion 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.

ReferenceOrigin: Misra Guidelines - Rule 87

403

User MISRA Guidelines

InitializeVariablesAtDeclaration.ruleAll automatic variables shall be initialized at declaration.

Examplevoid foo1() { int a; // violation int b=1; // ok int* ptr1; // ok}

OutputAll automatic variables shall be initialized at declaration.

ReferenceOrigin: Misra Guidelines - Rule 30

InvalidRangeOfShiftOperand.ruleThe right hand operand of a shift operator shall lie between zero and one less than the width in bits of the left hand operand (inclusive).Note: This rule was prepared for 32 bit integer.

Examplevoid foo() { unsigned int uVal = 1u; uVal <<= 2; /* Ok */ uVal <<= 100; /* Violation */}

OutputBitwise operations shall not be performed on signed integer types.

ReferenceOrigin: Misra Guidelines - Rule 38

404

User MISRA Guidelines

MakeDeclarationsStaticAtFileScope.ruleAll declarations at file scope should be static where possible.Note: The Severity Level for this rule is Informational.

Examplestatic int g1; // Ok

int g2; // violation

void foo1() ; // violation

static void foo2(); // ok

OutputAll declarations at file scope should be static where possible.

ReferenceOrigin: Misra Guidelines - Rule 23

MixedPrecisionArithmetic1.ruleMixed precision arithmetic should use explicit casting to generate the desired result.Note: The Severity Level for this rule is Informational.

Examplevoid foo48b(){ int iVar = 2; long lVar = 1; float fVar = 1.0; iVar = (((iVar==2) ? fVar : lVar) + 22); /* complain */ iVar = (((iVar==2) ? (int)fVar : (int)lVar) + 22); /* OK */

return;}

OutputNot all operators operate on the same data type.

ReferenceOrigin: Misra Guidelines - Rule 48

405

User MISRA Guidelines

MixedPrecisionArithmetic2.ruleMixed precision arithmetic should use explicit casting to generate the desired result.Note: The Severity Level for this rule is Informational.

Examplevoid foo48c(){ int iVar = 2; long lVar = 1; float fVar = 1.0; iVar = (((iVar==2) ? lVar : fVar ) + 22);

/* complain */ iVar = (((iVar==2) ? lVar : (int)fVar ) + 22);

/* OK */

return;}

OutputNot all operators operate on the same data type.

ReferenceOrigin: Misra Guidelines - Rule 48

406

User MISRA Guidelines

MixedPrecisionArithmetic3.ruleMixed precision arithmetic should use explicit casting to generate the desired result.

Examplevoid foo48a(){ int iVar = 2; long lVar = 1; float fVar = 1.0; fVar -= lVar; /* complain */ fVar -= (float)lVar; /* OK */ return;}

OutputNot all operators operate on the same data type.

ReferenceOrigin: Misra Guidelines - Rule 48

MixedPrecisionArithmetic4.ruleMixed precision arithmetic should use explicit casting to generate the desired result.

Examplevoid foo48(){ int iVar = 2; long lVar = 1; float fVar = 1.0; fVar = lVar/iVar; /* complain */ fVar = 34 + (float)lVar/(float)iVar - 2; /* OK */ return;}

OutputNot all operators operate on the same data type.

ReferenceOrigin: Misra Guidelines - Rule 48

407

User MISRA Guidelines

NameBitFields.ruleAll the members of a structure (or union) shall be named.

Exampletypedef signed int t;typedef int plain;struct tag { unsigned t:4; const t:5; /* violation */ plain r:5;};

OutputThe "bit field" facility in C is one of the most poorly defined parts of the language. There are two main uses to which bit-fields could be put:

1. To access individual bits, or group of bits, in larger data-types, in conjunction with unions (see rule 110).

2. To allow flags or other short-length data to be packed to save storage space. The packing together of short-length data to economise on storage is the only acceptable use of bit fields envisaged in this document.

Provided the elements of the structure are only ever accessed by their name, the programmer needs to make no assumptions about the way the bit fields are stored within the structure. This rules checks that all declared bit fields have names.

ReferenceOrigin: Misra Guidelines - Rule 113

408

User MISRA Guidelines

NullPointerDereferenced1.ruleThe NULL pointer shall not be dereferenced.

Example#include <stdlib.h>

int* foo();

struct T{ int _i;};

void bar() {

int* p; int j; struct T * tPtr;

p = foo(); j=*p; /* violation */

if (p != 0) { j=*p; /* OK */ j= (*p) + 1; /* OK */ }

tPtr = malloc(sizeof(struct T)); tPtr->_i = 1; /* violation */ free(tPtr);}

OutputThe NULL pointer shall not be dereferenced.

ReferenceOrigin: Misra Guidelines - Rule 107

409

User MISRA Guidelines

NullPointerDereferenced2.ruleThe NULL pointer shall not be dereferenced.

Example#include <stdlib.h>

int* foo();

struct T{ int _i;};

void bar() {

int* p; int j; struct T * tPtr;

p = foo(); j=*p; /* violation */

if (p != 0) { j=*p; /* OK */ j= (*p) + 1; /* OK */ }

tPtr = malloc(sizeof(struct T)); tPtr->_i = 1; /* violation */ free(tPtr);}

OutputThe NULL pointer shall not be dereferenced.

ReferenceOrigin: Misra Guidelines - Rule 107

410

User MISRA Guidelines

PointerNonPointerCast.ruleType casting from any type to or from pointers shall not be used.

Examplevoid foo45(){ char *cPtr = 0; int iVar = 0; void *vp = 0; cPtr = (char *)iVar; /* complain */ vp = (void *)iVar; /* complain */ return;}

void foo45a(){ int iVar = 0; short array[3] = {0}; iVar = (int)array; /* complain */ return;}

OutputUsing of casting a non-pointer type to a pointer type.

ReferenceOrigin: Misra Guidelines - Rule 45

411

User MISRA Guidelines

PreferConditionalCompilation.ruleSections of old code should not be "commented out". Disabling of sections of code should be achieved by use of conditional compilation (e.g. #if or #ifdef constructs).Note: The Severity Level for this rule is Informational.

Examplevoid foo() { int dVal = 5;

/* Violation *//* if (dVal==0) { //...code }*/

/* Ok */#if 0 if (dVal==0) { //...code }#endif}

OutputSection of code should not be 'commented out'.

ReferenceOrigin: Misra Guidelines - Rule 10

PreferFunctionsOverMacros.ruleA function should be used in preference to a function -like macro.Note: The Severity Level for this rule is Informational.

Example#define PI 3.1416 // OK#define test() "this is a string" // OK

#define SUM(A,B) ((A)+(B)) // violation

OutputA function should be used in preference to a function-like macro.

ReferenceOrigin: Misra Guidelines - Rule 93

412

User MISRA Guidelines

ProvideAllOrNoneArgumentNames.ruleIdentifiers shall either be given for all of the parameters in a function prototype declaration, or for none.

Examplevoid foo(); // Ok

void foo1(int, int); // Ok

void foo2(int a, int b); // Ok

void foo3(int a, int); // Violation

void foo4(int a, int, int b); // Violation

OutputIdentifiers shall be given for all parameters, or none.

ReferenceOrigin: Misra Guidelines - Rule 73

ProvideExplicitReturnType.ruleEvery function shall have an explicit return type.

Example/* compilable by cl.exe */

int goo(void); /*Ok*/foo(void); /*Violation*/

OutputEvery function shall have an explicit return type.

ReferenceOrigin: Misra Guidelines - Rule 75

413

User MISRA Guidelines

ProvideFinalDefaultForSwitch1.ruleAll switch statements should contain a final default clause.

Examplevoid foo(int i) { switch(i) /*Violation*/ { case 0 : i++; switch(i) { case 0 : break; default: ; }

case 1 : i++; break; }}

OutputThere is no default clause in switch statement.

ReferenceOrigin: Misra Guidelines - Rule 62

ProvideFinalDefaultForSwitch2.ruleAll switch statements should contain a final default clause.

Examplevoid foo(int i) { switch(i) /*Violation*/ { case 0 : break; }}

OutputThere is no default clause in switch statement.

ReferenceOrigin: Misra Guidelines - Rule 62

414

User MISRA Guidelines

ProvideFinalElseClause.ruleAll if, else if constructs should contain a final else clause.Note: The Severity Level for this rule is Informational.

Examplevoid foo(int x){

if ( x < 0) { // ok // }

if ( x < 0) { // Ok // } else { // }

if ( x < 0) { // } else if (x > 0) { // Violation // } if ( x < 0) { // } else if (x > 0) { // Ok // } else { }

}

OutputAll if+else if constructs should contain a final else clause.

ReferenceOrigin: Misra Guidelines - Rule 60

415

User MISRA Guidelines

ProvideSingleExitPointFromFunc.ruleA function should have a single point of exit.Note: The Severity Level for this rule is Informational.

Exampleint foo1(int a) { // Violation if (a>0) { return 1; } else { return 0; }}

int foo2(int a) { // Ok int l; if (a>0) { l=1; } else { l=0; }

return l;

}

OutputA function should have a single point of exit.

ReferenceOrigin: Misra Guidelines - Rule 82

416

User MISRA Guidelines

PutNullStatementsInTheirOwnLine1.ruleA null statement shall only occur on a line by itself, and shall not have any other text on the same line.

Example

void foo() { /*Violation*/ int dVal;; }

OutputA null statement shall only occur on a line by itself.

ReferenceOrigin: Misra Guidelines - Rule 54

PutNullStatementsInTheirOwnLine2.ruleA null statement shall only occur on a line by itself, and shall not have any other text on the same line.

Examplevoid foo(int dVal) { /*Violation*/ if (dVal==0) { ; /*Comment in this place is also violation*/ }

/*Ok*/ if (dVal==0) { ; }}

OutputA null statement shall only occur on a line by itself.

ReferenceOrigin: Misra Guidelines - Rule 54

417

User MISRA Guidelines

ReturnOfNonVoidFunctionMustHaveExpression.ruleFor each function with non-void return value, each return shall have an expression.

Example/* compilable by 'c' compiler */

void foo1() {

return; // Ok

}

int foo2() {

return ; // violation

}

int foo3() {

return 0; // ok

}

OutputEach return should have an expression.

ReferenceOrigin: Misra Guidelines - Rule 83

418

User MISRA Guidelines

ReturnOfVoidFunctionMustNotHaveExpression.ruleFor functions with void return type, return statements shall not have an expression.

Example/* compilable by 'c' compiler */

void foo1() { // Ok return;}

void foo2() { // violation return 1;}

void foo3() { // violation int a=0; return a;}

void foo4(int a) { // Violation return a;}

OutputIn function with void return type, return statement shall not have an expression.

ReferenceOrigin: Misra Guidelines - Rule 84

419

User MISRA Guidelines

ReturnValueVoidShallNotBeUsed.ruleThe values returned by void functions shall not be used.

Examplevoid foo();int moo();

void var() {

int j;

j=foo(); /* violation */

foo(); /* OK */

j=moo(); /* OK */

}

OutputThe values returned by void functions shall not be used.

ReferenceOrigin: Misra Guidelines - Rule 79

420

User MISRA Guidelines

TerminateCaseWithBreak.ruleEvery non-empty case clause in a switch statement shall be terminated with a break statement.

Examplevoid foo(int i) { switch(i) { case 0 : i++;/*Violation*/ case 1 :/*Ok*/ i++; break; case 3 :/*Ok (empty case)*/ case 4 : break; case 5: i++;/*Violation*/ default: ; }}

OutputEvery non-empty clause in a switch statement shall be terminated with a break statement.

ReferenceOrigin: Misra Guidelines - Rule 61

421

User MISRA Guidelines

TestErrorInformation.ruleIf a function return error information, then that error information should be tested.

Exampleint foo1();void foo2();int foo3();

void moo() { int i; i=foo1(); /* OK */ foo1(); /* violation */ (void)foo1(); /* OK */ foo2(); /* OK */

if (foo1()!=0) {} /* OK */ if (1) {

foo1(); /* violation */ } if (foo1()) {

foo3(); /* violation */ }

}

OutputThis rule assumes that error information is returned as function return value, any time return rype is integer, and it triggers when this return value is not somehow used.

ReferenceOrigin: Misra Guidelines - Rule 86

422

User MISRA Guidelines

TooManyPointerIndirectionLevels.ruleNo more than two levels of pointer indirection shall be used.Note: The Severity Level for this rule is Informational.

Exampleclass Test1 {private: int** x; // violation};

Test1** foo(); // violationTest1* foo(Test1** par); // violation

OutputNo more than two levels of pointer indirection shall be used.

ReferenceOrigin: Misra Guidelines - Rule 102

TypesSuffixForNumericConstants1.ruleNumeric constants should be suffixed to indicate type, where an appropriate suffix is available.Note: The Severity Level for this rule is Informational.

Examplevoid foo18a(){ unsigned long lVar1 = 65537; /* complain */ unsigned long lVar2 = 65537L; /* OK */ return;}

OutputUnsigned long variable $name is initialized by signed constant out of range. Use "L" suffix.

ReferenceOrigin: Misra Guidelines - Rule 18

423

User MISRA Guidelines

TypesSuffixForNumericConstants2.ruleNumeric constants should be suffixed to indicate type, where an appropriate suffix is available.Note: The Severity Level for this rule is Informational.

Examplevoid foo18b() { unsigned long arrL[] = { /* complain */ 0, 1, 32767, 32768, 65535,

65536, 2147483547, 2147483648, 4294967295 };}

OutputUnsigned long variable is initialized by signed constant out of range. Use "L" suffix.

ReferenceOrigin: Misra Guidelines - Rule 18

TypesSuffixForNumericConstants3.ruleNumeric constants should be suffixed to indicate type, where an appropriate suffix is available.Note: The Severity Level for this rule is Informational.

Examplevoid foo18(){ unsigned long lVar1 = 32768; /* complain */ unsigned long lVar2 = 32768U; /* OK */ return;}

OutputUnsigned long variable $name is initialized by signed constant out of range. Use "U" suffix.

ReferenceOrigin: Misra Guidelines - Rule 18

424

User MISRA Guidelines

TypesSuffixForNumericConstants4.ruleNumeric constants should be suffixed to indicate type, where an appropriate suffix is available.Note: The Severity Level for this rule is Informational.

Examplevoid foo18c() { unsigned long arrL[] = { /* complain */ 0, 1, 32767, 32768, 65535,

65536, 2147483547, 2147483648, 4294967295 };}

OutputUnsigned long variable is initialized by signed constant out of range. Use "u" or "U" suffix.

ReferenceOrigin: Misra Guidelines - Rule 18

UseBracesToMatchStructure.ruleBraces shall be used to indicate and match the structure in the non-zero initialization of arrays and structures.

Examplevoid test() {

int a[2][2] = {1,2,3,4}; // Violation int b[2][2] = { {1,2} , {3,4}}; // Ok}

OutputUse braces to indicate and match the structure in the non-zero initializa-tion of arrays and structures.

ReferenceOrigin: Misra Guidelines - Rule 31

425

User MISRA Guidelines

UseCommaInForLoopOnly.ruleThe comma operator shall not be used, except in the control expression of a for loop.

Examplevoid foo( int, int ); // Ok

void func() { for (int i = 0; i >=0, i < 10; i++) { // ok }} void func_one(int,int,int); // okvoid func_two(int,int); // ok

void bar() { int x,y,z;

func_one( x, y + 2, z ); // ok func_two( (x--, y + 2), z ); // violation

}

OutputThe comma operator should not be used, except in the control expression of a for statement.

ReferenceOrigin: Misra Guidelines - Rule 42

426

User MISRA Guidelines

UseConsistentLinkage.ruleIdentifiers shall not simultaneously have both internal and external linkage in the same translation unit.

Examplestatic unsigned short x;static unsigned short y;

void foo(){ extern unsigned short x; /* OK */ extern unsigned short y; /* same linkage a one visible at file scope */ { extern unsigned short y; /* complain */ }}

OutputVariables LIST(B) in the block scope does not have the same linkage as the prior declaration. Has external linkage.

ReferenceOrigin: Misra Guidelines - Rule 24

427

User MISRA Guidelines

UseConstForArgsPassedByRef.ruleconst qualification should be used on function parameters which are passed by reference, where it is intended that the function will not modify the parameter.Note: The Severity Level for this rule is Informational.

Examplevoid foo1(int x) { x +=1; // OK

}

void foo2(int& x) { x +=1; // OK

x=2;}

void foo3(const int& x) { int a; // OK a=x; }

void foo4(int& x) { int a; // violation a=x; }

OutputPass argument(s) LIST(D) with const specifier.

ReferenceOrigin: Misra Guidelines - Rule 81

428

User MISRA Guidelines

UseCurlyBraces1.ruleAlways use curly brackets after if statements.

Examplevoid foo2();

void foo(int x) {

if (x>0) {} // Ok // violation if (x>0) foo2();

// violation if (x>0) foo2(); else if (x < -1) { // ok } }

OutputAlways use curly brackets after if construction.

ReferenceOrigin: Misra Guidelines - Rule 59

429

User MISRA Guidelines

UseCurlyBraces2.ruleAlways use curly brackets after else statements.

Examplevoid foo2();

void foo(int x) {

if (x>0) foo2(); else if (x < -1) { // ok } // violation if (x >0) { } else foo2();}

OutputAlways use curly brace after else construction.

ReferenceOrigin: Misra Guidelines - Rule 59

430

User MISRA Guidelines

UseCurlyBraces3.ruleAlways use curly braces after for statement.

Examplevoid foo2();

void foo(int x) {

// violation for (int i=0; i< 10; i++) foo2();

// ok for (int j=0; j< 10; j++) {}

}

OutputAlways use curly braces after for construction.

ReferenceOrigin: Misra Guidelines - Rule 59

UseCurlyBraces4.ruleAlways use curly brackets after while statements.

Examplevoid foo2();

void foo(int x) {

// ok while (x > 10) { }

// violation while (1) foo2();

}

OutputAlways use curly braces after while construction.

ReferenceOrigin: Misra Guidelines - Rule 59

431

User MISRA Guidelines

UseCurlyBraces5.ruleAlways use curly brackets after do statement.

Examplevoid foo2();

void foo(int x) { // violation do foo2(); while(1);

// Ok do { } while (1);

}

OutputAlways use curly brackets after do construction.

ReferenceOrigin: Misra Guidelines - Rule 59

432

User MISRA Guidelines

UseEmptyParensForNoArgFunc.ruleFunctions called with no parameters should have empty parentheses.Note: The Severity Level for this rule is Informational.

Exampleint foo85();

void foo() { int iVar = 0; if( foo85 == 0 ) { /* complain */ iVar++; } if( 0 == foo85 ) { /* complain */ iVar++; }}

OutputDo not use pointer to the function in condition expression.

ReferenceOrigin: Misra Guidelines - Rule 85

433

User MISRA Guidelines

UseExplicitTestsAgainstZero.ruleTest of a value against zero should be made explicit.Note: The Severity Level for this rule is Informational.

Examplevoid foo() { int x; if (x != 0) { // Ok }

if (!x) { // violation }

if (x) { // violation }}

OutputTest of a value against zero should be made explicit.

ReferenceOrigin: Misra Guidelines - Rule 49

434

User MISRA Guidelines

UseIdenticalTypesForDeclDef1.ruleFor each function parameter the type given in the declaration and definition shall be identical, and the return types shall also be identical.

Exampletypedef int MyInt;typedef MyInt MyInt2;typedef MyInt MyInt3;

class test{};

void foo0();

void foo2(int a, MyInt2 b); // Violationvoid foo2b(int a, float b);

void foo2c(test a, float b);void foo3(int a) {}

void foo2(int a, MyInt3 b) {}void foo2c(test a, float b){}

int bar2(); // ViolationMyInt bar2(){return 0;}

OutputParameter types in declaration and implementation of $function are differ-ent.

ReferenceOrigin: Misra Guidelines - Rule 72

435

User MISRA Guidelines

UseIdenticalTypesForDeclDef2.ruleFor each function parameter the type given in the declaration and definition shall be identical, and the return types shall also be identical.

Exampletypedef int MyInt;typedef MyInt MyInt2;typedef MyInt MyInt3;

class test{};

void foo0();

void foo2(int a, MyInt2 b); // Violationvoid foo2b(int a, float b);void foo2c(test a, float b);

void foo3(int a) {}

void foo2(int a, MyInt3 b) {}void foo2c(test a, float b){}

int bar2(); // ViolationMyInt bar2(){return 0;}

OutputReturn types in declaration and implementation of $function are different.

ReferenceOrigin: Misra Guidelines - Rule 72

436

User MISRA Guidelines

UseMinimalCharacterSet.ruleOnly use characters defined in ISO C standard.

Example#define test 1

void foo() { int i; char c='$'; /* violation */}

OutputOnly those characters and escape sequences which are defined in the ISO C standard shall be used.

Section 5.2.1 of the ISO C standards defines 91 characters which are the minimum source character set for all compilers. These are the only charac-ters that should be used, even if the compiler supports a larger character set, or supports alternative character sets. These characters are:

* The 26 uppercase letters of the Latin alphabet (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

* The 26 lowercase letters of the Latin alphabet (a b c d e f g h i j k l m n o p q r s t u v w x y z)

* The 10 decimal digits (0 1 2 3 4 5 6 7 8 9)

* The following 29 graphic characters (!"#%&' ()*+,-./:;<=>?[\]^_{|}~

* The space character, and control characters representing horizontal tab, vertical tab, and form feed.

ReferenceOrigin: Misra Guidelines - Rule 5

437

User MISRA Guidelines

UseOnlyInstToDefineBitFields.ruleBit fields shall only be defined to be of type unsigned int or signed int.

Exampleenum E_TAG { E1, E2};struct A1 { unsigned char f1:2; /* complain */

unsigned short f2:2; /* complain */ unsigned long f3:2; /* complain */ unsigned int f4:2; /* OK */ signed int f5:2; /* OK */ enum E_TAG f8:2; /* complain */

};

OutputOnly integral bit-fields are supported by the standard.

ReferenceOrigin: Misra Guidelines - Rule 111

UseParenthesesForMacroArgs.ruleIn the definition of a function-like macro each instance of a parameter shall be enclosed in parentheses.

Example#define MULTI_2(x) (x*2) /*Violation*/#define MULTI_2(x) ((x)*2) /*Ok*/

OutputMissing parentheses.

ReferenceOrigin: Misra Guidelines - Rule 96

438

User MISRA Guidelines

UseTheSameIdentifiersInDeclDef.ruleIf identifiers are given for any of the parameters, then the identifiers used in the declaration and definition shall be identical.

Example

void foo1(); // Ok

void foo2(int a, int b); // Ok

void foo2(int a, int b) {}

void foo4(int , int ); // Ok

void foo4(int x, int y ) {}

void foo5(int a, int b); // Violation

void foo5(int x, int y ) {}

OutputIdentifiers given in declaration and definition of $function should be iden-tical.

ReferenceOrigin: Misra Guidelines - Rule 74

439

User MISRA Guidelines

UseTypedefsForBasicTypes.ruleThe basic types of char, int, short, long, float and double should not be used, but specific-length equivalents should be typedef'd for the specific compiler, and these type names used in the code.Note: The Severity Level for this rule is Informational.

Exampletypedef signed int SI;

void foo() { signed int c; // violation int a; // violation SI b; // ok}SI bar1(); // okdouble bar2() ; // violation

OutputFor $name, use typedef equivalent of char, int, short, long, float, double.

ReferenceOrigin: Misra Guidelines - Rule 13

UseVoidForFunctionsWithNoArgs.ruleFunctions with no parameters shall be declared with parameter type void.

Examplevoid foo1(void); // OKvoid foo2(); // violation

OutputFunction $name with no parameter should be declared with parameter void.

ReferenceOrigin: Misra Guidelines - Rule 76

440

User MISRA Guidelines

VoidExpressionsAsFunctionParameter.ruleVoid expressions shall not be used as function parameters.

Examplevoid foo();

void moo1(int);void moo2(int,int);int goo();void bar () {

void *p; int a=0;

moo1(a); /* OK */ moo1(foo()); /* violation */ moo2(a,foo()); /* violation */ moo2(a,a); /* OK */ moo1(*p); /* violation */ moo1((void)goo()); /* violation */

}

OutputVoid expressions shall not be used as function parameters.

ReferenceOrigin: Misra Guidelines - Rule 80

441

Legal Notices

Legal NoticesLegal NoticesMicrosoft Legal NoticeMicrosoft©, Visual C++®, and Visual Studio .NET® Integrated Development Environment (IDE) areeither registered trademarks or trademarks of Microsoft Corporation in the United States and/or othercountries.

PCRE Library Legal NoticePCRE is a library of functions to support regular expressions whose syntax and semantics are as closeas possible to those of the Perl 5 language.

Written by: Philip Hazel

University of Cambridge Computing Service,

Cambridge, England. Phone: +44 1223 334714.

Copyright (c) 1997-2003 University of Cambridge

Permission is granted to anyone to use this software for any purpose on any computer system, and toredistribute it freely, subject to the following restrictions:

1. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULARPURPOSE.

2. The origin of this software must not be misrepresented, either by explicit claim or by omission.In practice, this means that if you use PCRE in software which you distribute to others, com-mercially or otherwise, you must put a sentence like this

"Regular expression support is provided by the PCRE library package, which is open sourcesoftware, written by Philip Hazel, and copyright by the University of Cambridge, England."

somewhere reasonably visible in your documentation and in any relevant files or online helpdata or similar. A reference to the ftp site for the source, that is, to ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ should also be given in the documentation.

3. Altered versions must be plainly marked as such, and must not be misrepresented as beingthe original software.

4. If PCRE is embedded in any software that is released under the GNU General PurposeLicence (GPL), or Lesser General Purpose Licence (LGPL), then the terms of that licence shallsupersede any condition above with which it is incompatible.

The documentation for PCRE, supplied in the "doc" directory, is distributed under the sameterms as the software itself.

442

Legal Notices

Parsifal XML Parser Legal NoticeParsifal XML Parser Copyright (c) 2002-2003.Toni Uusitalo released to the public domain 2002-11-15.

Parsifal is free for both commercial and non-commercial use and redistribution, provided that author'scopyright and disclaimer are retained intact. You are free to modify Parsifal for your own use and toredistribute Parsifal with your modifications, provided that the modifications are clearly documented.

DISCLAIMER ---------- This program is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of Merchantability or fitness for a particular purpose.Please use it AT YOUR OWN RISK.

Apache Software Foundation Legal NoticeThe Apache Software License, Version 1.1. Copyright (c) 1999-2001. The Apache Software Founda-tion. All rights reserved. Redistribution and use in source and binary forms, with or without modifica-tion, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditionsand the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditionsand the following disclaimer in the documentation and/or other materials provided with the dis-tribution.

3. The end-user documentation included with the redistribution, if any, must include the followingacknowledgment:

"This product includes software developed by the Apache Software Foundation (http://www.apache.org/)." Alternately, this acknowledgment may appear in the software itself, if andwherever such third-party acknowledgments normally appear.

4. The names "Xerces" and "Apache Software Foundation" must not be used to endorse or pro-mote products derived from this software without prior written permission. For written permis-sion, please contact [email protected].

5. Products derived from this software may not be called "Apache", nor may "Apache" appear intheir name, without prior written permission of the Apache Software Foundation.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY ANDFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHESOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCEOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IFADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

====================================================

This software consists of voluntary contributions made by many individuals on behalf of the ApacheSoftware Foundation and was originally based on software copyright (c) 1999, International BusinessMachines, Inc., http://www.ibm.com. For more information on the Apache Software Foundation,please see <http://www.apache.org/>.

443

Legal Notices

Python Library Legal NoticeA. HISTORY OF THE SOFTWAREPython was created in the early 1990s by Guido van Rossum at StichtingMathematisch Centrum (CWI,see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remainsPython's principal author, although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives(CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of thesoftware.

In May 2000, Guido and the Python core development team moved to BeOpen.com to form theBeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Cre-ations (see http://www.digicool.com). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-relatedIntellectual Property. Digital Creations is a sponsoring member of the PSF.

All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition).Historically, most, but not all, Python releases have also been GPL-compatible; the table below sum-marizes the various releases.

Footnotes:

1. GPL-compatible doesn't mean that we're distributing Python under the GPL. All Pythonlicenses, unlike the GPL, let you distribute a modified version without making your changesopen source. The GPL-compatible licenses make it possible to combine Python with othersoftware that is released under the GPL; the others don't.

Thanks to the many outside volunteers who have worked under Guido's direction to makethese releases possible.

Release Derived from Year Owner GPL-compatible?

0.9.0 thru 1.2 1991-1995 CWI yes

1.3 thru 1.5.2 1.2 1995-1999 CNRI yes

1.6 1.5.2 2000 CNRI no

2.0 1.6 2000 BeOpen.com no

1.6.1 1.6 2001 CNRI no

2.1 2.0+1.6.1 2001 PSF no

2.0.1 2.0+1.6.1 2001 PSF yes

2.1.1 2.1+2.0.1 2001 PSF yes

2.2 2.1.1 2001 PSF yes

444

Legal Notices

B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISEUSING PYTHON

PSF LICENSE AGREEMENT FOR PYTHON 2.2

1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and theIndividual or Organization ("Licensee") accessing and otherwise using Python 2.2 software insource or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee anonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or dis-play publicly, prepare derivative works, distribute, and otherwise use Python 2.2 alone or inany derivative version, provided, however, that PSF's License Agreement and PSF's notice ofcopyright, i.e., "Copyright (c) 2001 Python Software Foundation; All Rights Reserved" areretained in Python 2.2 alone or in any derivative version prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or incorporates Python 2.2or any part thereof, and wants to make the derivative work available to others as providedherein, then Licensee hereby agrees to include in any such work a brief summary of thechanges made to Python 2.2.

4. PSF is making Python 2.2 available to Licensee on an "AS IS" basis. PSF MAKES NO REP-RESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUTNOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WAR-RANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE ORTHAT THE USE OF PYTHON 2.2 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.2 FORANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULTOF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.2, OR ANY DERIVA-TIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of its terms andconditions.

7. Nothing in this License Agreement shall be deemed to create any relationship of agency, part-nership, or joint venture between PSF and Licensee. This License Agreement does not grantpermission to use PSF trademarks or trade name in a trademark sense to endorse or promoteproducts or services of Licensee, or any third party.

8. By copying, installing or otherwise using Python 2.2, Licensee agrees to be bound by theterms and conditions of this License Agreement.

445

Legal Notices

C. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0

BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 11. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160

Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee")accessing and otherwise using this software in source or binary form and its associated docu-mentation ("the Software").

2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpenhereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, ana-lyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwiseuse the Software alone or in any derivative version, provided, however, that the BeOpenPython License is retained in the Software, alone or in any derivative version prepared by Lic-ensee.

3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKESNO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAM-PLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTA-TION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULARPURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRDPARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFT-WARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS ASA RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIV-ATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material breach of its terms andconditions.\

6. This License Agreement shall be governed by and interpreted in all respects by the law of theState of California, excluding conflict of law provisions. Nothing in this License Agreementshall be deemed to create any relationship of agency, partnership, or joint venture betweenBeOpen and Licensee. This License Agreement does not grant permission to use BeOpentrademarks or trade names in a trademark sense to endorse or promote products or servicesof Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on thatweb page.

7. By copying, installing or otherwise using the software, Licensee agrees to be bound by theterms and conditions of this License Agreement.

446

Legal Notices

D. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.11. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives,

having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individualor Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source orbinary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licenseea nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/ordisplay publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone orin any derivative version, provided, however, that CNRI's License Agreement and CNRI'snotice of copyright, i.e., "Copyright (c) 1995-2001 Corporation for National Research Initiatives;All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version preparedby Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute thefollowing text (omitting the quotes): "Python 1.6.1 is made available subject to the terms andconditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may belocated on the Internet using the following unique, persistent identifier (known as a handle):1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet usingthe following URL: http://hdl.handle.net/1895.22/1013".

3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1or any part thereof, and wants to make the derivative work available to others as providedherein, then Licensee hereby agrees to include in any such work a brief summary of thechanges made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NOREPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION ORWARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE ORTHAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS ARESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, ORANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of its terms andconditions.

7. This License Agreement shall be governed by the federal intellectual property law of theUnited States, including without limitation the federal copyright law, and, to the extent suchU.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Vir-ginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative worksbased on Python 1.6.1 that incorporate non-separable material that was previously distributedunder the GNU General Public License (GPL), the law of the Commonwealth of Virginia shallgovern this License Agreement only as to issues arising under or with respect to Paragraphs 4,5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed tocreate any relationship of agency, partnership, or joint venture between CNRI and Licensee.This License Agreement does not grant permission to use CNRI trademarks or trade name in atrademark sense to endorse or promote products or services of Licensee, or any third party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwiseusing Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this LicenseAgreement.

447

Legal Notices

E. CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rightsreserved.

Permission to use, copy, modify, and distribute this software and its documentation for any purposeand without fee is hereby granted, provided that the above copyright notice appear in all copies andthat both that copyright notice and this permission notice appear in supporting documentation, and thatthe name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertainingto distribution of the software without specific, written prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THISSOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, INNO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDI-RECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROMLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OROTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PER-FORMANCE OF THIS SOFTWARE.

JPython .jar file (Python implementation for Java)Legal NoticeHISTORY OF THE SOFTWAREJPython was created in late 1997 by Jim Hugunin. Jim was also the primary developer while he was atCNRI. In February 1999 Barry Warsaw took over as primary developer and released JPython version1.1. In October 2000 Barry helped move the software to SourceForge where it was renamed to Jython.Jython is developed by a group of volunteers.

The standard library is covered by the BeOpen / CNRI license. See the Lib/LICENSE file for details.

The oro regular expresion matcher is covered by the apache license. See the org/apache/LICENSE filefor details.

The zxJDBC package was written by Brian Zimmer and originally licensed under the GNU PublicLicense. The package is now covered by the Jython Software License.

Jython Changes Software License.Copyright (c) 2000, Jython Developers. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted providedthat the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditionsand the following disclaimer.

2. Redistributions in binary form must reproduce the above copy right notice, this list of conditionsand the following disclaimer in the documentation and/or other materials provided with thedistribution.

3. Neither the name of the Jython Developers nor the names of its contributors may be used toendorse or promote products derived from this software without specific prior written permis-sion.

448

Legal Notices

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FORANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAM-AGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SER-VICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ORTORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OFTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

JPython Software License.IMPORTANT: PLEASE READ THE FOLLOWING AGREEMENT CARE FULLY. BY CLICKING ONTHE "ACCEPT" BUTTON WHERE INDICATED, OR BY INSTALLING, COPYING OR OTHERWISEUSING THE SOFTWARE, YOU ARE DEEMED TO HAVE AGREED TO THE TERMS AND CONDI-TIONS OF THIS AGREEMENT.

JPython version 1.1.x1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives,

having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individualor Organization ("Licensee") accessing and using JPython version 1.1.x in source or binaryform and its associated documentation as provided herein ("Software").

2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licenseea non-exclusive, non-transferable, royalty-free, world-wide license to reproduce, analyze, test,perform and/or display publicly, prepare derivative works, distribute, and otherwise use theSoftware alone or in any derivative version, provided, however, that CNRI's License Agree-ment and CNRI's notice of copyright, i.e., "Copyright ©1996-1999 Corporation for NationalResearch Initiatives; All Rights Reserved" are both retained in the Software, alone or in anyderivative version prepared by Licensee.

Alternatively, in lieu of CNRI's License Agreement, Licensee may substitute the followingtext (omitting the quotes), provided, however, that such text is displayed prominently in theSoftware alone or in any derivative version prepared by Licensee: "JPython (Version 1.1.x) ismade available subject to the terms and conditions in CNRI's License Agreement. This Agree-ment may be located on the Internet using the following unique, persistent identifier (known asa handle): 1895.22/1006. The License may also be obtained from a proxy server on the Webusing the following URL: http://hdl.handle.net/1895.22/1006."

3. In the event Licensee prepares a derivative work that is based on or incorporates the Softwareor any part thereof, and wants to make the derivative work available to the public as providedherein, then Licensee hereby agrees to indicate in any such work, in a prominently visible way,the nature of the modifications made to CNRI's Software.

4. Licensee may not use CNRI trademarks or trade name, including JPython or CNRI, in a trade-mark sense to endorse or promote products or services of Licensee, or any third party. Lic-ensee may use the mark JPython in connection with Licensee's derivative versions that arebased on or incorporate the Software, but only in the form "JPython-based___________________," or equivalent.

449

Legal Notices

5. CNRI is making the Software available to Licensee on an "AS IS" basis. CNRI MAKES NOREPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION ORWARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE ORTHAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

6. CNRI SHALL NOT BE LIABLE TO LICENSEE OR OTHER USERS OF THE SOFTWAREFOR ANY INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS AS ARESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIV-ATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. SOME STATESDO NOT ALLOW THE LIMITATION OR EXCLUSION OF LIABILITY SO THE ABOVE DIS-CLAIMER MAY NOT APPLY TO LICENSEE.

7. This License Agreement may be terminated by CNRI (i) immediately upon written notice fromCNRI of any material breach by the Licensee, if the nature of the breach is such that it cannotbe promptly remedied; or (ii) sixty (60) days following notice from CNRI to Licensee of a mate-rial remediable breach, if Licensee has not remedied such breach within that sixty-day period.

8. This License Agreement shall be governed by and interpreted in all respects by the law of theState of Virginia, excluding conflict of law provisions. Nothing in this Agreement shall bedeemed to create any relationship of agency, partnership, or joint venture between CNRI andLicensee.

9. By clicking on the "ACCEPT" button where indicated, or by installing, copying or otherwiseusing the Software, Licensee agrees to be bound by the terms and conditions of this LicenseAgreement.

450

IndexIndex

Symbols#pragma and suppressions 25

AAction field 21

CC rules 170class field 23CodeWizard

customizing options 30customizing results 19installing 3using 10

coding standardscustom 17definition 1enforced 48

compilers supported 2configuration files 30contacting Parasoft 9

Eeditor, selecting 46embedded development 1, 13

Ffile field 23

IInsra 42–47

troubleshooting 46installation 3item field 22

LLicenseServer 6

Mmakefile 12metrics 169meyer-klaus rules 130miscellaneous rules 169misra built-in rules 89misra user rules 344

Nnaming conventions 169notes field 24

Ooracle proc files, see proc files

PParasoft, contacting 9Persistence field 21platforms supported 2proc files, codewizard support of 29psrc options 30

451

Qquality consulting 9

Rresults 11, 42

customizing 19rules

32 to 64 bit porting 170additional effective C++ 80built-in misra rules 89C 170effective C++ 49metrics 169meyers-klaus 130miscellaneous 169naming conventions 169telecom 269text 169universal coding standards 133user misra rules 344user rules 169

RuleWizard 17

Ssource, viewing 46suppressions 19, 45

adding 21and #pragma 25control panel 21, 27deleting 25example 27explanation 19moving 25saving 25

Ttechnical support 9telecom rules 269text rules 169type field 22

Uuniversal coding standards 133user rules 169

Vviolation messages

deleting 45saving/loading 46suppressing 19viewing 11, 42

452