Structure of a C++ Program
A basic C++ program follows a specific structure that helps the compiler understand what tasks need to be executed. Below is the standard layout of a simple C++ program.
Example: Simple C++ Program
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to ShikshaSanchar!";
return 0;
}
Note:
Always save your C++ program with a .cpp extension (e.g.,
hello.cpp) so the compiler can recognize it as C++ source code.
Output:
Welcome to ShikshaSanchar!
Explanation of Each Component:
-
#include <iostream> :
This is a preprocessor directive that includes the
iostreamheader file in the program.iostreamstands for "input-output stream".- It allows us to use
cin,cout, etc.
-
using namespace std; :
This line tells the compiler to use the
std(standard) namespace. Without it, you would need to write std::cout instead of just cout.
A namespace is a logical container that holds identifiers like functions, variables, and objects to avoid name conflicts in large programs.In C++, all standard library functions and objects like
cout,cin,endletc., are defined inside thestdnamespace.- By writing
using namespace std;, we don’t have to prefixstd::before every standard keyword. - Without this line, we would need to write:
std::cout,std::cin, etc. - It helps make code cleaner and shorter for small projects or learning purposes.
- By writing
-
int main() :
The
main()function is the entry point of every C++ program.intindicates that the function returns an integer value.- Execution starts from the
main()function.
-
{ and } :
These are curly braces used to define the body of functions, loops, conditions, etc.
In this case, they define the body of themain()function. -
cout << "text"; :
This is the C++ way to print output on the screen.
coutstands for "console output".<<is the insertion operator."text"is the string to be displayed.
-
; (Semicolon) :
Every C++ statement ends with a semicolon (
;). It tells the compiler that the statement is complete. -
return 0; :
This indicates that the program has run successfully.
0is returned to the operating system from themain()function.
Summary:
- A C++ program starts with header files using
#include. using namespace std;lets us avoid writingstd::before keywords.main()is the main execution point.- Curly braces define code blocks.
- Semicolon ends statements.
coutis used for displaying output.return 0;signifies successful execution.