C++ syntax is relatively similar to other C-based languages like C and Java. The
structure of a C++ program is important for proper compilation and execution.
Below is an overview of key components of C++ syntax and structure.
1. Basic Structure of a C++ Program
A basic C++ program typically consists of the following parts:
Preprocessor Directives: Instructions that tell the compiler to include
external files or libraries.
Main Function: The entry point of the program where execution starts.
Statements and Expressions: Instructions that perform actions, such as
displaying text or performing calculations.
Example of a basic C++ program:
#include <iostream> // Preprocessor directive to include input-output library
using namespace std; // Standard namespace to avoid prefixing 'std::' with
common objects
int main() { // Main function, the starting point of a C++ program
cout << "Hello, World!" << endl; // Output a message to the console
return 0; // Return 0 to indicate successful completion
}
2. Preprocessor Directives
Preprocessor directives are instructions given to the preprocessor before actual
compilation begins. They usually begin with a # symbol.
Common preprocessor directives:
, #include <iostream>: Tells the compiler to include the iostream library,
which is used for input and output operations.
#define: Defines constants or macros.
#include: Includes other header files, e.g., #include <cmath> for
mathematical functions.
3. main() Function
The main() function is the entry point of any C++ program. The program always
starts execution from here. Every C++ program must have a main() function.
Syntax:
int main() {
// Program code
return 0;
}
o int: The return type of main(). It returns an integer, typically 0, to
indicate that the program ran successfully.
o return 0;: Ends the execution of the program and returns control to
the operating system. A return value of 0 indicates successful
completion.
4. C++ Statements and Expressions
Statements: Instructions that perform actions like printing output or
assigning values. Each statement is usually terminated by a semicolon (;).
o Example: cout << "Hello, World!" << endl; – This is an output
statement.
Expressions: Combinations of variables, operators, and function calls that
produce a result. They can be used in statements.
o Example: int x = 5 + 10; – This is an expression (5 + 10) that is
assigned to variable x.