Monday, 22 September 2014

Difference between endl and '\n'


Look at these two output statements:

cout << endl << "This is output.";
cout << endl << "\tThis is output after a tab.";

They will produce these lines:

This is output.
This is output after a tab.

The \t in the second output statement causes the output text to be indented to the first tab position.

In fact, instead of using endl, you could use the escape sequence for the newline character, \n, in each string, so you could rewrite the preceding statements as follows:

cout << "\nThis is output.";
cout << "\n\tThis is output after a tab.";

Note that \n is not quite the same as endl. endl will output a newline and flush the stream, while \n will output the newline without flushing the stream.

Sunday, 21 September 2014

Difference between #include<> and #include""


Before knowing the difference lets know what is #include directive:

#include <iostream>

This is called a directive because it directs the compiler to do something — in this case, to insert the contents of the file, iostream, that is identified between the angled brackets, <>, into the program source file before compilation. The iostream file is called a header file because it’s invariably inserted in another source file. The iostream header file is part of the standard C++ library, and it contains definitions that are necessary for you to be able to use C++ input and output statements. If you didn’t include the contents of iostream into the program, it wouldn’t compile, because you use output statements in the program that depend on some of the definitions in this file. There are many different header files provided by Visual C++ that cover a wide range of capabilities. You’ll be seeing more of them as you progress through the language facilities.

The name of the file to be inserted by an #include directive does not have to be written between angled brackets. The name of the header file can also be written between double quotes, thus:

#include "iostream"

The only difference between this and the preceding version between angled brackets is the places where the compiler is going to look for the file.

If you write the header file name between double quotes, the compiler searches for the header file first in the directory that contains the source file in which the directive appears. If the header file is not there, the compiler then searches the directories where the standard header files are stored.

If the filename is enclosed between angled brackets, the compiler only searches the directories in which it expects to find the standard header files. \

Thus, when you want to include a standard header in a source, place the name between angled brackets because it will be found more quickly. 

When you are including other header files, typically ones that you create yourself, place the name between double quotes; otherwise, they will not be found at all.