Home > Articles > Programming > C/C++

Top Ten Tips for Correct C++ Coding

  • Print
  • + Share This
Brian Overland, long-time Microsoft veteran and author of C++ Without Fear: A Beginner's Guide That Makes You Feel Smart, 2nd Edition, shares 10 of his most hard-earned, time-saving insights from decades of writing and debugging C++ code.
Like this article? We recommend

My first introduction to the C family of languages was decades ago (yes, I know this dates me horribly). Later I learned C++. I wish someone back then had steered me around the most obvious potholes; it might have saved me hundreds of frustrating hours.

I can give you at least a few of those much-needed (excuse the term) pointers. This isn’t a tutorial on C++ but a guide for those in the middle of learning it. But let’s face it—with C++, there’s always something to learn.

What follows are 10 of the more important things to keep in mind if you want to write polished, professional C++ code that is easy to maintain and less likely to need debugging—so I am actually more exacting here in this article than I sometimes am in my book, C++ Without Fear, Second Edition.

These guidelines are in no particular order (sorry David Letterman), except that the earlier items are addressed more to mistakes that beginners have trouble with.

#1: Don’t Confuse Assign (=) with Test-for-Equality (==).

This one is elementary, although it might have baffled Sherlock Holmes. The following looks innocent and would compile and run just fine if C++ were more like BASIC:

if (a = b)
     cout << "a is equal to b.";

Because this looks so innocent, it creates logic errors requiring hours to track down within a large program unless you’re on the lookout for it. (So when a program requires debugging, this is the first thing I look for.) In C and C++, the following is not a test for equality:

a = b

What this does, of course, is assign the value of b to a and then evaluate to the value assigned.

The problem is that a = b does not generally evaluate to a reasonable true/false condition—with one major exception I’ll mention later. But in C and C++, any numeric value can be used as a condition for “if” or “while.

Assume that a and b are set to 0. The effect of the previously-shown if statement is to place the value of b into a; then the expression a = b evaluates to 0. The value 0 equates to false. Consequently, a and b are equal, but exactly the wrong thing gets printed:

if (a = b)     // THIS ENSURES a AND b ARE EQUAL...
     cout << "a and b are equal.";
else
     cout << "a and b are not equal.";  // BUT THIS GETS PRINTED!

The solution, of course, is to use test-for-equality when that’s what you want. Note the use of double equal signs (==). This is correct inside a condition.

// CORRECT VERSION:
if (a == b)
     cout << "a and b are equal.";

#2: Do Get Rid of “Magic Numbers”

Magic number refers to a literal number that pops up in a program without explanation. Most seasoned programmers prefer to see a program consisting of nothing but symbolic names like MAX_ROWS, SCREEN_WIDTH, and so on.

In short, professional computer programmers—some of the most mathematically inclined people around—really hate numbers!

A bit of history helps explains why. Back in the 1940s, all programming was in machine code, consisting of nothing but raw bit patterns. Programmers lived in the lowest circle of hell, having to constantly translate these patterns. Programming became a thousand times easier when assembly language enabled the use of symbolic names.

And even today, programmers tend to dislike declarations like these:

char input_string[81];

81 is a “magic number.” Where does it come from? The better policy is to control the use of numbers with #define or enum statements.

#define SCREEN_WIDTH 80

SCREEN_WIDTH is more meaningful than 81, and if you decide to reset this width later, you need change only one line in the program. That change is then automatically reflected in statements such as:

int input_string[SCREEN_WIDTH + 1];

#3: Don’t Rely on Integer Division (Unless That’s What You Want)

The integer type (int in the C/C++ family, along with short, long, and now long long) is to be preferred whenever you don’t need to store fractional quantities—for a lot of good reasons, which I won’t go into here.

But sometimes, integer quantities are part of larger expressions that do involve fractions. Here’s an example from my boo, C++ Without Fear:

cout << results / (n / 10);

The program generates random numbers between 0 and 9; each should come up about 1/10th of the time. The total “hits” for each number is then compared to the expected total, N/10. So if the results (total hits) for the number 3 is, say, 997, and there are 10,000 trials, the number 997 is compared to the expected hits—in this case, 1000.

But results, n, and 10 are all integers. So 997 is divided by 1000, producing[el] zero!

Wait a moment. We were supposed to get 0.997. What went wrong?

Integer division rounds down, producing a nice integer result. The remainder is thrown away. This isn’t necessarily as bad as it seems. C++ provides two separate operations: division and remainder division:

int dividend = n / m;   // Put ratio here.
int remainder = n % m;  // Put remainder here.

By the way, the previous code fragment example used a—shudder!—magic number, 10. But the next section addresses the bigger problem: loss of data.

#4: Do Use Data Promotion to Control Results

In mixed integer/floating-point expressions, integer operands are promoted to type double. Consequently, this expression produces what we want:

cout << results / (n / 10.0);

Note that 10.0, though having no fraction, is stored as type double; this causes C++ to promote n and results to type double as well, and then carries out floating-point division.

Other ways to produce this effect include use of data casts:

cout << results / (n / (double) 10);
cout << results / (n / static_cast<double>(10));

#5: Don’t Use Non-Boolean Conditions (Except with Care)

Designed originally to help write operating systems, the C language was meant to give programmers freedom—not only to manipulate data at a machine-code level (through the use of pointers) but also to write shortcuts. Shortcuts are dangerous for beginners but sometimes nice for programmers who know what they’re doing. If they’re willing to live dangerously.

One of the most elegant tricks is the following, a slick way of saying “Do something N times:”

while (n--) {
     do_something();
}

You can make this even shorter:

while (n--) do_something();

Again, we’re dealing with the rule that any numeric value can be a condition in C and C++. When n becomes 0, after being decremented once each trip through the loop, the loop ends. But there are problems: What if n contains an initial negative value? Then the loop I’ve just shown goes on forever, or at least goes to the lowest negative value before overflowing. That can really ruin your day.

In general, then, only expressions that are strict Boolean (that is, true/false) expressions should be used as conditions.

while (n-- > 0) {
     do_something();
}

There’s one major exception. The shortcut makes sense when dealing with a pointer set to NULL (that is, 0) when an operation fails. Effectively, NULL means false. A null pointer can also be used in the context of a linked list to indicate a pointer that is at the end of the list, with its next_node member pointing nowhere (Nowheresville, they said in the 1950s and 1960s). In the following case, a null pointer means a file-open failed:

if (! file_pointer) {
     cout << "File open failed.";
     return ERROR_CODE;
}

By the way, this is one place where you might want to use an assignment inside a condition:

if (! (file_pointer = open_the_file(args))) {
     cout << "File open failed.";
     return ERROR_CODE;
}

#6: Do Use using Statement, Especially with Smaller Programs

Technically, common data-stream objects cin and cout are members of the std namespace, requiring you to write code like this:

std::cout << "Hello." << std::endl;

What a load of extra work! (And what a load.) For most programming, I strongly recommend bringing in the entire std namespace, thus eliminating the need to use the std:: prefix with cin, cout, etc. Just place the following at the beginning of every program:

using namespace std;

#7: Don’t Use Global Variables Except to Communicate Between Functions

Only a few words need be said about this one. Programmers sometimes ask themselves whether to make a variable local or global. The rule is simple: If a variable is used to store information that communicates between functions, either make the variable into a parameter (part of an argument list), passing the information explicitly, or make it global.

When information is to be shared between several functions, it’s often most practical to just go with global variables. In syntactic terms, this means declaring them outside all function definitions.

The reason for using relatively few variables global is clear: With global variables, the internal actions of one function can interfere with the internal actions of other functions—often unintentionally, especially in a large program. So try to make most variables local if you can. Enough said.

#8: Do Use Local Variables with the for Statement

With all but the most ancient versions of C++, the slickest way to localize a variable is to declare a loop variable inside of a for statement. This ability was not always supported, so old-timers like me sometimes need reminding that you can do this.

for (int i = 1; i <= n; i++) {  // Declare i inside the loop.
     cout << i << " ";          // Print out numbers 1 to n.
}

In the case of for loops, it’s rare that the final value of i, the loop variable, will be used later in the program (although that does happen occasionally). Generally speaking, you’re going to want to use a variable such as i for a loop counter and then throw it away when you’re done. Making i local to the loop itself is not only a slick way to save some space, but it’s safer programming.

One of the benefits of this use of for is that it automatically takes care of having to initialize i, a local variable. Yes, it can be extra work, but initializing a local variable is something you ideally ought to do—although it is tempting to leave it uninitialized if the very first statement in the function is going to set the variable’s value. Nonetheless, the most correct programs tend to initialize their locals:

void do_stuff() {
     int n = 0;   // Number of repetitions
     int i = 0;   // Loop counter.

Remember that initialized global variables (including objects) contain all-zero values, while uninitialized locals (including objects) contain garbage—garbage being a technical term for “meaningless, useless value that is likely to blow up your program.”

#9: Don’t Be Intimidated into Overusing Classes and Objects

This is a general philosophical pointer. When people start programming in C++, they’re typically told to make every data structure into a class and to make every function a class member.

But object-oriented programming (OOP), which was so hyped in the 1990s and in the early years of the millennium, has suffered a bit of a backlash in the last few years. The truth is, for short console-output-oriented programs, it’s nearly impossible to find examples in which classes and objects save programming effort. On the contrary, programs that unnecessarily use classes take up more space.

Why use classes at all, then? Consider that object-oriented concepts were pioneered by the same people who came up with graphical-user interface (GUI)[el] no, not Microsoft, and not Apple, despite its claims. The originator of both these technologies was PARC, the Palo Alto Research Center.

It’s not surprising, then, that classes and objects provide best and highest use within a graphical or event-driven system. An object—or instance of a class—is a self-contained data item with both state and behavior, meaning it knows how to respond to requests for services. This fits the GUI model very well.

Beyond that, I recommend mastering the basics of class and object syntax so you can take advantage of the Standard Template Library (STL). The STL provides a lot of rich facilities, including strings, lists, and stacks, that simplify a lot of programming tasks.

#10: Do Remember: Semi’s After Class Declarations, Not Functions

Once you do start defining classes, don’t get tripped up by the syntax.

BASIC programmers sometimes complain, “I don’t want to have to think about how often to use a semicolon goes.” This made them dislike Pascal. C and C++ are at least a little better; the semicolon (;) is not a statement separator but a statement terminator, making its use more consistent.

But you don’t terminate a compound statement with a semi:

if (a == b) {
     cout << "a and b are equal.";
}

So the rule is to terminate each statement with a semicolon, but don’t follow a closing brace with a semicolon. Consequently, function definitions are not semicolon-terminated.

There is one major exception: Each class declaration (including struct and union declarations) must be terminated with a semicolon:

class Point {
  public:
    int x;
    int y;
};

Now we can state the full syntax rule in C/C++:

  1. Terminate each statement with a semicolon.
  2. Don’t follow a closing brace with a semicolon unless it ends a class declaration, in which case it’s required.

Summary

Programming in C++ (or for that matter, in any language) is a life-long pursuit, and you never stop learning. In this article, I’ve looked at just the tip of the iceberg; however, in my programming experience going all the way back to the 1980s and even earlier, the issues in these article are points that, for me at least, come up again and again.

Among the more important ideas: Use the right operator for the right task (don’t confuse = and ==); pay attention to the effect of data types in math operations; be extra-careful about tempting shortcuts, such as while(n—); use local variables within for loops; and use meaningful symbolic names as much as possible. To be honest, I sometimes cut corners myself for very simple programs, but when you get into complex programming, following these guidelines will save you a lot of headache—if not heartache!

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020