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 braces should always be indented at the same level.

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 by indenting with a double tab (or manually aligning it with the line above).

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:


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

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

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

  • 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

  • joanne

    what should i do if my programme is
    cout<<“hello…welcome to c++\\n”;
    cout<<“this is the first pgm”;

  • db_z

    how to change the backgroung color of the windows
    can someone gimme a code for that

    • WordPress

      Write and run a C++ code or open up an existing executable C++ DOS/CLI. Right click it at the start menu dock. Click Defaults. You should be able to work it out from there.

      • WordPress

        And just in case you’re wondering, a DOS is a Disk operating system. It is the usually black colored executable that debugs your C++ source code.

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

        //#include <stdafx.h> // Visual Studio users need to uncomment this line

        #include <iostream>

        // Make a string object that will replace the non-qualified endl in our code
        // Do not do a 'using namespace std;' because it will cause an ambiguity
        // error between std::endl and our string endl.
        std::string endl("\n");

        // I keep my namespace just releasing cout and cin to std namespace
        using std::cout;
        using std::cin;

        int getNumberCR() {
        int x;
        cout << "Enter a number: ";
        cin >> x;
        cout << endl; // cout refers to std::cout, endl refers to string "\n"
        return x;

        int doubleNumber (int x) {
        return x*2;

        void printNumberCR (int x) {
        cout << x << endl;

        int main() {
        int x = getNumberCR();
        x = doubleNumber(x);

      • rameye

        I apologize for the ugly formatting in my example, but the HTML engine of this comment board seemed to suck my indentation whitespace into oblivion. :(

  • 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


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

  • dkdae2


    i am a newbi here and i am trying to learn C++. i have written a program to calc the simple interest and amount of a given data.

    i am using visual C++ express edition and it returns unexpected results though it compiles. please help me understand y.

    // calculating the simple interest for the data from he user
    //please help me solve this

    #include “stdafx.h” //since i am using visual C++
    #include //well, iostream is necessary

    float si(float a, float b, float c) //declaring that the data could be in decimals
    return a*b*c/100; //the formula

    int main() //main
    using namespace std;

    cout<<"principal"<>p; //taking the entered value as p



    cout << "interest="<< //printing the interest
    cout << si(p,t,r) << endl; //calling the function

    cout << "amount="<< //amount
    cout << si(p,t,r)+p; //printing the amount
    return 0;

    this is what it returns when i run it

    for principal=1
    it shows

    please help me out.
    thank you.
    a fellow programmer.

    • (I no longer trust the comment system, so I’m using 3rd party service to host my code. Also I’ve set the link to expire in 2 weeks (just so that you’re warned)).
      It worked fine for me (VS2010; removed the stdafx.h #include, because I ticked off the pre-compiled headers).

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

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




15 + 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="">