Cpp Programming Operators And Expressions Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    13 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of CPP Programming Operators and Expressions

C++ Programming: Operators and Expressions

Types of Operators in C++

  1. Arithmetic Operators

    • + (Addition): Adds two numbers.
      int sum = 5 + 3; // sum = 8
      
    • - (Subtraction): Subtracts second operand from first.
      int difference = 5 - 3; // difference = 2
      
    • * (Multiplication): Multiplies two numbers.
      int product = 5 * 3; // product = 15
      
    • / (Division): Divides first operand by second.
      int quotient = 5 / 3; // quotient = 1 (integer division)
      
    • % (Modulus): Returns the remainder of integer division.
      int remainder = 5 % 3; // remainder = 2
      
    • ++ (Increment): Increases the value by one.
      int a = 5;
      a++; // a = 6
      
    • -- (Decrement): Decreases the value by one.
      int b = 5;
      b--; // b = 4
      
  2. Relational Operators

    • == (Equal to): Checks if two values are equal.
      bool isEqual = (5 == 3); // isEqual = false
      
    • != (Not equal to): Checks if two values are not equal.
      bool isNotEqual = (5 != 3); // isNotEqual = true
      
    • > (Greater than): Checks if left operand is greater than right.
      bool isGreater = (5 > 3); // isGreater = true
      
    • < (Less than): Checks if left operand is less than right.
      bool isLess = (5 < 3); // isLess = false
      
    • >= (Greater than or equal to): Checks if left operand is greater than or equal to right.
      bool isGreaterOrEqual = (5 >= 3); // isGreaterOrEqual = true
      
    • <= (Less than or equal to): Checks if left operand is less than or equal to right.
      bool isLessOrEqual = (5 <= 3); // isLessOrEqual = false
      
  3. Logical Operators

    • && (Logical AND): Returns true if both conditions are true.
      bool resultAnd = ((5 > 3) && (3 > 1)); // resultAnd = true
      
    • || (Logical OR): Returns true if at least one condition is true.
      bool resultOr = ((5 > 3) || (3 < 1)); // resultOr = true
      
    • ! (Logical NOT): Reverses the logical state of its operand.
      bool resultNot = !(5 > 3); // resultNot = false
      
  4. Assignment Operators

    • = (Simple assignment): Assigns value of right operand to left operand.
      int x = 5; // x = 5
      
    • += (Add and assign): Adds right operand to the left and assigns the result to left operand.
      int x = 5;
      x += 3; // x = 8
      
    • -= (Subtract and assign): Subtracts right operand from left and assigns the result to left operand.
      int x = 5;
      x -= 3; // x = 2
      
    • *= (Multiply and assign): Multiplies left operand with right and assigns the result to left operand.
      int x = 5;
      x *= 3; // x = 15
      
    • /= (Divide and assign): Divides left operand by right and assigns the result to left operand.
      int x = 5;
      x /= 3; // x = 1 (integer division)
      
    • %= (Modulus and assign): Takes modulus using two operands and assigns the result to left operand.
      int x = 5;
      x %= 3; // x = 2
      
  5. Bitwise Operators

    • & (Bitwise AND): Performs binary AND on each bit of its operands.
      int resultAnd = 5 & 3; // resultAnd = 1 (0101 & 0011 = 0001)
      
    • | (Bitwise OR): Performs binary OR on each bit of its operands.
      int resultOr = 5 | 3; // resultOr = 7 (0101 | 0011 = 0111)
      
    • ^ (Bitwise XOR): Performs binary XOR on each bit of its operands.
      int resultXor = 5 ^ 3; // resultXor = 6 (0101 ^ 0011 = 0110)
      
    • ~ (Bitwise NOT): Flips the bits of its operand.
      int resultNot = ~5; // resultNot = -6 (flips 0101 to 1010, with sign bit considering it as negative)
      
    • << (Left shift): Shifts the bits of the first operand to the left by a number of positions specified by the second operand.
      int resultLeftShift = 5 << 1; // resultLeftShift = 10 (0101 << 1 = 1010)
      
    • >> (Right shift): Shifts the bits of the first operand to the right by a number of positions specified by the second operand.
      int resultRightShift = 5 >> 1; // resultRightShift = 2 (0101 >> 1 = 0010)
      
  6. Conditional (Ternary) Operator

    • ? : (Conditional): Evaluates a condition; if true, it returns the value of the first expression; otherwise, it returns the value of the second expression.
      int result = (5 > 3) ? 10 : 20; // result = 10
      
  7. Comma Operator

    • , (Comma): Evaluates both of its operands (from left to right) and returns the value of the second operand.
      int a, b;
      a = (b = 5, b + 3); // b = 5, a = 8
      
  8. Sizeof Operator

    • sizeof: Returns the size, in bytes, of its operand or type.
      int size = sizeof(int); // size = 4 (depends on compiler and architecture)
      

Expressions in C++

An expression in C++ can be anything as simple as a literal value (e.g., 42), a variable (x), or a complex set of operations between variables and values (e.g., (a + 3) * b). Expressions are classified based on the number of operands they contain.

  • Unary Expressions: Contain a single operand.

    int a = -5; // Unary minus
    bool b = !false; // Unary NOT
    
  • Binary Expressions: Contain two operands.

    int c = 5 + 3; // Binary plus
    bool d = (a > 3); // Binary relational operator
    
  • Ternary Expressions: Contain three operands.

    int e = (a > 0) ? 1 : 0; // Ternary conditional operator
    

Important Information

  • Operator Precedence: Operators have different levels of precedence, which control the order in which operands and operators are grouped. For example, in the expression a + b * c, multiplication (*) is evaluated before addition (+).

  • Operator Associativity: When operators of the same precedence appear in an expression, their associativity defines the order in which they are evaluated. Most binary operators are left-to-right associative, while a few are right-to-left associative.

  • Short-Circuit Evaluation: Logical operators (&& and ||) use short-circuit evaluation, meaning the second operand is evaluated only if necessary. For example, in a && b, if a is false, b is not evaluated because the result of a && b must be false.

  • Constants and Literals: Constants are values that don’t change during execution, whereas literals are constant values written directly in the code. C++ supports different types of literals, such as integer literals, floating-point literals, and string literals.

Understanding and effectively using operators and expressions in C++ enhances code efficiency, readability, and maintainability. They offer powerful tools for performing computations and logical tests, ultimately making the development process more streamlined and effective.

Conclusion

Mastery of C++ operators and expressions is crucial for any C++ developer. By grasping the different types of operators and understanding their precedence and associativity, you can write more robust and efficient code. Furthermore, expressions, with their varied forms, provide a flexible way to perform calculations and logical evaluations, enabling developers to handle complex computational tasks with ease.


Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement CPP Programming Operators and Expressions

1. Arithmetic Operators

Arithmetic operators perform basic arithmetic operations on variables and constants.

Example: Basic Arithmetic Operations

#include <iostream>

int main() {
    int a = 10, b = 5;
    int sum, difference, product, quotient, remainder;

    // Addition
    sum = a + b; // 10 + 5
    std::cout << "Sum: " << sum << std::endl;

    // Subtraction
    difference = a - b; // 10 - 5
    std::cout << "Difference: " << difference << std::endl;

    // Multiplication
    product = a * b; // 10 * 5
    std::cout << "Product: " << product << std::endl;

    // Division
    quotient = a / b; // 10 / 5
    std::cout << "Quotient: " << quotient << std::endl;

    // Modulus (Remainder)
    remainder = a % b; // 10 % 5
    std::cout << "Remainder: " << remainder << std::endl;

    return 0;
}

Step-by-Step Explanation:

  1. Include the iostream library to use std::cout.
  2. Define two integer variables a and b with values 10 and 5 respectively.
  3. Declare additional integer variables (sum, difference, product, quotient, remainder) to store the results of the operations.
  4. Use the + operator to add a and b, storing the result in sum.
  5. Use the - operator to subtract b from a, storing the result in difference.
  6. Use the * operator to multiply a and b, storing the result in product.
  7. Use the / operator to divide a by b, storing the integer part of the division in quotient.
  8. Use the % operator to find the remainder of the division of a by b, storing it in remainder.
  9. Print the results using std::cout.

2. Relational Operators

Relational operators compare two values and return a boolean result (true or false).

Example: Using Relational Operators

#include <iostream>

int main() {
    int a = 20, b = 10;

    std::cout << "a == b: " << (a == b) << std::endl; // False
    std::cout << "a != b: " << (a != b) << std::endl; // True
    std::cout << "a > b: " << (a > b) << std::endl;    // True
    std::cout << "a < b: " << (a < b) << std::endl;    // False
    std::cout << "a >= b: " << (a >= b) << std::endl;   // True
    std::cout << "a <= b: " << (a <= b) << std::endl;   // False

    return 0;
}

Step-by-Step Explanation:

  1. Define two integer variables a and b with values 20 and 10 respectively.
  2. Use relational operators:
    • == checks if a is equal to b.
    • != checks if a is not equal to b.
    • > checks if a is greater than b.
    • < checks if a is less than b.
    • >= checks if a is greater than or equal to b.
    • <= checks if a is less than or equal to b.
  3. Print the results using std::cout. Note that true and false print as 1 and 0, respectively.

3. Logical Operators

Logical operators allow the construction of complex logical conditions by combining multiple relational expressions.

Example: Using Logical Operators

#include <iostream>

int main() {
    bool p = true;
    bool q = false;

    std::cout << "p && q: " << (p && q) << std::endl; // Logical AND
    std::cout << "p || q: " << (p || q) << std::endl; // Logical OR
    std::cout << "!p: " << (!p) << std::endl;         // Logical NOT

    return 0;
}

Step-by-Step Explanation:

  1. Define two boolean variables p and q with values true and false.
  2. Use logical operators:
    • && (logical AND) evaluates to true only if both p and q are true.
    • || (logical OR) evaluates to true if either or both of p and q are true.
    • ! (logical NOT) inverts the value of p.
  3. Print the results using std::cout.

4. Assignment Operators

Assignment operators assign values to variables.

Example: Using Assignment Operators

#include <iostream>

int main() {
    int a = 5;
    int b;

    std::cout << "Initial value of a: " << a << std::endl;

    // Simple assignment
    b = a;
    std::cout << "Simple assignment (b = a): " << b << std::endl;

    // Compound assignments
    a += 3; // Equivalent to a = a + 3
    std::cout << "Compound addition (a += 3): " << a << std::endl;

    a -= 2; // Equivalent to a = a - 2
    std::cout << "Compound subtraction (a -= 2): " << a << std::endl;

    a *= 2; // Equivalent to a = a * 2
    std::cout << "Compound multiplication (a *= 2): " << a << std::endl;

    a /= 3; // Equivalent to a = a / 3
    std::cout << "Compound division (a /= 3): " << a << std::endl;

    a %= 2; // Equivalent to a = a % 2
    std::cout << "Compound modulus (a %= 2): " << a << std::endl;

    return 0;
}

Step-by-Step Explanation:

  1. Define an integer variable a with a value of 5 and an uninitialized integer variable b.
  2. Print the initial value of a.
  3. Assign the value of a to b using the simple assignment operator =.
  4. Use compound assignment operators to perform arithmetic and assignment in one step:
    • += adds a value to a.
    • -= subtracts a value from a.
    • *= multiplies a by a value.
    • /= divides a by a value.
    • %= assigns the remainder of a divided by a value back to a.
  5. Print the results after each operation using std::cout.

5. Bitwise Operators

Bitwise operators perform operations at the bit level.

Example: Using Bitwise Operators

#include <iostream>

int main() {
    unsigned int a = 60; // Binary: 0011 1100
    unsigned int b = 13; // Binary: 0000 1101

    std::cout << "a & b: " << (a & b) << std::endl; // Bitwise AND
    std::cout << "a | b: " << (a | b) << std::endl; // Bitwise OR
    std::cout << "a ^ b: " << (a ^ b) << std::endl; // Bitwise XOR
    std::cout << "~a: " << (~a) << std::endl;       // Bitwise NOT (Note: The output will be a large positive number due to unsigned int)
    std::cout << "a << 1: " << (a << 1) << std::endl; // Left Shift by 1
    std::cout << "a >> 1: " << (a >> 1) << std::endl; // Right shift by 1

    return 0;
}

Step-by-Step Explanation:

  1. Define two unsigned integer variables a and b with decimal values 60 and 13, which correspond to binary values 0011 1100 and 0000 1101 respectively.
  2. Use bitwise operators:
    • & (bitwise AND) compares corresponding bits. If both bits are 1, it returns 1, else 0.
    • | (bitwise OR) compares corresponding bits. If either bit is 1, it returns 1.
    • ^ (bitwise XOR) compares corresponding bits. It returns 1 if bits are different, otherwise 0.
    • ~ (bitwise NOT) inverts all bits. Since we're using an unsigned int, the result is still in positive form.
    • << (left shift) shifts the bits of the number to the left and fills in zeros on the right.
    • >> (right shift) shifts the bits of the number to the right and adds zeros on the left.
  3. Print the results using std::cout.

6. Conditional (Ternary) Operator

Conditional operators (also known as ternary operators) evaluate one condition and execute the first block if the condition is true, otherwise, they execute the second block.

Example: Conditional (Ternary) Operator

#include <iostream>

int main() {
    int score = 85;
    char grade;

    // Conditional operator
    grade = (score >= 60) ? 'P' : 'F';  // P for Pass, F for Fail

    std::cout << "Score: " << score << ", Grade: " << grade << std::endl;

    return 0;
}

Step-by-Step Explanation:

  1. Define an integer variable score with a value of 85.
  2. Declare a character variable grade.
  3. Use the conditional operator ? : to determine the grade:
    • (score >= 60) ? 'P' : 'F': Evaluates the condition score >= 60. If true, grade is assigned the value 'P' (Pass); otherwise, 'F' (Fail).
  4. Print the results using std::cout.

7. Comma Operator

Comma operators allow you to separate more than one expression where only one is expected.

Example: Using Comma Operator

#include <iostream>

int main() {
    int a = 10, b = 20;
    int c = ++a, b = --b; // Increment a, Decrement b, Assign new a to c 

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

    return 0;
}

Step-by-Step Explanation:

  1. Initialize integers a and b with values 10 and 20.
  2. Use the comma operator to increment a and then assign its new value to c, while simultaneously decrementing b.
  3. Notice, though, that in this code, variable declaration b = --b; is invalid since b has already been declared in the same scope.
  4. Correct the code by changing b = --b to another valid expression, e.g., int d = ++a, e = --b;.

Here’s the corrected example:

#include <iostream>

int main() {
    int a = 10, b = 20;
    int c = ++a, d = --b; // Corrected by introducing another variable d for decrementing b
  
    std::cout << "a: " << a << ", b: " << b << ", c: " << c << ", d: " << d << std::endl;

    return 0;
}

Step-by-Step Explanation:

  1. Correctly use the comma operator to perform two independent operations in one statement.
  2. Increment a and assign its new value to c.
  3. Decrement b and assign its new value to d.
  4. Print the results using std::cout.

8. Sizeof Operator

Sizeof operator returns the size (in bytes) of a data type or variable.

Example: Using Sizeof Operator

#include <iostream>

int main() {
    int a;
    double b;
    char c;

    std::cout << "Size of int: " << sizeof(a) << " bytes." << std::endl;
    std::cout << "Size of double: " << sizeof(b) << " bytes." << std::endl;
    std::cout << "Size of char: " << sizeof(c) << " byte." << std::endl;

    return 0;
}

Step-by-Step Explanation:

  1. Declare three variables of different types (int, double, char).
  2. Use the sizeof operator to determine the size of each data type in bytes.
  3. Print the results using std::cout.

Top 10 Interview Questions & Answers on CPP Programming Operators and Expressions

1. What are the different types of operators in C++?

Answer: C++ supports various categories of operators, which are used to perform operations on variables and data. The main types of operators in C++ are:

  • Arithmetic Operators: +, -, *, /, %, ++, --
  • Assignment Operators: =, +=, -=, *=, /=, %=
  • Comparison (Relational) Operators: ==, !=, >, <, >=, <=
  • Logical Operators: && (AND), || (OR), ! (NOT)
  • Bitwise Operators: &, |, ^, ~, <<, >>
  • Member Access Operators: . (member selection), -> (pointer to member selection)
  • Conditional (Ternary) Operator: ? :
  • Comma Operator: ,
  • Sizeof Operator: sizeof()
  • Pointer Operators: * (dereference), & (address-of)

2. What is the precedence and associativity of operators in C++?

Answer: Operator precedence determines the order in which operators are evaluated in an expression. If two operators in an expression have the same precedence, the associativity determines the order of evaluation.

Example of Precedence:

  • The postfix increment a++ and postfix decrement a-- have higher precedence than the prefix increment ++a and prefix decrement --a.
  • Multiplicative operators *, /, % have higher precedence than additive operators +, -.

Associativity:

  • Most binary operators (operators that take two operands) are left-to-right associative.
  • For example, in a + b + c, first a + b is evaluated, then the result is added to c.
  • Exceptionally, assignment operators (=, +=, -=, etc.), the conditional operator (?:), and the comma operator (,) are right-to-left associative.

3. How are operators overloaded in C++?

Answer: Operator overloading allows you to define the behavior of operators when applied to user-defined types (classes and structs). Overloaded operators are essentially functions but they are invoked using their operator symbol and operands.

Syntax:

type operator symbol(type param1, type param2);

Example:

class Complex {
public:
    int real, imag;
    Complex(int r = 0, int i = 0) : real(r), imag(i) {}
    Complex operator + (const Complex& obj) {
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;
        return res;
    }
};

4. What is the difference between prefix and postfix increment/decrement operators in C++?

Answer: Both prefix (++a / --a) and postfix (a++ / a--) increment and decrement operators increase or decrease the integer value by 1, but they differ in how they return the value:

Prefix (++a / --a):

  • Increment or decrement the value first.
  • Return the modified value from the expression.

Postfix (a++ / a--):

  • Return the current value from the expression.
  • Increment or decrement the value after it has been used in the expression.

Example:

int a = 5;
int x = a++;  // x = 5, a = 6 (Postfix)
int y = ++a;  // y = 7, a = 7 (Prefix)

5. What is the difference between == and = operators in C++?

Answer:

  • = Operator: The assignment operator is used to assign the value on its right to the variable on its left. It changes the value of the left operand to the value of the right operand.
  • == Operator: The equality operator is used to compare two values for equality. It checks whether the value on its left is equal to the value on its right. It returns a boolean value (true or false).

Example:

int a = 5;
int b = 10;
a = b;        // a is now 10 (Assignment)
if (a == b) { // true (Equality check)
    // block of code to execute
}

6. What is a conditional (ternary) operator in C++?

Answer: The conditional operator is a one-line replacement for the if-else statement in C++. It takes three operands and is written as:

condition ? expression_if_true : expression_if_false;

Example:

int a = 10, b = 20;
int max = (a > b) ? a : b;  // max will be 20

7. What is the function of the bitwise operators in C++?

Answer: Bitwise operators perform operations on the individual bits of integers. The bitwise operators in C++ are:

  • & (AND): Sets each bit to 1 if both bits are 1.
  • | (OR): Sets each bit to 1 if one of two bits is 1.
  • ^ (XOR): Sets each bit to 1 if only one of two bits is 1.
  • ~ (NOT): Flips all the bits.
  • << (Left Shift): Shifts the bits of the first operand to the left by a number of positions specified by the second operand.
  • >> (Right Shift): Shifts the bits of the first operand to the right by a number of positions specified by the second operand.

Example:

int a = 5; // 101 in binary
int b = 3; // 011 in binary

int andResult = a & b; // 001 (1)
int orResult = a | b;  // 111 (7)
int xorResult = a ^ b; // 110 (6)
int notResult = ~a;    // 11111111111111111111111111111010 (-6 in 2's complement)
int leftShift = a << 1; // 1010 (10)
int rightShift = a >> 1; // 010 (2)

8. What is the difference between == and is operators in C++?

Answer: In C++, there is no is operator like in some other languages (e.g., Python). The == operator is used for equality comparison in C++. There is also the != operator for inequality comparison.

However, if you are asking about identity comparison which in some languages is done using is, then in C++, you use the == operator to compare the values of primitive types, and for pointers, you can use == to check if two pointers point to the same memory location.

9. What is a compound assignment operator in C++?

Answer: Compound assignment operators are used to assign the value of an arithmetic expression to its left operand. They combine an arithmetic or bitwise operation with the assignment statement.

Common compound assignment operators include:

  • +=: Addition assignment.
  • -=: Subtraction assignment.
  • *=: Multiplication assignment.
  • /=: Division assignment.
  • %=: Modulus assignment.
  • &=: Bitwise AND assignment.
  • |=: Bitwise OR assignment.
  • ^=: Bitwise XOR assignment.
  • <<=: Left shift assignment.
  • >>=: Right shift assignment.

Example:

int a = 10;
a += 5; // equivalent to a = a + 5; a is now 15

10. What is the use of the sizeof operator in C++?

Answer: The sizeof operator in C++ is a compile-time operator that determines the size, in bytes, of a type or a variable. It can be used to determine the size of any data type, including basic types, user-defined types (like classes and structures), and even expressions.

Syntax:

sizeof(type);
sizeof(variable);

Example:

You May Like This Related .NET Topic

Login to post a comment.