2.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 newlines. The C++ compiler generally ignores whitespace, with a few minor exceptions (when processing text literals). For this reason, we say that C++ is a whitespace-independent language.

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

Even the last statement that is split over two lines 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:

Quoted text separated by nothing but whitespace (spaces, tabs, or newlines) will be concatenated:

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) It’s fine to use either tabs or spaces for indentation (most IDEs have a setting where you can convert a tab press into the appropriate number of spaces). Developers who prefer spaces tend to do so because it makes the formatting self-describing -- code that is spaced using spaces will always look correct regardless of editor. Proponents of using tabs wonder why you wouldn’t use the character designed to do indentation for indentation, especially as you can set the width to whatever your preference is. There’s no right answer here -- and debating it is like arguing whether cake or pie is better. It ultimately comes down to personal preference.

Either way, we recommend you set your tabs to 4 spaces worth of indentation. Some IDEs default to 3 spaces of indentation, which is fine too.

2) There are two acceptable styles for function braces.

The Google C++ style guide recommends putting the opening curly brace on the same line as the statement:

The justification for this is that it reduces the amount of vertical whitespace (you aren’t devoting an entire line to nothing but the opening curly brace), so you can fit more code on a screen. More code on a screen makes the program easier to understand.

However, we prefer the common alternative, where the opening brace appears on its own line:

This enhances readability, and is less 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 curly 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, 80 characters is the maximum length a line should be. If a line is going to be longer, it should be split (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 is split with an operator (eg. << or +), the operator should be placed at the beginning of the next line, not the end of the current line

This helps make it clearer that subsequent lines are continuations of the previous lines, and allows you to align the operators on the left, which makes for easier reading.

6) Use whitespace to make your code easier to read by aligning values or comments or adding spacing between blocks of code.

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. One exception: If you are working in someone else’s code base, adopt their styles. It’s better to favor consistency than your preferences.

2.7 -- Forward declarations and definitions
2.5 -- Why functions are useful, and how to use them effectively

76 comments to 2.6 — Whitespace and basic formatting

  • SriKolla

    Thanks for these Awesome C++ tutorials.

  • DragonD

    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:


    This is what you have written above the bold text that says "Basic Formatting".

    My question for you sir is whether you're talking about the blank spaces or newlines in comments when you say "Another exception where the C++ compiler pays attention to whitespace ..."?

  • My dear c++ Teacher,
    Please let me say that program in paragraph "Basic formatting 4)" works fine even when second operator << in 3rd and 6th line is omitted, as follows:

    With regards and friendship.

    • Alex

      True. C++ will concatenate sequential string literals, so at least in the case of sequential C-style string literals, the << symbols aren't necessary. I still like to use them, because this concatenation doesn't work for other types.

  • My dear c++ Teacher,
    Please let me say, Dev-C++ 5.11 IDE defaults to 3 spaces.
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me comment that first example's output clear shows that all statements do the exact same thing, when "endl" is added at the end of each statement as follows:

    With regards and friendship.

  • Matthieu B.

    "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"

    Shouldn't whitespace be replaced by newlines here?
    Thank you for this tutorial.

  • Vineeta Bedarkar


    I had tried learning programming through many websites/tutorials/books, but those all generated a kind of fear ,earlier I used to think, programming is like cramming things a lot (Which I hate !), but since you always explain the reason and how things work, it is easy for me to learn. Thank you so much for creating this wonderful course.

    My best wishes !!!

  • Simone

    Hi! I'm glad to read this post as today my teacher presented me his c++ work and is really... unreadable! No spaces, no comments, no new lines. I've read that there isn't a performance reason to do this, so why?

    A little curiosity:
    is there a way to remove every empty spaces from whole the code?
    I mean

    must become

    All teacher's code is like the last one.
    Assuming that there are many calculations in the code, is there a better way to write them?

    could this be fine?

    • Alex

      Yes, compacting your code doesn't affect anything in C++. For some people, it's a matter of style/habit.

      That line of calculations looks totally fine.

  • Nyap

    is formatting basically the way it's presented?

  • Pierre

    A quick note about aligning assignments and comments:

    Some argue that lining up assignments as in the following:

    is a maintenance nightmare. If you change a variable name, you have to re-align every equal sign around it by adding or removing spaces.

    Same goes for end of line comments that span several lines, if you change some of the code and the lines become shorter or longer, the comments are out of alignment.

    While it is definitely easier to read, chances are it will only be easier to read when the code is first checked in. After being edited by several developers, it will likely become misaligned because it’s a pain to add the relevant spaces every time.

    • Alex

      Aligning variable comments is a bit easier if you use tabs instead of spaces, and changing variable names isn't that common.

      Ultimately, it's up to you if you want to spend the extra time to align for readability or not.

  • jatin

    Hallo evryone,
    I'm new learner for this c++ langauge. I want to know what if we want to add white spaces i out text.
    For example I want to print like
    cout<<" Name             : jd <<endl ;
    cout<<" Occupation       : student;
    how can I write it like this. Exactly like this. So that thze symmetry doesn't change. and I can freely give the number of white spaces I want to give.

    • Muhammad Kamal

      As far as I know, the font of the command prompt is Lucida Console, this sets a fixed width for all characters including spaces, so you just open Note Pad, set the font to Lucida Console if it wasn't set, paste the text that you want to edit, edit it and then paste it back into your C++ editor.

      P_S__/ The code that you posted had one error, you didn't end the string with another double quotes character! If "jd" is a variable then you need to insert another two << (Insertion operators) because you use endl, if you aren't gonna use endl you'll only need one insertion operator.

      P_S__/ Some editors have their font set to Lucida Console (In my case, Visual Studio 2015) and allows you to carry out such alignments easily inside the editor, instead of having to resort to external means.

  • Owen

    What's the difference between << and +

    • Alex

      << has a couple of meanings, depending on context. But in this case, we use it to send text or a number to std::cout for printing on the console. + is mathematical plus -- the same one you use in standard mathematics. We use it to add two things together.

  • Simon

    I disagree that aligning assignment operators makes the code more readable overall, as you suggest in the first pair of examples on recommendation 6.  It makes the values easier to see (a good reason to use this formatting with comments), but it makes it more difficult to associate them with the identifiers, especially if one of the identifiers is much longer than its neighbors.  If code looks scrunched without aligning the assignment operators an extra line between the assignments would go a long way towards making it more readable:

  • 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. :)

  • Alam

    your tab should be set to 4 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.

    • Darren

      In Visual Studio 2013 (it's somewhat buried) go to TOOLS -> Options -> Text Editor -> C/C++ -> Tabs and you'll find the settings there to play around with.

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

  • 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


      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. :)

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

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

  • Hele

    THANKS A LOT for this tutorial :) ...I'm actually having fun! ;)

  • chaospheonix440

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

  • 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

  • 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!

    • Darren

      The issue of a double greater-than symbol used to terminate a nested template list being interpreted as the stream output operator has now been fix from C++11 on-wards (C++11 released in 2014). Though I do agree the second line is more readable if less compact.

      • Darren

        I'll correct myself; C++11 was released in 2011 (hence the name). C++14 was released in 2014 (are we spotting a pattern here).

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

  • El-Nino

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


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

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

  • Ter

    Thanks for making things easy to understand.

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

  • kon_nos

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

  • 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 ]

Leave a Comment

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