C++ follows a structured approach that makes it easier to read and write programs. Let’s analyze a simple example to understand its essential components.
Example
#include <iostream> using namespace std; int main() { cout << "Welcome to the world of motorcycles!"; return 0; }
Explanation
Line 1: #include <iostream>
This is a header file that allows your program to handle input and output operations. It provides access to objects like cout
, which is used to display information on the screen.
Line 2: using namespace std;
This statement lets you use standard library components without explicitly referring to std::
before them.
If this seems confusing, don’t worry! These statements are commonly found in C++ programs, so you’ll see them often.
Line 3: (Blank line)
C++ ignores white spaces and blank lines, but programmers use them to keep their code organized and readable.
Line 4: int main()
Every C++ program needs a main function. This is where execution begins. Any code inside its curly braces {}
will run when the program starts.
Line 5: cout << "Welcome to the world of motorcycles!";
The cout
object (pronounced “see-out”) works with <<
, known as the insertion operator, to print text to the screen.
Important Notes:
- C++ is case-sensitive—
cout
andCout
are treated as different terms. - Every C++ statement ends with a semicolon (
;
). - The entire
main()
function could be written in a single line:int main() { cout << "Welcome to the world of motorcycles!"; return 0; }
Though valid, writing it this way makes the code harder to read.
Line 6: return 0;
This statement ends the main function, signaling that the program has finished running successfully.
Line 7: }
A closing curly brace marks the end of main()
, ensuring proper program structure.
Omitting using namespace std;
Some C++ programs avoid using namespace std;
. Instead, they explicitly reference standard library objects with std::
.
Example:
#include <iostream> int main() { std::cout << "Welcome to the world of motorcycles!"; return 0; }