Navigation



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:

cout << "Hello world!";

cout               <<            "Hello world!";

		cout << 		"Hello world!";

cout
	<< "Hello world!";

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

The following functions all do the same thing:

int add(int x, int y) { return x + y; }

int add(int x, int y) {
    return x + y; }

int add(int x, int y)
{    return x + y; }

int add(int x, int y)
{
    return x + y;
}

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:

cout << "Hello
     world!" << endl; // Not allowed!

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:

cout << "Hello world!" << endl; // Here is a single-line comment
this is not part of the comment

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

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

int main()
{
}

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

int main()
{
    cout << "Hello world!" << endl;
    cout << "Nice to meet you." << endl;
}

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.

int main()
{
    cout << "This is a really, really, really, really, really, really, really, " <<
            "really long line" << endl;
    cout << "This one is short" << endl;
}

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:

    cout << "This is a really, really, really, really, really, really, really, " <<
            "really long line" << endl;

Not

    cout << "This is a really, really, really, really, really, really, really, "
            << "really long line" << endl;

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:

nCost = 57;
nPricePerItem = 24;
nValue = 5;
nNumberOfItems = 17;

Easier to read:

nCost          = 57;
nPricePerItem  = 24;
nValue         = 5;
nNumberOfItems = 17;

Harder to read:

cout << "Hello world!" << endl; // cout and endl live in the iostream library
cout << "It is very nice to meet you!" << endl; // these comments make the code hard to read
cout << "Yeah!" << endl; // especially when lines are different lengths

Easier to read:

cout << "Hello world!" << endl;                  // cout and endl live in the iostream library
cout << "It is very nice to meet you!" << endl;  // these comments are easier to read
cout << "Yeah!" << endl;                         // especially when all lined up

Harder to read:

// cout and endl live in the iostream library
cout << "Hello world!" << endl;
// these comments make the code hard to read
cout << "It is very nice to meet you!" << endl;
// especially when all bunched together
cout << "Yeah!" << endl;

Easier to read:

// cout and endl live in the iostream library
cout << "Hello world!" << endl;

// these comments are easier to read
cout << "It is very nice to meet you!" << endl;

// when separated by whitespace
cout << "Yeah!" << endl;

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

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

  • [...] 1.6 — Whitespace and basic formatting [...]

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

    
    #include <iostream>
    
    using namespace std;                    //Globally declaring namespace std to be used thru the whole program. Locally? Why me worry?
    
    int doubler(int w)                      //The doubler function. It does the doubling. Yay.
    {return 2 * w;}                         //The return value to be used by main so it can double the number given to cin.
    
    int main()                              //Main. Well, duh! We need this.
    {cout << "Pick a number to double:";    //A blank prompting for information can be confusing. Gotta tell the user something.
     int w;                                 //We will be using w from this point on in the function.
     cin >> w;                              //The piece of code that does the actual prompting.
     cout << doubler(w);                    //The piece of code that displays the doubled value to the user.
     return 0;}                             //Goodbye World!
    

    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.

  • [...] 1.6 — Whitespace and basic formatting  Print This Post This entry is filed under C++ Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. 19 Responses to “1.7 — Forward declarations” Comment by GovZ 2007-12-13 18:44:12 [...]

  • El-Nino

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

    start_of_block {
      statement1;
      statement2;
      ..
      statementn;
    }
    

    Example:

    if (n == 1) {
      a = (n*2);
      b = (a*a);
    else
      a = ((n*n)*2);
      b = a;
    }
    

    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:

      } else {

      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?

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

    stack<pair<int,int>> bar;
    stack< pair<int,int> > foo;
    

    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
    #include
    #include
    main();
    {
    clrscr();
    cout<<”hello…welcome to c++\\n”;
    cout<<”this is the first pgm”;
    getch()
    };

  • db_z

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

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

    cout << "Hello world!";
    cout << "Hello world!" << endl;
    

    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.

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

    int doubleVal(x);
    
    int main()
    {
    	int nCosto	 = 38;
    	int ItemsPor     = 34;
    	int x;
    	cout << "Give me a number ";
    	cin >> x;
    
    	doubleVal(x);
    
    	cout << doubleVal(x) << endl;
    
            return 0;
    
    }
    
    int doubleVal(int x)
    {
    	return x * 2;
    }
    

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

    int doubleVal(int x)
    {
    	return x * 2;
    }
    
    int main()
    {
    	int nCosto	 = 38;
    	int ItemsPor     = 34;
    	int x;
    	cout << "Give me a number ";
    	cin >> x;
    
    	doubleVal(x);
    
    	cout << doubleVal(x) << endl;
    
            return 0;
    
    }
  • dkdae2

    hi!

    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.

    Code:
    // 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<<"time"<>t;

    cout<<"rate"<>r;

    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
    time=1
    rate=1
    it shows
    interest=10572ACC0.01
    amount=10572ACC1.01

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

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

You must be logged in to post a comment.