Structure of a C++ Program
Structure of a C++ Program cplus tutorial
Introduction
Before diving into complex concepts, it is essential to understand how a simple C++ program is organized. The structure defines how code is written, compiled, and executed by the compiler.
Here’s a minimal C++ program:
#include <iostream> // Header file
using namespace std; // Namespace
int main() { // Main function
cout << "Hello, World!" << endl; // Output statement
return 0; // Exit status
}
Begin with # (like #include, #define).
Instruct the compiler to include files or define macros before compilation.
Example: #include <iostream> includes the standard input/output stream library.
Groups identifiers (like variables, functions) to avoid naming conflicts.
Commonly used: using namespace std;
This allows access to standard library objects like cout, cin, etc.
main() Function
Every C++ program must have a main() function.
Execution starts from main().
Returns an integer value to the operating system (0 indicates success).
Actual instructions that the program executes.
Example: cout << "Hello"; prints output.
Used for documentation and are ignored by the compiler.
Single-line: // comment
Multi-line: /* comment */
Preprocessing — Includes headers and expands macros.
Compilation — Translates source code into object code.
Linking — Combines object code with libraries.
Execution — Runs the final executable.
#include <iostream> // Header
#define PI 3.1415 // Macro definition
using namespace std;
// Function declaration
void greet() {
cout << "Welcome to C++!" << endl;
}
int main() {
greet(); // Function call
cout << "Value of PI is: " << PI << endl; // Macro usage
return 0;
}
Every C++ program has preprocessor directives, namespaces, functions, and statements.
The main() function is mandatory and serves as the entry point.
Understanding the structure helps you write organized and maintainable code.