Structure of c++ program
The structure of a C++ program consists of several components that help in organizing the code efficiently. Outline of a basic C++ program structure are as follows:
+----------------------------------------------+
| Preprocessor Directives |
+----------------------------------------------+
| Namespace Declaration |
+----------------------------------------------+
| Global Variables (Opt) |
+----------------------------------------------+
| Function Prototypes (Opt). |
+----------------------------------------------+
| The main() Function |
+----------------------------------------------+
| User-Defined Functions (Opt). |
+----------------------------------------------+
| Classes and Objects (Opt) |
+----------------------------------------------+
1. Preprocessor Directives
These are instructions that are processed before compilation begins.
Example:
#include <iostream> // Includes the standard input-output stream library
2. Namespace Declaration
Defines the scope of identifiers used in the program.
Example:
using namespace std; // Allows using standard C++ library functions without prefixing 'std::'
3. Global Variables (Optional)
Declared outside functions and accessible from any function.
Example:
int globalVar = 10;
4. Function Prototypes (Optional)
Declaration of functions before main()
.
Example:
void displayMessage(); // Function prototype
5. The main() Function
The entry point of the C++ program.
Example:
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
6. User-Defined Functions (Optional)
Functions written by the programmer to perform specific tasks.
Example:
void displayMessage()
{
cout << "This is a user-defined function." << endl;
}
7. Classes and Objects (Optional in Basic Programs)
Used in object-oriented programming to define templates for objects.
Example:
class Car
{
public:
string brand;
void showBrand()
{
cout << "Car Brand: " << brand << endl;
}
};
Example of a Complete C++ Program
#include <iostream>
using namespace std;
void displayMessage(); // Function prototype
class Car // Class definition
{
public:
string brand;
void showBrand()
{
cout << "Car Brand: " << brand << endl;
}
};
int main()
{
cout << "Hello, World!" << endl;
displayMessage(); // Function call
Car myCar;
myCar.brand = "Toyota";
myCar.showBrand();
return 0;
}
void displayMessage()
{
cout << "This is a user-defined function." << endl;
}
0 Comments