Skip to main content

Command Palette

Search for a command to run...

C++ constructs and syntax, tokens, variables, datatypes, type conversion, operators, Expressions, Namespace, flowControl and decision making statement

Updated
7 min read

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(),,. The main() function is explicitly expected to return an integer type value (int) to the operating system, with a return 0 statement 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 cout represents 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 cin corresponds 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.

TokenDescription
KeywordsExplicitly 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,.
IdentifiersNames 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.
ConstantsFixed 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'),.
OperatorsSymbols representing actions (e.g., +, <<, new),.
StringsSequences 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:

  1. Built-in (Basic/Fundamental) Types: Includes integral types (int, char), floating types (float, double), and void. Modifiers such as signed, unsigned, long, and short can be applied to character and integer types.

  2. 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 class members are private by default, while struct members are public by default,.

    • Enumerated Types: Defined using enum to attach names to integer constants. In C++, the tag names (e.g., enum color {red, blue};) become new type names,.

  3. Derived Types: Includes arrays, functions, pointers, and references.

New ANSI C++ Data Types:

  • bool: Holds a Boolean value, either true (default value 1) or false (default value 0),,. bool values 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:

    1. Automatic: Default (local visibility, destroyed upon block exit).

    2. External: Global (accessible program-wide, lifetime of the program).

    3. Static: Local visibility but retains value (entire program lifetime).

    4. 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 ConversionMechanism 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++ Notationtype-name (expression) (e.g., float(i)).
New ANSI CastingANSI C++ provides specialized operators for greater control and visibility of casts,:
static_castUsed for standard conversions or safe casts between related types (e.g., base class pointer to derived class pointer).
const_castUsed explicitly to override the const or volatile attributes of an object.
reinterpret_castUsed to change one type into a fundamentally different, often incompatible type (e.g., pointer to integer).
dynamic_castUsed 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: new and delete allocate 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,.
  • Operator Keywords: ANSI C++ defines keyword alternatives for certain operators (e.g., and for &&, or for ||).

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 += 10 is equivalent to x = 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 namespace keyword, without a terminating semicolon,.

    • Standard Namespace: All standard C++ class libraries reside in the std namespace,.

  • Accessing Members:

    • Qualification: Members are accessed using the scope resolution operator (::) (e.g., Name1::x).

    • using Directive: using namespace std; makes all members of the std namespace globally accessible,.

    • using Declaration: 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:

  1. Sequence Structure: Statements are executed in a straight line.

  2. 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.

  3. Loop Structure (Iteration/Repetition): Used for repeated execution:

    • Entry-Controlled Loops: while and for structures, where the termination condition is checked before executing the loop body.

    • Exit-Controlled Loops: do-while structure, where the loop body is guaranteed to execute at least once before the condition is checked.

17 views

More from this blog

Shanlaksh

16 posts