C++ - Syntax
First C++ Program
Although the "Hello World!" program looks simple, it has all the fundamental concepts of C++ which is necessary to learn to proceed further. Lets break down "Hello World!" program to learn all these concepts.
//Hello World! Example #include <iostream> int main () { std::cout<<"Hello World!."; return 0; }
The output of the above code will be:
Hello World!.
Line 1: This is a single line comment which starts with //. Generally, comments are added in programming code with the purpose of making the code easier to understand. It is ignored by compiler while running the code. Please visit comment page for more information.
Line 2: #include <iostream> is header file library. It allows program to perform input and output operations.
Line 3: Blank line has no effect. It is used to improve readability of the code.
Line 4: int main() - It declares of function main. A function is a block of code with a name. Please visit function page for more information.
Line 5 and 8: It consists of open curly bracket { and close curly bracket }. It is essential to keep all block of codes of main function within curly bracket.
Line 6: std::cout << "Hello World!"; - std::cout is standard character output device defined in <iostream> header file. It facilitates output from a program. After that insertion operator (<<) is used which tells std::cout what is inserted into it. Finally, ("Hello world!") is inserted into the std::cout. Please note that, in C++, every statement ends with semicolon ;.
Line 7: reurn 0; indicates ends of the main function.
using namespace std;
cout is defined under std namespace in <iostream> header file. If we add using namespace std; before main function, we can use cout without std:: prefix.
#include <iostream> using namespace std; int main () { cout<<"Hello World!."; return 0; }
The output of the above code will be:
Hello World!.
Semicolons
In a C++ program, the semicolon is a statement terminator. Each individual statement in C++ must be ended with a semicolon. It indicates that the current statement has been terminated and other statements following are new statements. For example - Given below are two different statements:
cout<<"Hello World!."; return 0;
endl and "\n"
endl and "\n" facilitates line change while performing output operation. endl indicates end of the line to the program. "\n" tells to start a new line to the program.
#include <iostream> using namespace std; int main () { cout<<"Hello World!.\n"; cout<<"Learning C++ is fun."<<endl; cout<<"And easy too."; return 0; }
The output of the above code will be:
Hello World!. Learning C++ is fun. And easy too.