Search

1.6 — Whitespace and basic formatting

Whitespace is a term that refers to characters that are used for formatting purposes. In C++, this refers primarily to spaces, tabs, and (sometimes) newlines. The C++ compiler generally ignores whitespace, with a few minor exceptions.

Consequently, the following statements all do the exact same thing:

Even the last statement with the newline in it compiles just fine.

The following functions all do the same thing:

One exception where the C++ compiler does pay attention to whitespace is inside quoted text, such as "Hello world!".

"Hello world!"

is different than

"Hello     world!"

and each prints out exactly as you’d expect.

Newlines are not allowed in quoted text:

Another exception where the C++ compiler pays attention to whitespace is with // comments. Single-line comments only last to the end of the line. Thus doing something like this will get you in trouble:

Basic formatting

Unlike some other languages, C++ does not enforce any kind of formatting restrictions on the programmer (remember, trust the programmer!). Many different methods of formatting C++ programs have been developed throughout the years, and you will find disagreement on which ones are best. Our basic rule of thumb is that the best styles are the ones that produce the most readable code, and provide the most consistency.

Here are our recommendations for basic formatting:

1) Your tabs should be set to 4 spaces (most IDEs have a setting where you can configure this). Some IDEs default to 3 spaces, which is a little unconventional but okay.

You can use tabs or spaces for indentation. Most major companies and style guides recommend using spaces (either 2 or 4 at a time) because it produces more consistency across all editors. Personally, I don’t find this reason compelling, and prefer tabs because they are easier to use.

(The tabs vs spaces is a debate that has gone on for 50+ years now -- there’s no right answer. Most important thing is to be consistent with the code around yours and the standards of your company, if applicable).

2) The braces that tell where a function begins and ends should be aligned with the function name, and be on their own lines:

Although some coders prefer other styles, this one is the most readable and least error prone since your brace pairs should always be indented at the same level. If you get a compiler error due to a brace mismatch, it’s very easy to see where.

3) Each statement within braces should start one tab (or 4 spaces) in from the opening brace of the function it belongs to. For example:

4) Lines should not be too long. Typically, 72, 78, or 80 characters is the maximum length a line should be. If a line is going to be longer, it should be broken (at a reasonable spot) into multiple lines. This can be done by indenting each subsequent line with an extra tab, or if the lines are similar, by aligning it with the line above (whichever is easier to read).

5) If a long line that is broken into pieces is broken with an operator (eg. << or +), the operator should be placed at the end of the line, not the start of the next line:

Not

This makes it more obvious from looking at the first line that the next line is going to be a continuation.

6) Use whitespace to make your code easier to read.

Harder to read:

Easier to read:

Harder to read:

Easier to read:

Harder to read:

Easier to read:

We will follow these conventions throughout this tutorial, and they will become second nature to you. As we introduce new topics to you, we will introduce new style recommendations to go with those features.

Ultimately, C++ gives you the power to choose whichever style you are most comfortable with, or think is best. However, we highly recommend you utilize the same style that we use for our examples. It has been battle tested by thousands of programmers over billions of lines of code, and is optimized for success.

1.7 -- Forward declarations and definitions
Index
1.5 -- A first look at operators

74 comments to 1.6 — Whitespace and basic formatting

  • himanshu

    5) If a long line that is broken into pieces is broken with an operator (eg. << or +), the operator should be placed at the end of the line, not the start of the next line:

    1
    2
        std::cout << "This is a really, really, really, really, really, really, really, " <<
                "really long line" <

    HI'
    HOW TO USE ,"+" AS A TAB
    CAN YOU  PLEASE GIVE A LITTLE EXAMPLE TO ME.

  • Pork and Beans

    Hello Alex!

    Thank you as always for providing your amazing lessons.

    I found a tiny grammatical error that I'm sure you'll like to correct.  It is near the beginning of this lesson, after the second code sample in the following text:

    "One exception where the C++ compiler does pays attention..."

    It should be "pay" instead of "pays".

    I feel that you would have wanted to know this.

    May you be right where you want to be.

    Have a great day.

  • Linyuan

    I love this Tutorial from this website. I've been looking for more than 20+ different books and webs that teaching people how to code in C++.

    and this is the best i found until now.

  • Tyler

    I've been coding for about 15 years now, reading up these pages as a refresher on C++ as I have not used it in several years. I have to say I very strongly disagree with Basic Formatting #1. I'm an extremely adamant believer in "tabs for indentation, spaced for alignment". Your reasoning for using spaces was to allow the indentation to stay the same between editors, there is no reason for this to be an advantage, maintaining alignment with code like that displayed in Basic Formatting #4 would not suffer from using tabs, you'd use a tab to indent to the scope level, then spaces to align further, in the first case for example for Basic Formatting #4 it double be 1 tab and then 4 spaces. Changing the tab size will then still maintain alignment and this way has many advantages over using only spaces that I would prefer not spend hours writing about.

    Honestly most of the people who argue for exclusively using spaces almost always come off as overly pretentious, and many of the most popular arguments for using spaces exclusively are plain and simply false or work with tabs as well. Instead of coming off as a pretentious coder version of a grammar nazi, at least discuss the alternatives instead of forcing users down a route that is highly debated. If pure space coding was entirely superior, there would be no argument, the fact that there is shows immediately that there are benefits to the other that are being ignored. Coding with spaces only is literally one of the most painful times coding I've ever dealt with, the pure added tedium dealing with the negative consequences of a system based on using more characters to solve a trivial problem is enough that my productivity goes down approximately 30% when dealing with using pure spaces. I'm more productive with keyboard navigation through code and having 24 spaces versus a handful of tabs and then a handful of spaces for additional alignment is just about the most irritating thing in the entirety of programming. I dislike dealing with 4 or 5 levels of indentation of spaces more than I get annoyed at debugging memory allocation/deallocation problems.

    • Alex

      To be clear, I'm not trying to advocate a position in the eternal tabs vs spaces debate. Personally, I use tabs, but many companies and style guides recommend spaces.

      I've rewritten recommendation 1 to try to make this a little more clear.

  • Porter

    I find it more readable to do:

    Rather than:

    Just a personal preference.

    • Alex

      A lot of people agree with you because that style is more compact, and you can fit more code on the screen.

      Personally, I like having my opening and closing braces at the same level of indentation. It makes it easier to see the indentation structure of a function or class and generally makes reading more pleasant.

      It's less important which style you choose/prefer and more important that you're consistent.

  • Richard

    BASIC FORMATTING point one, paragraph two. Do you have the words 'space' and 'tab' the wrong way around?

  • My dear c++ Teacher,
    Please comment following comment:
    Regarding 2nd easier to read example, I see more easier following:

    Indeed comments are below statements.
    Is it disadvantage?
    With regards and friendship.

    • Alex

      Generally, comments not placed on the same line as the code are placed before the line, not after. This is because the comment normally provides some sort of enlightening information about the line to come -- and you want to know that information before you try and understand the line, not after.

      I've never seen anybody place comments after the lines. That's not to say it never happens, but it's certainly not best practice, and I would not recommend it.

  • My dear c++ Teacher,
    Please let me say that in "Basic formatting", 4th recommendation, in program, in 2nd statement, text is not aligned with the previous line. In the following program is aligned:

    Also in 5th recommendation, in program, edl are not preceded by std::.
    With regards and friendship.

  • My dear c++ Teacher,
    please let me send you program with your second snippet and output capability.

    With regards and friendship.

  • Leander

    Love these sort of guidelines. As a new programmer it's hard to tell what is considered good practice and what is frowned upon even if it won't prevent your program from functioning correctly.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]