1.8 — 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 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:

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

This makes your lines easier to read. On modern wide-screen monitors, it also allows you to place two windows with similar code side by side and compare them more easily.

Best practice

Your lines should be no longer than 80 chars in length.

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.

Automatic formatting

Most modern IDEs will help you format your code as you type it in (e.g. when you create a function, the IDE will automatically indent the statements inside the function body).

However, as you add or remove code, or change the IDE’s default formatting, or paste in a block of code that has different formatting, the formatting can get messed up. Fixing the formatting for part or all of a file can be a headache. Fortunately, modern IDEs typically contain an automatic formatting feature that will reformat either a selection (highlighted with your mouse) or an entire file.

For Visual Studio users

In Visual Studio, the automatic formatting options can be found under Edit > Advanced > Format Document and Edit > Advanced > Format Selection.

For Code::Blocks users

In Code::Blocks, the automatic formatting options can be found under Right mouse click > Format use AStyle.

For easier access, we recommend adding a keyboard shortcut to auto-format the active file.

Best practice

Using the automatic formatting feature is highly recommended to keep your code’s formatting style consistent.

1.9 -- Introduction to literals and operators
1.7 -- Keywords and naming identifiers

109 comments to 1.8 — Whitespace and basic formatting

  • Waldo Lemmer

    Section "Basic formatting", "5)":

    Indented one level too deep?

  • Hariharan VN

    std::cout << "Hello "
         "world!"; // prints "Hello world!"

    How this even works, I last lesson, I read something like to join multiple string we need to use concatenation
    something like this

    std::cout << "Hello "<<"world!";

    Beginner to CPP

    • Alex

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

      causes the compiler to concatenate "Hello " and "world!" into "Hello world!".

      Causes the compiler to output two separate pieces of text.

      The result is the same either way.

  • Marceille

    Great work so far.

    But can u help me with this one:
    "For easier access, we recommend adding a keyboard shortcut to auto-format the active file."

    -I'm using codeblocks on linux and searched all of the 1.72*10^9 existing websites and haven't found a way to assign a shortcut to auto-format the code. Found some answers: "Go to Settings -> Editor -> Keyboard Shortcuts" but that does not exist for me :(

  • Ysaood9

    Heya guys I'm new to C++ and I had the luck to come across this amazing tutorial. I am an apple mac user and I really love the UI in Xcode it would be pretty cool if anyone can help me get my IDE to automatically format and close my brackets.

    • Zach

      Sadly, there isn't really an option to auto-format your code using Xcode. There is an option using Ctrl + I to re-indent your code but that's about as far as it goes.

  • empleat

    Isn't there some formatting option somewhere (in VS 19) which would automatically put all = next to longest variable, if you have like list of 20 variables listed next to each other??? I find it can't even autocomplete std:: in front of cout LOL...

    I Am referring to this example:

    cost          = 57;
    pricePerItem  = 24;
    value         = 5;
    numberOfItems = 17;

  • Charles

    VSCode users: Ctrl+K Ctrl+F to format highlighted regions, and Shift+Alt+F to format the whole file.  You'll thank me later :')

  • Nolan

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

    Such a ridiculous statement... Obviously cake is superior! :)

    Thanks for these tutorials, they have been absolutely amazing. Wish there were brilliant resources like this for every subject I wish to learn. Cheers!

  • I just want to express how thankful I am for these tutorials. I can't believe I'm learning these just for free. Thank you so much for your effort Author!!!

  • Remy

    First of all thank you guys so much for everything! I went from not knowing a thing about coding to programming a simple application with a GUi all because of this site.

    I have a question about formatting that I'm a little hesitant to ask cause it has nothing to do with the material on this site but I'll be really thankful if someone can help me.

    I'm trying out unreal engine so I downloaded a .clang-format file from No matter how I tried to configure it I still can't get the results that I want. I've tried everything that I could for 4 days...omg..4days straight..and here I am finally..

    In "visual studio" the format that I'm getting with the .clang-farmat after configuring it.

    This is the format I'm trying to achieve.

    There goes another 30 minutes, pasting made the format a mess. lol

    The second format was done by using the mozilla style in VS but I don't like how it's indenting and a lot of other stuff. I wish there's a way to configure a format style based on another style in VS but I guess we can't have nice things.

    Any help is greatly appreciated! A link to a better .clang-format would be'm speechless..I need sleep..sleep..

  • I feel like this is a dumb question but oh well

    "For easier access, we
    recommend adding a keyboard shortcut to auto-format the active file."
    Can you please tell me how I could do that on Visual Studio? I am a complete beginning but I'm a sucker for neat stuff XD

    • Remy

      The default hotkey in Visual studio is ctrl k then ctrl d. If you want other styles you can go under tools > options > Text Editor > C/C++ > Formatting > General . In the Default Formatting Style section you can choose a style and try to see if you like it. :)

  • Do you think you could recommend me some motivation, or just something that will tell me, just do it?

    • Anubhav Chauhan

      It's only who you can do it and no one else. And during the time you don't, there are thousands of other people who're doing the same thing and becoming better and better

      • BeanSprugget

        I'd like to somewhat contest your second sentence: it may seem that a lot of people are better than you already, but your success is independent other's performance. And I assume that this is something you want to learn: regardless of how others act about it, it's still the thing YOU want to learn.

        Also, for myself I found that it helps to think "just do it": there are no "tricks" to being motivated, which in some sense is discouraging, but is also motivating, because there is nothing really stopping you from success.

  • Ryan

    Very minor typo! At the bottom of the page, it says "modern IDEs typically contains an automatic formatting feature", where 'contains' should be 'contain'.

  • Jimmy Hunter

    I love this tutorial!

    It is so excellent, I want to help, even with this miniscule correction.

        One exception where the C++ compiler does pays attention

    Should be "pay" not "pays".

    You indicated in an earlier post that you fixed it.  But somehow it is back.

  • Etienne

    This is best short and sweet style guide I've read so far. Thank you! I used your style in class and the professor was very impressed.

  • Anastasia

    Are 'mixed' braces styles (e.g. k&r, stroustrup, "One True Brace Style", mozilla, etc.) acceptable to use? I mean, I know that it's the personal preference and consistency that count, but for those who have neither one nor the other yet?

    And same question about indentation, many styles use different amount of spaces from conventional 4, if it doesn't have a big impact on readability, is it okay to use them?

    And in particular, is stroustrup style (opening braces are broken from functions, attached otherwise, tabbed indent of 5 spaces) often used?

    • > Are 'mixed' braces styles [...] acceptable to use?
      Yes, as long as you're consistent.

      > And same question about indentation

      > is stroustrup style [...] often used?
      I don't pay a lot of attention to formatting unless I'm reviewing code. I don't recall seeing this style. I'd say mixed braces and anything but 2 or 4 spaces is rather rare.

      Which formatting you use during development is completely up to you. If the project you're working on enforces a specific formatting, you can still write the code how you're used to and in the end auto-format everything with the demanded settings.

      • Anastasia

        Thank you, I know that it's not so important, just trying to set my formatter to some (more or less) acceptable style I like and stick with it. There are so many different formatting practices, it's easy to get lost.

        > I don't recall seeing this style. I'd say mixed braces and anything but 2 or 4 spaces is rather rare.
        That's a shame. I hoped they were more common.

    • Killi

      Is there a way to enforce it through compiler option ?.

  • About braces-on-newline being better due to an indentation mismatch, that's also provided by braces-on-same-line, example

    Indentation still makes it obvious which brace is missing. Further, IDEs have features to highlight the corresponding brace when selecting one.

    For this reason, the "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." claim is in my opinion invalid.

    • Sahil

      Although they tell you to use an IDE, there are many people who opt to use the command line and a simple text editor instead. In such cases this statement stands true. Although just like it said in the article, it is a matter of personal preference

  • Bob

    In the comments, you state that the operator should be placed at the end of the current line, but in the actual article you state the opposite.

    Which is correct?

  • Louis Cloete

    Just below the first example: "Even the last two statements with the newlines in them compiles just fine."

    I see only one statement with a newline in it (the last one).

  • why i'm getting error

    • A function can only be defined once. If all functions have different names, your program compiles.

    • seaque

      you can do this. This is called function overloading. If you send int values, program will use the first function. If you sent double values, program will use double function. That is enough to know for know.

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