Mastering C++ Operators: Unlock Efficiency or Face Errors


In our previous article, for example, we discussed variables such as int banana = 3 and int apples = 3. These two objects were positioned in the memory in different places. Let’s assume we are having a shake. After putting three bananas and three apples in a crisper, we combined them with a glass of milk and put them in the juicer. After a minute, the three bananas and apples changed into something else called shake.

Similarly, in programming, you can create other things by executing various operations on the variables and values with the help of operators. Operators are used to carry out these operations. In our last example, the operation was the grinding of apples and bananas together, and the juicer machine was the operator. This article will explore the various C++ operators, their types, the precedence and associativity of operators, and typical operator usage errors.

Introduction 

The special symbols known as operators are used in C++ programming to carry out various operations (such as logical and mathematical operations) on operands in order to create a generic program. for example,

int banana=3;

int apple=2;

int total = banana+apple; 

Using the operator “+,” we add the banana and three apples in this example, and the banana and apple are operands. There are different operators that we use in our program, including arithmetic operators, logical operators, relational operators, conditional operators, assignment operators, bitwise operators, increment decrement operators, and special operators. Each of them we will discuss separately.

Types of Operators in C++

Arithmetic Operators

    One day, I was asked to bring twenty desktop computers and ten laptops by my friend. After loading all of those systems onto a truck, I headed for his house.

e.g 

int laptops=10;

int desktops=20;

int total=laptops+desktops;

int truck=total;

On reaching the home, he asked me to keep two systems in the study room, which means 

int total=total-2;

After I had two systems in the study area, the remaining systems were split up into two equal groups and distributed to the high school students.

e.g

total=total/2;

My friend asked me the total cost of the systems after I had distributed the desktops. I calculated the total cost and presented him with the bill.

Like 

int cost_of_one_laptop=100000 ;

Int cost_of_one_desktop=50000;

Int cost_of_whole_laptop=20*cost_of_one_laptop;

Int cost_of_all_desktop=20*cost_of_one_desktop;

Int totalcost=cost_of_whole_laptop+cost_of_all_desktop;

Once I saw the bill, my friend gave me a thirty-five lac check. I went to the bank, took out thirty-five lacs, paid the company, and gave my friend the remaining amount.

E.g.

 int remainingmoney= totalcost%3500000;

We described all of the arithmetic operations in this scenario, such as modulus, multiplication (*), subtraction (-), addition (+), and division (/). Various operators are used to perform each of these operations. Similarly, in programming, these operators are employed to create a distinct program.

Relational Operators

We frequently compare various things in our daily lives to create something positive, such as when I went to the market to buy ice cream. There were two categories of ice cream: ice cream A and ice cream B. In addition to having a better flavor than Ice Cream B, Ice Cream A is quieter.

I chose to buy ice cream A after weighing the quantity and flavour. Similarly, in C++, different operators are used to compare to make a good decision, which greatly helps in programming. We will discuss different operators used in C++ one by one.

Syntax of Relational operators

Operand1 <operator>oprator2

KEY POINTS ABOUT RELATIONAL OPERATORS

  • There must be two operands
  • The result is given in the form of true or false after comparison
  • True indicates 1 and false indicates 0
  • The relational operator can not be used with a single operator
  • Operands could be values or variables

 

Greater than (>),

The greater operator is used to compare two operands.

If the left side operand1 is greater than the right side one, it will return true; otherwise, it will return false

Example 12>4;

 Less than (<),

The smaller operator is used to compare two operands.

If the right side operand is greater than the left side one, it will return true, otherwise false

operand1<operand2;

4<10;

 and the smaller operator works opposite to this one.

Equal to (==), 

The == operator checks whether the two operands are equal or not.

If both of the operands are equal then it will return true,otherwise false

Example 

operand1== operand2;

0==0;

There is a difference between (=) and (==) operators. The (=) operator is used to assign one value to another. While the (==) operator just compares the two expressions.

as 

 int operand1=13;

Here, (=) sing gives operand1 a value of 12. Conversely, == sing determines whether operand1 and operand2 are equal.

Not equal to (!=)

Another relational operator that is used for the opposite task of the equal operator is the not equal operator, which returns true if both operands are not equal but returns true if both operands are equal.

Logical Operators

Logical operators are the special operators in C++ that help to perform logical operations and help to evaluate different logics. The most common logical operators are mentioned below

AND (&&)

                        An AND operator is a binary operator that gives the output true if both of the expressions are true, otherwise false.

The general syntax of AND operator is 

EXPRESSION1 OPERATOR EXPRESSION2;

Example:

int  marks=70 ;

if(marks>=70 && marks<80)

{

cout<<” CONGRATULATIONS! You got B grade”;

}

This statement executes if both of the expressions are true. If one of these expressions is false the statement will not execute.

OR (||)

The OR operator gives true if one of the expressions meets the condition, which means if one of these expressions is true the statement will execute like

int  English =30;

int  mathematics =20;

if(English <33 || Mathematics<30)

{

cout<<” please try again next time”;

}

In this example, if one of these expressions is true the statement will execute. It is not necessary to be the bothe both expressions true.

 NOT (!).

The not-operator always works against the actual expression. If the expression is true it will make it false,if the expression is false the not operator makes it true;

General syntax is

 operator Expression2 ;

 if(!marks>33)

{

cout<<” try again please”;

}

Assignment Operators

The operators that are used to assign different values of expressions to other expressions.

Basic (=)

The equal operator is a basic assignment operator that directly assigns the value of an expression to another;

Example;

 Expression1 = Expression2;

Number1 =number2;

Compound Assignment Operators (+=, -=, *=, /=, etc.)

These operators combine arithmetic operations with assignment, performing the operation first and then assigning the result to the variable.

Example: +=

This operator first adds the values of two expressions and then assigns the result to the variable:

  • int num1 = 3;
  • int num2 = 2;
  • num1 = num1 + num2; // Equivalent to:
  • num1 += num2;       // num1 now equals 5

The same logic applies to other compound assignment operators:

  • -=: Subtracts the second operand from the first and assigns the result.
  • *=: Multiplies the operands and assigns the result.
  • /=: Divides the first operand by the second and assigns the quotient.
  • %=: Assigns the remainder of the division.

Example:

int num1 = 10;

num1 -= 3;  // num1 is now 7

num1 *= 2;  // num1 is now 14

num1 /= 7;  // num1 is now 2

 Increment and Decrement Operators

These operators are used to increase or decrease a variable’s value by one.

  • Pre-increment (++var): Increments the value before it is used.
  • Post-increment (var++): Uses the current value before incrementing it.
  • Pre-decrement (–var): Decrements the value before it is used.
  • Post-decrement (var–): Uses the current value before decrementing it.

Example:

int x = 5;

int y = ++x;  // x becomes 6, then y gets the value 6

int z = x–;  // z gets the current value of x (6), then x becomes 5

 Conditional (Ternary) Operator

The ternary operator is a shorthand for if-else conditions.

Syntax:

condition? expr1 : expr2;

If the condition is true, expr1 is evaluated; otherwise, expr2 is evaluated.

Example:

int age = 20;

string result = (age >= 18) ? “Adult” : “Minor”; // result = “Adult”

 Special Operators

1. sizeof

Returns the size (in bytes) of a data type or variable.

int x = 10;

cout << sizeof(x);  // Output: 4 (on most systems)

2. Comma (,)

Allows multiple expressions to be evaluated in a single statement.

int a, b;

a = (b = 5, b + 2);  // b = 5, then a = 7

3. Pointer (*) and Address-of (&)

Accesses the value at a memory address (dereference).

& retrieves the address of a variable.

int x = 10;

int* ptr = &x;  // ptr stores the address of x

cout << *ptr;   // Output: 10 (value at the address)

Examples and Use Cases

Example 1: Simple Calculation

int length = 5, width = 10;

int area = length * width;  // area = 50

Example 2: Logical Conditions

int age = 20;

if (age >= 18 && age < 30)

{    cout << “You are eligible for the youth program.”;}

Example 3: Using Ternary Operator

int marks = 75;

string grade = (marks >= 50) ? “Pass” : “Fail”;

cout << “Result: ” << grade;

 Common Mistakes with Operators

  • Misuse of Precedence
    Forgetting operator precedence can lead to incorrect results.

    int result = 5 + 3 * 2;  // Evaluates as 5 + (3 * 2), not (5 + 3) * 2
  • Using the Wrong Operator
    Confusing = with == in conditions.

    if (x = 10) {  // Assigns 10 to x instead of comparing    cout << “True”;}
  • Forgetting Parentheses
    In complex expressions, forgetting parentheses can make results ambiguous.

    if (a > b && b < c || a == c)  // Ambiguous without parentheses

 Conclusion

Operators are fundamental to programming in C++, enabling developers to build functional and efficient code. Understanding their types, precedence, and associativity is essential for avoiding common errors. Practice these operators in various coding exercises to gain confidence and mastery.

read more

link1

link2

Here are five concise FAQs based on the article:

  1. What are operators in C++?
    Operators in C++ are special symbols used to perform operations on variables and values, such as arithmetic, logical, and relational operations.
  2. What is the purpose of arithmetic operators in C++?
    Arithmetic operators like +, -, *, /, and % perform mathematical operations such as addition, subtraction, multiplication, division, and modulus.
  3. What are relational operators used for in C++?
    Relational operators (>, <, ==, !=) are used to compare two operands and return true or false based on the comparison result.
  4. How do logical operators work in C++?
    Logical operators (&&, ||, !) evaluate expressions to return true or false, based on logical conditions like AND, OR, and NOT.
  5. What common mistakes should be avoided when using operators in C++?
    Common mistakes include confusing the assignment operator (=) with the equality operator (==), neglecting operator precedence, and forgetting parentheses in complex expressions.

Leave a Comment