Basic Structure of C++
When you’re just starting with C++, it’s important to understand how a typical program is structured. Here’s a breakdown of the fundamental components that make up a basic C++ program:
1. Preprocessor Directive
#include <iostream>
Explanation:
- This line tells the compiler to include the Input/Output stream library.
- It allows the use of
std::cout
andstd::cin
for printing and taking input.
Think of it as importing features you need, like importing modules in Python or packages in Java.
2. Namespace Declaration
using namespace std;
Explanation:
std
is the standard namespace in C++ that includes common functions likecout
,cin
, etc.- Writing this line means we don’t need to write
std::
before everything.
Without this, you’d have to write
std::cout
instead of justcout
.
3. The main()
Function
int main() {
// code goes here
return 0;
}
Explanation:
- Every C++ program starts with the
main()
function. int
indicates that this function returns an integer value.return 0;
means the program executed successfully.
4. Printing Output
cout << "Hello, world!" << endl;
Explanation:
cout
is used to display output to the console.<<
is the insertion operator, which pushes the data to the output stream.endl
is used to move to a new line after the message.
It’s similar to
print()
in Python.
5. Taking User Input
int age;
cin >> age;
Explanation:
int age;
declares a variable to store user input.cin
is used to get input from the user.>>
is the extraction operator, which pulls the input from the input stream into the variable.
Full Example: Simple C++ Program
#include <iostream> // 1. Include I/O library
using namespace std; // 2. Use standard namespace
int main() { // 3. Start of the main function
cout << "Hello, world!" << endl; // 4. Print message
int age; // Declare a variable
cout << "Enter your age: ";
cin >> age; // 5. Take input from user
cout << "You are " << age << " years old." << endl;
return 0; // End of program
}
📌 Summary
Part | Purpose |
---|---|
#include <iostream> | Gives access to input/output functions |
using namespace std; | Avoids prefixing std:: everywhere |
int main() | Entry point of the program |
cout | Prints output to the console |
cin | Reads input from the user |
return 0; | Indicates successful program execution |