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 pays 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 fine too.

The reason to use spaces instead of tab characters is so that if you open your code in another viewer, it’ll retain the correct indentation.

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 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
Index
1.5 -- A first look at operators

30 comments to 1.6 — Whitespace and basic formatting

  • Cody

    The code examples which all display “Hello World!” are not all correct. The one at line has no semicolon so it would not work.

    [ Fixed! Thanks for the note. -Alex ]

  • kon_nos

    Is this format affecting the size or the speed of the compiled code?

  • I like the way you are slowly introducing new elements to the language.

  • Ter

    Thanks for making things easy to understand.

  • Ian

    Is it generally acceptable in programming communities to “box in” your code with the curly brackets? To me at least, that looks easier to read and is less of an eyesore. For instance this is what I mean:

    Beware, my screen resolution is high so it all fits on my screen, don’t know about yours.

    • Ian

      Actually, forget I asked that, I got to 1.10 and discovered a problem with doing that, it seems to cause the compiler to choke on preprocessor directives if you use the curly brackets like that. I don’t know if this is a problem with just the IDE I’m using (Code::Blocks) or if there is a way around it. Oh well.

      • Alex

        You sometimes see people “box” code with curly brackets for one-line functions. For example,

        But outside of that, not so much.

  • El-Nino

    Regarding block statements enclosed between braces, I prefer this style:

    Example:

    I find it compacts code and hence is more neat. Just a personal view. Experience has also shown that having 2 spaces for tabbing produces well defined code.

    • Kiena

      The example’s 4th line should look like this:

      Keeping the opening braces on the same line is the recommended formatting in java’s case, for example, where formatting is just as unrestricted as in c++.

      I also prefer 2 spaces wide tabs, but it’s personal preference and such things as the font or screen resolution may matter. For this reason I use tabs only for indentation, but for alignment on lines strictly spaces. That way a different tab size produces consistent layout.

      Another recommendation for c and c++, that might be worth mentioning, is to put the signature or a part of it after closing braces as a line comment to help navigation in case the IDE doesn’t provide sufficient support. Keeping functions short is helpful too. (If a function is “too long”, there are probably parts that can be extracted into separated functions, and just be called where their code was originally.) This kind of notation can be useful for nested control statements too.

      (I don’t know if my suggestions happen to be mentioned later in the tutorials.)

  • csvan

    Alex, near the beginning of this page, you write:

    “One exception where the C++ compiler does pays attention to whitespace is inside quoted text, such as “Hello world!”. “Hello world!” is different than “Hello world!” ”

    the last two strings you compared here are not different at all, did you mean something else?

    • Yes, the second one was supposed to have more whitespace, which HTML unhelpfully collapsed down to a single space. I’ve fixed it — thanks for noticing.

  • Ashley

    There are a few other cases where whitespace matters, and they have to do with using two-character operators. Pretty obvious for comparative operators (!= == >= etc.), but I ran into trouble when using multiple templates. For instance, creating a stack of pairs:

    The first line will not compile (if you are using namespace std) because it reads the extract operator >> at the end. The second line is more readable as well!

  • Sam

    I have some basic understanding of C++. But am truly new and I looked at the comments done by users here and what the tutorial says to do and by far the tutorial after showing friends and to me is perfectly illustrated. I can see why thousands of programmers skilled have developed a solid clean way of coding.

    Best Regards

  • chaospheonix440

    This tutorial is great! Thanks for showing how to make code neat. It’s really important and often overlooked.

  • Hele

    THANKS A LOT for this tutorial :) …I’m actually having fun! ;)

  • Ian

    When is it necessary to have << endl; ? Will the two following lines of code work the same?

    I love these tutorials by the way. Thank you!

    • Ian

      Sorry, my mistake. I forgot endl simply moved the cursor down one line of text. I remembered only moments after the countdown ended. Anyways, I’m learning…slowly…but surely. noobs gotta get there eventually.

      • rameye

        std::endl does more than just a carriage return to the beginning of the following line. It also forces an immediate flush of the underlying iostream object’s stream buffer. This defeats the purpose of the buffer in the first place. To me it seemed better (if you just have to type endl) to simply:

        #define endl '\n'

        However this creates a problem if you are using the qualified std::endl, the preprocessor changes it to std::'\n' before compiling and that breaks the compilation.

        Do it this way:

        std::string endl("\n");

        This declares a std::string object endl and initializes it to “\n”

        Now in code following it whenever you do cout << endl it inserts the \n into the stream instead of std::endl (even if you have used using namespace std; before it).

      • rameye

        Here is my solution to one of the quizzes and I implement what I was talking about in previous comment.

  • I removed the comment, because the code didn’t look as it should and would have been more confusing than helpful.

  • Leo

    Well, this is very good. I have a question: Assuming that you have more than one function, main() function should be at the top or not?

    Or, it doesn’t matter if it’s at the bottom (since there’s a “Find” dialog box to look for it easily):

    • rameye

      Your code looks good. Just one thing though.

      In your main() function body you have

      doubleVal(x);

      and the int value returned by that function is not being assigned to any variable that is local to main(). So essentially you have done nothing constructive by simply calling the function. Comment that line out or remove it and your code will still work.

      The reason cout << doubleVal(x) << endl; works is because doubleVal(x) is evaluated to the int value returned by the function, before it is inserted into the output stream by the operator<<() member of class ostream.

      This mechanics of this will all be revealed later, and since it has been four years since you posted this you probably already know all about it. :)

  • Shailesh Joshi

    Does the size of program increases by giving a long, readable variable name?
    And, i wrote a program, and compiled it through both code::blocks and turbo c++, but what i found is the size of program build by code::blocks is much larger than the same program build with turbo c++, And another thing what i found is the program compiled with code::blocks uses less RAM than the same program compiled with turbo c++. why this is so??
    (RAM used is found using task manager).

    • Different compilers, different usage. The reason why the filesize might be larger, is because you’re compiling the program with the debug flag, that will add additional code to your program to help you debug. Switch to release, and your filesizes will probably be the same.

    • rameye

      Using long expressive variable names is good, don’t worry about it, and that alone will not increase the size of your final executable. Debug compiliation and optimizations are what affect executable file size. Variable name lengths will affect the size of the assembly file that is output by the compiler for the linker. That is no problem. In your source code readability is paramount, and start now training yourself into a good system for naming variables in your code. You will thank yourself when you have to wade through it again for some reason years later.

  • Alam

    your tab should be set to 4 spaces.how?can any one explain it pls

    • rameye

      This will depend on what you are using for a code editor.

      I use the NetBeans 8.0.1 IDE, and it has a very extensive set of editor options for writing C++ code. The tab size setting is right in there.

  • Catreece

    It's funny… in the computer world? I'm tidy as hell. Clear, cleanly defined areas as much as possible, where there may be more time spent on the formatting to make it legible than in the actual written documentation or code itself. Looking around where I sleep, however, one could never predict this. =P

    It's nice to see there's actually some sort of more-or-less agreed upon set of rules for legibility, though. I'm sure I'll find exceptions to each and every rule listed, but for the most part, I don't see any real reason to alter what you have set up.

    One tiiiiiiiny question though…

    With the squiggly brackets each on their own separate lines, and that I like to use set numbers of empty lines of whitespace to break up functions and so on, do these count towards the total line count of a program? =P

    • Alex

      I suppose it depends on whether you’re using a smart line counting tool or not. In theory, a good line counting tool should ignore whitespace and lines consisting only of curly braces.

      For what it’s worth, line count is a horrible, horrible metric to judge developers by. :)

Leave a Comment (Note: put C++ code inside [code][/code] brackets)

  

  

  

17 − one =

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">