CPP Tutorials

Operators in C++ in Brief

Introduction

Hello, aspiring programmers! Get ready to explore the exciting world of operators in C++! Operators are like superheroes that empower us to perform incredible tasks in our code, making it dynamic and powerful. In this comprehensive guide, we’ll cover everything you need to know about operators. We’ll discuss why operators are essential, what they are, and how we can use them to manipulate data and control the flow of our programs. By the end of this article, you’ll have a solid understanding of operators and be ready to conquer coding challenges with ease. Let’s embark on this exciting journey together!

What are Operators?

Operators in programming are special symbols or keywords that perform specific operations on values or variables. They allow us to perform tasks like addition, subtraction, comparison, and more. For example, the plus sign (+) is an operator used for addition, while the equals sign (=) is an operator used for assignment. Operators are essential tools that help us manipulate and work with data in our programs.

Operators in C++

Operators in C++

Operators are special symbols that allow you to do different actions with numbers and values. For instance, the + symbol lets you add numbers together, and the – symbol helps you subtract them.

Operators in C++ can be classified into 8 types:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Assignment Operators
  • Bitwise Operators
  • Conditional Operator
  • Type Casting Operators
  • Miscellaneous Operators

Arithmetic Operators

Arithmetic operators are like math magicians. They perform mathematical calculations on numbers. We have operators like the addition symbol (‘+‘), subtraction symbol (‘-‘), multiplication symbol (‘*‘), division symbol (‘/‘), and even a modulus symbol (%). Let’s see them in action:

OperatorDescriptionExampleResult
+Addition5 + 38
Subtraction10 – 46
*Multiplication6 * 212
/Division16 / 44
%Modulus (remainder)17 % 52
++Increment (by 1)a = 5; a++;a = 6
Decrement (by 1)b = 8; b–;b = 7
Arithmetic Operators

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int num1 = 10, num2 = 5;

    // Addition
    int sum = num1 + num2;

    // Subtraction
    int difference = num1 - num2;

    // Multiplication
    int product = num1 * num2;

    // Division
    int quotient = num1 / num2;

    // Modulus (Remainder)
    int remainder = num1 % num2;

    // Displaying the results
    cout << "Sum: " << sum << endl;
    cout << "Difference: " << difference << endl;
    cout << "Product: " << product << endl;
    cout << "Quotient: " << quotient << endl;
    cout << "Remainder: " << remainder << endl;

    return 0;
}

Output:

C++
Sum: 15
Difference: 5
Product: 50
Quotient: 2
Remainder: 0

Explanation:

  • The example demonstrates the usage of arithmetic operators in C++.
  • The operators used are addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
  • These operators are applied to two integer variables, num1 and num2.
  • The ‘sum‘ variable stores the result of adding num1 and num2.
  • The ‘difference‘ variable stores the result of subtracting num2 from num1.
  • The ‘product‘ variable stores the result of multiplying num1 and num2.
  • The ‘quotient‘ variable stores the result of dividing num1 by num2.
  • The ‘remainder‘ variable stores the remainder when num1 is divided by num2.
  • The ‘cout‘ statement is used to display the results of these operations.

Increment and Decrement Operators in C++

C++ also provides increment and decrement operators: ++ and -- respectively.

  • ++ increases the value of the operand by 1
  • -- decreases it by 1

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int num = 5;

    // Increment Operator
    num++;  // Increment by 1
    cout << "After increment: " << num << endl;

    // Decrement Operator
    num--;  // Decrement by 1
    cout << "After decrement: " << num << endl;

    // Compound Operators
    num += 3;  // Increment by 3 using compound operator
    cout << "After adding 3: " << num << endl;

    num -= 2;  // Decrement by 2 using compound operator
    cout << "After subtracting 2: " << num << endl;

    return 0;
}

Output:

C++
After increment: 6
After decrement: 5
After adding 3: 8
After subtracting 2: 6

Explanation:

  • The code uses the “increment” (++) and “decrement” (--) operators to modify the value of a variable named ‘num‘.
  • The ‘num‘ variable is initially set to 5.
  • The “increment” operator (num++) is used to increase the value of ‘num‘ by 1.
  • The “decrement” operator (num--) is used to decrease the value of ‘num‘ by 1.
  • The code demonstrates the use of “compound operators” like += and -=. The ‘num += 3‘ statement increases the value of ‘num‘ by 3, while ‘num -= 2‘ decreases it by 2.
  • After each operation, the updated value of ‘num‘ is printed using the ‘cout‘ statement.

Relational Operators

Relational operators help us compare values and check if certain conditions are met. They are like judges who decide whether something is true or false. Let’s meet some of these judges:

OperatorDescriptionExampleResult
==Equal tox == yTrue/False
!=Not equal tox != yTrue/False
>Greater thanx > yTrue/False
<Less thanx < yTrue/False
>=Greater than or equal tox >= yTrue/False
<=Less than or equal tox <= yTrue/False
Relational Operators

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int num1 = 5, num2 = 10;

    // Using relational operators
    bool isEqual = (num1 == num2);
    bool isNotEqual = (num1 != num2);
    bool isGreater = (num1 > num2);
    bool isLess = (num1 < num2);
    bool isGreaterOrEqual = (num1 >= num2);
    bool isLessOrEqual = (num1 <= num2);

    // Displaying the results
    cout << "Is num1 equal to num2? " << isEqual << endl;
    cout << "Is num1 not equal to num2? " << isNotEqual << endl;
    cout << "Is num1 greater than num2? " << isGreater << endl;
    cout << "Is num1 less than num2? " << isLess << endl;
    cout << "Is num1 greater than or equal to num2? " << isGreaterOrEqual << endl;
    cout << "Is num1 less than or equal to num2? " << isLessOrEqual << endl;

    return 0;
}

Output:

C++
Is num1 equal to num2? 0
Is num1 not equal to num2? 1
Is num1 greater than num2? 0
Is num1 less than num2? 1
Is num1 greater than or equal to num2? 0
Is num1 less than or equal to num2? 1

Explanation:

  • The code example demonstrates the usage of relational operators in C++ to compare the values of two variables: ‘num1‘ and ‘num2‘.
  • The relational operators used are == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
  • These operators help in evaluating and determining the relationships between the values of num1 and ‘num2‘.
  • The results of these comparisons are stored in boolean variables like ‘isEqual‘, ‘isNotEqual‘, ‘isGreater‘, ‘isLess‘, ‘isGreaterOrEqual‘, and ‘isLessOrEqual‘.
  • The cout statements are used to display the results of these comparisons, indicating whether the conditions specified by the relational operators are true (1) or false (0).

Logical Operators

Logical operators help us make decisions based on conditions. They combine multiple conditions and allow us to create powerful logic in our programs. Let’s meet them:

OperatorDescriptionExampleResult
&&Logical ANDa && btrue if both a and b are true, otherwise false
||Logical ORa || btrue if either a or b (or both) are true, otherwise false
!Logical NOT!atrue if a is false, and vice versa
Logical Operators

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    bool a = true;
    bool b = false;

    // Logical AND operator
    cout << "a AND b = " << (a && b) << endl;

    // Logical OR operator
    cout << "a OR b = " << (a || b) << endl;

    // Logical NOT operator
    cout << "NOT a = " << (!a) << endl;

    return 0;
}

Output:

C++
a AND b = 0
a OR b = 1
NOT a = 0

Explanation:

  • The example involves two boolean variables named ‘a‘ and ‘b‘.
  • Logical AND (&&), logical OR (||), and logical NOT (!) operators are employed for logical operations using these variables.
  • Logical AND (&&) checks if both ‘a‘ and ‘b‘ are true, and returns false if either or both are false.
  • Logical OR (||) verifies if either ‘a‘ or ‘b‘ is true, and returns true if at least one is true.
  • Logical NOT (!) operator reverses the value of ‘a‘.
  • The program then prints out the outcomes of these logical operations.
  • The output showcases the results of the logical operations, revealing how the logical operators behave with the given boolean values.

Assignment Operators

Assignment operators help us give values to variables. They allow us to store and update information in our programs. Let’s meet them:

OperatorExampleEquivalent to
=x = 5;x = 5;
+=x += 3;x = x + 3;
-=x -= 2;x = x – 2;
*=x *= 4;x = x * 4;
/=x /= 2;x = x / 2;
%=x %= 3;x = x % 3;
<<=x <<= 1;x = x << 1;
>>=x >>= 2;x = x >> 2;
&=x &= 7;x = x & 7;
^=x ^= 5;x = x ^ 5;
|=x |= 3;x = x | 3;
Assignment Operators

Cod Example:

C++
#include <iostream>
using namespace std;

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

    // Assignment operators
    b += a;
    cout << "b += a: " << b << endl;

    b -= a;
    cout << "b -= a: " << b << endl;

    b *= a;
    cout << "b *= a: " << b << endl;

    b /= a;
    cout << "b /= a: " << b << endl;

    b %= a;
    cout << "b %= a: " << b << endl;

    b &= a;
    cout << "b &= a: " << b << endl;

    b |= a;
    cout << "b |= a: " << b << endl;

    b ^= a;
    cout << "b ^= a: " << b << endl;

    b <<= a;
    cout << "b <<= a: " << b << endl;

    b >>= a;
    cout << "b >>= a: " << b << endl;

    return 0;
}

Output:

C++
b += a: 15
b -= a: 5
b *= a: 50
b /= a: 5
b %= a: 5
b &= a: 0
b |= a: 10
b ^= a: 0
b <<= a: 0
b >>= a: 0

Explanation:

  • In this example, there are two integer variables, ‘a‘ and ‘b‘, initialized with values 10 and 5 respectively.
  • Different assignment operators are used to modifying the value of the variable ‘b‘ based on its initial value and the value of variable ‘a‘.
  • The ‘+= ‘operator adds the value of a to ‘b‘, resulting in ‘b‘ being updated to 15.
  • The ‘-=‘ operator subtracts the value of ‘a‘ from ‘b‘, reverting ‘b‘ back to 5.
  • The ‘*=‘ operator multiplies the value of ‘a‘ with ‘b‘, making ‘b‘ equal to 50.
  • The ‘/=‘ operator divides the value of ‘b‘ by ‘a‘, changing ‘b‘ to 5 again.
  • The ‘%=‘ operator calculates the remainder when b is divided by ‘a‘, keeping ‘b‘ at 5.
  • The ‘&=‘ operator performs a bitwise AND between ‘a‘ and ‘b‘, resulting in ‘b‘ becoming 0.
  • The ‘|=‘ operator performs a bitwise OR between ‘a‘ and ‘b‘, setting ‘b‘ to 10.
  • The ‘^=‘ operator performs a bitwise XOR between ‘a‘ and ‘b‘, resetting ‘b‘ to 0.
  • The ‘<<=‘ operator shifts the bits of ‘b‘ left by the value of ‘a‘, leaving ‘b‘ as 0.
  • The ‘>>=‘ operator shifts the bits of ‘b‘ right by the value of ‘a‘, maintaining ‘b‘ as 0.
  • The output shows the updated value of the ‘b‘ after each assignment operation.

Bitwise Operators

Bitwise operators perform operations on individual bits of values.

OperatorDescriptionExampleResult
&Bitwise ANDnum1 & num2Bitwise AND of num1 and num2
|Bitwise ORnum1 | num2Bitwise OR of num1 and num2
^Bitwise XOR (exclusive OR)num1 ^ num2Bitwise XOR of num1 and num2
~Bitwise NOT (complement)~num1Bitwise NOT of num1
<<Left Shiftnum1 << 1Left shift num1 by 1 bit
>>Right Shiftnum1 >> 1Right shift num1 by 1 bit
Bitwise Operators

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int num1 = 5;  // Binary: 0101
    int num2 = 3;  // Binary: 0011

    // Bitwise AND
    int resultAND = num1 & num2;  // Binary: 0001
    cout << "Bitwise AND: " << resultAND << endl;

    // Bitwise OR
    int resultOR = num1 | num2;  // Binary: 0111
    cout << "Bitwise OR: " << resultOR << endl;

    // Bitwise XOR
    int resultXOR = num1 ^ num2;  // Binary: 0110
    cout << "Bitwise XOR: " << resultXOR << endl;

    // Bitwise NOT (Unary Operator)
    int resultNOT1 = ~num1;  // Binary: 11111010 (32-bit representation)
    int resultNOT2 = ~num2;  // Binary: 11111100 (32-bit representation)
    cout << "Bitwise NOT of num1: " << resultNOT1 << endl;
    cout << "Bitwise NOT of num2: " << resultNOT2 << endl;

    // Left Shift Operator
    int leftShift = num1 << 1;  // Binary: 1010 (Decimal: 10)
    cout << "Left Shift: " << leftShift << endl;

    // Right Shift Operator
    int rightShift = num1 >> 1;  // Binary: 0010 (Decimal: 2)
    cout << "Right Shift: " << rightShift << endl;

    return 0;
}

Output:

C++
Bitwise AND: 1
Bitwise OR: 7
Bitwise XOR: 6
Bitwise NOT of num1: -6
Bitwise NOT of num2: -4
Left Shift: 10
Right Shift: 2

Explanation:

  • This C++ program demonstrates the use of bitwise operators on two integers, ‘num1‘ (5) and ‘num2‘ (3).
  • Bitwise AND (&), OR (|), and XOR (^) operations are performed, comparing each bit of ‘num1‘ and ‘num2‘ and setting the result bits accordingly.
  • Bitwise NOT (~) operation is performed, flipping the bits of ‘num1‘ and ‘num2‘.
  • Bitwise shift operations are performed: Left Shift (<<) shifts the bits of ‘num1‘ to the left by one place and Right Shift (>>) shifts the bits of ‘num1‘ to the right by one place.
  • The results of all operations are printed to the console.
  • The program ends by returning 0, indicating successful execution.

Conditional Operator

The conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. It has the form ‘condition ? expression1 : expression2‘.

OperatorDescriptionExampleResult
? :Conditional Operatorcondition ? value1 : value2If condition is true, returns value1, otherwise returns value2
Conditional Operator

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int num1 = 10, num2 = 20;

    // Using conditional operator to find the maximum
    int maxNum = (num1 > num2) ? num1 : num2;

    cout << "The maximum number is: " << maxNum << endl;

    return 0;
}

Output:

C++
The maximum number is: 20

Explanation:

  • The conditional operator (? :) is used to check a condition: ‘num1 > num2‘.
  • If ‘num1 > num2‘ is true, ‘num1‘ is assigned to ‘maxNum‘.
  • If ‘num1 > num2‘ is false, ‘num2‘ is assigned to ‘maxNum‘.
  • The value of ‘maxNum‘ is then printed to the console. This will be the greater of ‘num1‘ and ‘num2‘.

Type Casting Operators

These operators are used to explicitly convert between different data types or perform type conversions that might not be implicitly handled by the compiler. It’s important to use the appropriate casting operator based on the context and desired type of conversion behavior.

OperatorDescriptionExample
static_castPerforms a wide range of type conversions, checked at compile-time.double num = static_cast<double>(intNum);
dynamic_castUsed in polymorphic classes to safely downcast pointers or references.Derived* d = dynamic_cast<Derived*>(basePtr);
const_castAdds or removes the const qualifier from a variable.int* mutablePtr = const_cast<int*>(constPtr);
reinterpret_castConverts a pointer to an unrelated type, often used for low-level operations.char* bytePtr = reinterpret_cast<char*>(&intNum);
C-style CastA legacy cast that can perform a wide range of conversions. It’s less safe compared to other casts.double num = (double)intNum;
Type Casting Operators

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int numInt = 10;
    float numFloat = 15.75;

    // Implicit conversion using promotion
    float resultImplicit = numInt + numFloat;
    cout << "Implicit conversion result: " << resultImplicit << endl;

    // Explicit type casting
    int resultExplicit = int(numFloat);
    cout << "Explicit conversion result: " << resultExplicit << endl;

    // C-style casting
    double resultCStyle = (double)numInt;
    cout << "C-style casting result: " << resultCStyle << endl;

    // static_cast
    int resultStatic = static_cast<int>(numFloat);
    cout << "static_cast result: " << resultStatic << endl;

    // dynamic_cast - not applicable to simple types
    // reinterpret_cast - not applicable to simple types

    return 0;
}

Output:

C++
Implicit conversion result: 25.75
Explicit conversion result: 15
C-style casting result: 10
static_cast result: 15

Explanation:

  • dynamic_cast‘ and ‘reinterpret_cast‘ are specific types of casting operators in C++.
  • They are primarily used in complex situations involving pointers and class hierarchies.
  • dynamic_cast‘ is used for converting pointers and references within an inheritance hierarchy.
  • reinterpret_cast‘ is used for low-level casts that yield implementation-dependent results.
  • Neither of these casting operators is applicable to simple types like integers and floats.

Miscellaneous Operators

There are several other operators in C++ that serve various purposes.

OperatorDescription
sizeofReturns the size in bytes of a data type or variable.
typeidReturns the type information of an expression.
&Returns the memory address of a variable.
*Pointer to a variable.
?:Conditional (ternary) operator. Evaluates an expression and returns one of two values based on a condition.
,Comma operator. Separates expressions in a statement and evaluates them from left to right.
Miscellaneous Operators

Code Example:

Certainly! Here’s a simple code example that includes various miscellaneous operators in C++ along with their explanations and outputs:

C++
#include <iostream>
using namespace std;

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

    // sizeof() Operator
    cout << "Size of int data type: " << sizeof(int) << " bytes" << endl;

    // Conditional Operator
    int maxNum = (a > b) ? a : b;
    cout << "Maximum of " << a << " and " << b << " is: " << maxNum << endl;

    // Comma Operator
    int x = (a++, b++);
    cout << "Value of x: " << x << endl;

    // Bitwise Operators
    int bitwiseAND = a & b;
    int bitwiseOR = a | b;
    cout << "Bitwise AND of " << a << " and " << b << " is: " << bitwiseAND << endl;
    cout << "Bitwise OR of " << a << " and " << b << " is: " << bitwiseOR << endl;

    // Unary Operators
    int negateA = -a;
    int postIncrement = a++;
    int preIncrement = ++b;
    cout << "Negation of " << a << " is: " << negateA << endl;
    cout << "Post-increment of " << a << ": " << postIncrement << endl;
    cout << "Pre-increment of " << b << ": " << preIncrement << endl;

    return 0;
}

Output:

C++
Size of int data type: 4 bytes
Maximum of 10 and 4 is: 10
Value of x: 4
Bitwise AND of 10 and 4 is: 0
Bitwise OR of 10 and 4 is: 14
Negation of 10 is: -10
Post-increment of 10: 10
Pre-increment of 5: 6

Explanation:

  • The example demonstrates the use of various miscellaneous operators in C++.
  • The ‘sizeof()‘ operator is used to determine the size of a variable or data type.
  • The conditional operator (?:) is used to perform different computations based on a condition.
  • The comma operator (,) is used to link related expressions together.
  • Bitwise operators (&, |, ^, ~, <<, >>) are used for the manipulation of individual bits of a number.
  • Unary operators (such as ++, --, !, ~) are used to perform operations on a single operand.
  • The outputs of these operations are also demonstrated.

Operator Precedence and Associativity

Operator precedence and associativity in C++ are rules that determine the order in which operators are evaluated in an expression. These rules help the compiler understand how to perform calculations correctly.

Operator Precedence: This defines which operators are evaluated first. For example, multiplication (*) usually takes precedence over addition (+). So, in the expression ‘a + b * c‘, ‘b * c‘ would be calculated before adding to ‘a‘.

Associativity: When there are multiple operators of the same precedence, associativity decides the order in which they are evaluated. For instance, the expression ‘a - b - c‘, the associativity of the subtraction operator is left-to-right. So, it’s evaluated as ‘(a - b) - c‘.

Understanding these rules is important to writing accurate and predictable code. It ensures that complex expressions are evaluated correctly, following the rules set by the language.

Overloading Operators

Overloading operators in C++ means giving special meanings to existing operators so that they can work with user-defined data types. It allows you to use operators like +, -, *, etc., with your own classes or data types, just like you use them with built-in types like integers or floating-point numbers. This makes your code more intuitive and expressive.

For instance, you can define how the ‘+‘ operator should behave when applied to two instances of your class. This enables you to perform custom operations or computations that make sense for your data type. Overloading operators let you use familiar syntax to work with your own objects, making your code easier to understand and maintain.

Summary

Congratulations, young programmers! You have explored the fascinating world of operators in C++. We’ve met arithmetic operators who perform mathematical magic, relational operators who compare values, logical operators who make decisions, and assignment operators who give values to variables. Understanding and mastering these operators will empower you to create amazing programs and bring your ideas to life. Keep coding and embracing the power of operators!

Frequently Asked Questions (FAQs)

FAQ 1: What are operators in C++?

ANS. Operators in C++ are symbols or keywords that perform various operations on one or more operands. They are used to manipulate data, perform calculations, and make logical comparisons within a program.

FAQ 2: What are the different types of operators in C++?

ANS. C++ supports several types of operators, including arithmetic operators (+, -, *, /, %), relational operators (==, !=, <, >, <=, >=), logical operators (&&, ||, !), assignment operators (=, +=, -=, *=, /=), bitwise operators (&, |, ^, ~, <<, >>), and more.

FAQ 3: What is the precedence and associativity of operators?

ANS. The precedence of operators determines the order in which they are evaluated in an expression. Operators with higher precedence are evaluated first. In the case of operators with the same precedence, the associativity (either left-to-right or right-to-left) determines the order of evaluation.

FAQ 4: Can operators be overloaded in C++?

ANS. Yes, C++ allows for operator overloading, which means redefining the behavior of an operator for a user-defined class or data type. Operator overloading enables objects of a class to behave like built-in types and provides a more intuitive and concise syntax for certain operations.

FAQ 5: What is the difference between unary and binary operators?

ANS. Unary operators operate on a single operand, while binary operators operate on two operands. Unary operators include operators like ++ (increment), — (decrement), and ! (logical NOT). Binary operators include arithmetic operators, relational operators, assignment operators, and more.

FAQ 6: How are arithmetic operators used in C++?

ANS. Arithmetic operators in C++ are used to perform basic mathematical calculations. They include addition (+), subtraction (-), multiplication (*), division (/), and modulo (%). These operators can be used with numeric data types to perform operations like addition, subtraction, multiplication, division, and finding the remainder.

FAQ 7: What are the logical operators in C++ used for?

ANS. Logical operators in C++ are used to perform logical operations on boolean values or expressions. They include the AND operator (&&), OR operator (||), and NOT operator (!). Logical operators are typically used to evaluate multiple conditions and make decisions based on the results.

FAQ 8: How do assignment operators work in C++?

ANS. Assignment operators in C++ are used to assign a value to a variable. The basic assignment operator is the equals sign (=), but C++ also provides compound assignment operators like +=, -=, *=, and /=, which combine an arithmetic operation with the assignment.

FAQ 9: What are the bitwise operators used in C++?

ANS. Bitwise operators in C++ are used to manipulate individual bits of integers. They include operators like bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~), left shift (<<), and right shift (>>). Bitwise operators are commonly used in low-level programming, network protocols, and manipulating hardware registers.

FAQ 10: How is the ternary conditional operator and comma operator used in C++?

ANS. The ternary conditional operator (?:) allows for conditional expressions and returns one of two values based on a condition. The comma operator (,) is used to separate multiple expressions and evaluates them from left to right, returning the value of the rightmost expression.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Index
Becoming a Full Stack Developer in 2023 How to Become a Software Engineer in 2023
Close

Adblock Detected

Please consider supporting us by disabling your ad blocker!