C++ constructs and syntax, tokens, variables, datatypes, type conversion, operators, Expressions, Namespace, flowControl and decision making statement
C++ programming is founded on a comprehensive set of language constructs and syntactic rules that govern how code is structured, how data is managed, and how program flow is controlled.
I. C++ Constructs and Basic Syntax
The typical C++ program structure follows a client-server model where class definitions and member functions serve as the backend (server) and the main() function acts as the interface (client). The general structure consists of: include files, class declarations, member function definitions, and the main() function program.
Execution Flow: Program execution begins at
main(),,. Themain()function is explicitly expected to return an integer type value (int) to the operating system, with areturn 0statement often signaling successful execution,,.Style and Punctuation: C++ is a free-form language, meaning the compiler largely ignores carriage returns and white spaces. All C++ statements generally terminate with semicolons.
Comments: C++ supports the traditional C-style multiline comments (
/* comment */),, but also introduced the single-line comment symbol//(double slash), which ignores everything until the end of the line,.Input/Output (I/O): I/O operations require the inclusion of the
<iostream>header file,,.Output: The predefined object
coutrepresents the standard output stream (usually the screen). The operator<<is the insertion (or put to) operator, which sends the content of the right operand to the stream object on its left,.Input: The predefined object
cincorresponds to the standard input stream (usually the keyboard). The operator>>is the extraction (or get from) operator, taking a value from the stream and assigning it to the variable on its right,.Cascading: The multiple use of the
<<or>>operators in a single statement (e.g.,cout << a << b;) is known as cascading,.
II. Tokens
Tokens are the smallest individual units used to construct a C++ program.
| Token | Description |
| Keywords | Explicitly reserved identifiers that implement specific C++ features. ANSI C++ retains C keywords and adds new ones like bool, class, dynamic_cast, namespace, mutable, explicit, using, wchar_t, typeid, and various casting operators,. |
| Identifiers | Names chosen by the programmer for variables, functions, classes, etc.. They consist of letters, digits, and underscores, must not start with a digit, and are case sensitive. ANSI C++ places no limit on their length. |
| Constants | Fixed values that do not change during execution, such as integers (decimal, octal, hexadecimal), characters, floating-point numbers, and strings,. The wide-character literal wchar_t begins with the letter L (e.g., L'ab'),. |
| Operators | Symbols representing actions (e.g., +, <<, new),. |
| Strings | Sequences of characters. C++ supports C-style character arrays and the string class type,. |
III. Data Types
C++ data types are organized into three major categories:
Built-in (Basic/Fundamental) Types: Includes integral types (
int,char), floating types (float,double), andvoid. Modifiers such assigned,unsigned,long, andshortcan be applied to character and integer types.User-Defined Types: Includes structures (
struct), unions (union), classes (class), and enumerated types (enum).Classes and Structs: Both group data and functions. The key difference in C++ is that
classmembers are private by default, whilestructmembers are public by default,.Enumerated Types: Defined using
enumto attach names to integer constants. In C++, the tag names (e.g.,enum color {red, blue};) become new type names,.
Derived Types: Includes arrays, functions, pointers, and references.
New ANSI C++ Data Types:
bool: Holds a Boolean value, eithertrue(default value 1) orfalse(default value 0),,.boolvalues are automatically elevated to integers in non-Boolean expressions.wchar_t: Intended to hold 16-bit wide characters, particularly for large character sets (e.g., Japanese),.
IV. Variables and Initialization
Declaration Location: While variables must be declared before use, C++ allows declaration almost anywhere within the scope, often right at the place of its first use, improving code readability and manageability,,.
Dynamic Initialization: Variables can be initialized at run time using expressions, rather than just constant expressions fixed at compile time,.
Reference Variables: Declared using the ampersand (
&) (e.g.,float & sum = total;), a reference variable provides an alias (alternative name) for a previously defined variable, pointing to the exact same memory location,. Reference variables must be initialized at the time of declaration,.Storage Classes: Define a variable's lifetime and visibility. They are:
Automatic: Default (local visibility, destroyed upon block exit).
External: Global (accessible program-wide, lifetime of the program).
Static: Local visibility but retains value (entire program lifetime).
Register: Stored in CPU registers for speed (function block lifetime).
V. Type Conversion
C++ handles type compatibility strictly. When mixing types, conversion is necessary and can be implicit or explicit:
| Type of Conversion | Mechanism and Application |
| Implicit (Automatic) | Occurs automatically by the compiler in mixed-mode expressions. Generally promotes a "smaller" type to a "wider" type (e.g., int to float) to avoid data loss. This includes integral widening conversion (char or short promoted to int),. |
| Explicit (Casting) | Forced by the programmer using the type cast operator,. |
| C Notation | (type-name) expression (e.g., (float)i). |
| C++ Notation | type-name (expression) (e.g., float(i)). |
| New ANSI Casting | ANSI C++ provides specialized operators for greater control and visibility of casts,: |
static_cast | Used for standard conversions or safe casts between related types (e.g., base class pointer to derived class pointer). |
const_cast | Used explicitly to override the const or volatile attributes of an object. |
reinterpret_cast | Used to change one type into a fundamentally different, often incompatible type (e.g., pointer to integer). |
dynamic_cast | Used to cast the type of an object at runtime (Run-Time Type Information - RTTI). Essential for polymorphic objects, returning NULL if the conversion fails,,. |
VI. Operators and Expressions
Operators
C++ includes all C operators and adds several specifically for object-oriented functionality:
Scope Resolution Operator (
::): Used to access hidden global variables or, primarily in OOP, to specify the class a member function belongs to,.Memory Management Operators:
newanddeleteallocate and deallocate memory dynamically from the free store (heap),,.Pointer-to-Member Operators:
::*,->*,.*facilitate access to class members through pointers,.Operator Overloading: The mechanism to give additional meanings (multiple forms/behaviors) to an operator when applied to user-defined types (objects),,. This is achieved using a special operator function (
operator op()).- Unoverloadable Operators: Class member access (
.,.*), scope resolution (::), size operator (sizeof), and conditional operator (?:) cannot be overloaded,.
- Unoverloadable Operators: Class member access (
Operator Keywords: ANSI C++ defines keyword alternatives for certain operators (e.g.,
andfor&&,orfor||).
Expressions
An expression is a combination of operators, constants, and variables that yields a value. Expressions are classified by their resulting type:
Types: Constant, Integral, Float, Pointer, Relational (Boolean - yielding
true/false), Logical, and Bitwise expressions. Combinations form compound expressions.Special Assignment Expressions:
Chained Assignment: Assigning a single value across multiple variables (e.g.,
x = y = 10).Compound Assignment (Shorthand): Combining an arithmetic operator with assignment (e.g.,
x += 10is equivalent tox = x + 10).
VII. Namespaces and Scope
Namespaces: Introduced by ANSI C++ to manage global identifiers and prevent name conflicts,,. A namespace defines a scope for identifiers.
Definition: Defined using the
namespacekeyword, without a terminating semicolon,.Standard Namespace: All standard C++ class libraries reside in the
stdnamespace,.
Accessing Members:
Qualification: Members are accessed using the scope resolution operator (
::) (e.g.,Name1::x).usingDirective:using namespace std;makes all members of thestdnamespace globally accessible,.usingDeclaration:using namespace_name::member_name;makes only a specific member accessible.
Scope: C++ is a block-structured language. The scope of a variable runs from its declaration to the end of its containing block. The scope resolution operator (
::) can access a global variable that is otherwise hidden by a local declaration.
VIII. Flow Control and Decision Making Statements
C++ implements structured programming using three core control structures:
Sequence Structure: Statements are executed in a straight line.
Selection Structure (Branching): Used for decision-making:
if/if...else: Provides two-way branching based on a condition being true (non-zero) or false (zero).switch: Provides multi-way branching based on the value of an expression.
Loop Structure (Iteration/Repetition): Used for repeated execution:
Entry-Controlled Loops:
whileandforstructures, where the termination condition is checked before executing the loop body.Exit-Controlled Loops:
do-whilestructure, where the loop body is guaranteed to execute at least once before the condition is checked.