Lesson 03-C++ Expressions and Statements

Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, etc.

  • Addition (+): Adds two values.
  • Subtraction (-): Subtracts the second value from the first value.
  • Multiplication (*): Multiplies two values.
  • Division (/): Divides the first value by the second value.
  • Modulus (%): Returns the remainder of the division.
  • Exponentiation (** or ^ in some languages): Computes the base raised to the power of the exponent.
  • Floor Division (// in Python): Returns the integer part of the quotient.

Relational and Logical Operators

Relational and logical operators are used to compare two values and return a Boolean result (true or false).

  • Equal to (==): Checks if two operands are equal.
  • Not equal to (!= or <> in some languages): Checks if two operands are not equal.
  • Less than (<): Checks if the left operand is less than the right operand.
  • Greater than (>): Checks if the left operand is greater than the right operand.
  • Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.
  • Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand.

Assignment Operators

Assignment operators are used to assign values to variables.

Simple Assignment (=): Assigns a value to a variable. Compound Assignment: These operators combine simple assignment with arithmetic operations.

  • +=: Equivalent to x = x + y
  • -=: Equivalent to x = x - y
  • *=: Equivalent to x = x * y
  • /=: Equivalent to x = x / y
  • %=: Equivalent to x = x % y
  • **=: Equivalent to x = x ** y (in languages that support exponentiation)
  • //=: Equivalent to x = x // y (in languages that support floor division)

Increment and Decrement Operators

Increment and decrement operators are used to quickly increase or decrease the value of a numeric variable by 1.

  • Increment (++): Increases the variable’s value by 1.
  • Prefix Increment (++x): Increases the variable’s value first, then uses it.
  • Postfix Increment (x++): Uses the variable’s value first, then increases it.
  • Decrement (–): Decreases the variable’s value by 1.
  • Prefix Decrement (–x): Decreases the variable’s value first, then uses it.
  • Postfix Decrement (x–): Uses the variable’s value first, then decreases it.

Complex Number Operations

A complex number consists of a real part and an imaginary part. Most programming languages provide libraries or built-in functionality to handle complex numbers.

  • Creating Complex Numbers: Typically created via constructors or specific literals.
  • Complex Arithmetic: Supports basic operations such as addition, subtraction, multiplication, and division.

Conditional Operator

The conditional operator, also known as the ternary operator, returns different values based on a condition.

  • Conditional Operator (?:): If the condition is true, returns the value of the first expression; otherwise, returns the value of the second expression.
  • Syntax: condition ? expression1 : expression2

sizeof Operator

sizeof is a compile-time operator used to obtain the size (in bytes) of a data type or expression.

  • Syntax: sizeof(type) or sizeof(expression)
  • Purpose: Obtains the size of a variable or data type.

new and delete Expressions

new and delete are operators used for memory allocation and deallocation, commonly used in C++.

  • new: Dynamically allocates memory and returns a pointer to the newly allocated memory.
  • Syntax: new type
  • Arrays: new type[count]
  • delete: Frees memory previously allocated with new.
  • Syntax: delete pointer
  • Arrays: delete[] pointer

Comma Operator

The comma operator (,) is used to chain multiple expressions and returns the value of the last expression.

  • Syntax: expression1, expression2, …, expressionn
  • Behavior: Evaluates each expression from left to right, and the final result is the value of the rightmost expression.

Bitwise Operators

Bitwise operators are used to directly manipulate binary bits.

  • Bitwise AND (&): Result is 1 only if both corresponding bits are 1.
  • Bitwise OR (|): Result is 1 if at least one of the corresponding bits is 1.
  • Bitwise XOR (^): Result is 1 if the corresponding bits are different.
  • Bitwise NOT (~): Inverts each bit (0 becomes 1, 1 becomes 0).
  • Left Shift (<<): Shifts the binary bits to the left by the specified number of positions.
  • Right Shift (>>): Shifts the binary bits to the right by the specified number of positions.

bitset Operations

bitset is a data structure used to store a sequence of bits, typically used for efficient bit manipulation.

  • Creating bitset: Can be initialized via constructor.
  • Access and Modification: Provides methods to access and modify bits in the bitset.
  • Bit Operations: Supports bitwise AND, OR, XOR, etc.

Operator Precedence

Operator precedence determines the order in which operations are performed in an expression.

  • Parentheses (()): Highest precedence, can change the order of operations.
  • Arithmetic Operations: Multiplication, division, and modulus have higher precedence than addition and subtraction.
  • Bitwise AND (&): Higher precedence than bitwise OR (|) and bitwise XOR (^).
  • Logical Operations: Logical NOT (!) has higher precedence than logical AND (&&) and logical OR (||).
  • Assignment Operations: Lowest precedence.

Type Conversion

Type conversion is used to convert a value of one type to another type.

Implicit Type Conversion

Implicit type conversion (also known as automatic type conversion) refers to type conversions performed automatically by the compiler. This conversion typically occurs between two types where one can be safely converted to the other without loss of information.

#include <iostream>

int main() {
    int a = 10;
    double b = a; // Implicit type conversion

    std::cout << "a: " << a << ", b: " << b << std::endl;

    return 0;
}

Output:

a: 10, b: 10

Explicit Type Conversion

Explicit type conversion (also known as casting) refers to type conversions explicitly specified by the programmer. This is typically used when the compiler cannot perform the conversion automatically.

#include <iostream>

int main() {
    double a = 10.5;
    int b = static_cast<int>(a); // Explicit type conversion

    std::cout << "a: " << a << ", b: " << b << std::endl;

    return 0;
}

Output:

a: 10.5, b: 10

Type Conversion Keywords in C++

C++ provides several different type conversion keywords, each with its specific use.

  • static_cast: Used for general type conversions, including pointer to integer, integer to pointer, etc.
  • const_cast: Used to remove or add const qualification.
  • reinterpret_cast: Used for conversions between pointers, especially between different pointer types.
  • dynamic_cast: Primarily used for type conversion in polymorphic contexts, for downcasting.
#include <iostream>

class Base {
public:
    virtual ~Base() {}
};

class Derived : public Base {};

int main() {
    Base* basePtr = new Derived();
    Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Safe downcast

    if (derivedPtr != nullptr) {
        std::cout << "Conversion successful" << std::endl;
    } else {
        std::cout << "Conversion failed" << std::endl;
    }

    delete basePtr;

    return 0;
}

Output:

Conversion successful
Share your love