Home Icon Home Resource Centre Operators In C++ | Types, Precedence & Associativity (+ Examples)

Operators In C++ | Types, Precedence & Associativity (+ Examples)

Operators in C++ are a set of symbols that enable users to manipulate values in the program and operate a variety of operations on them. They help in solving complex algorithms with ease.
Shivani Goyal
Schedule Icon 0 min read
Operators In C++ | Types, Precedence & Associativity (+ Examples)
Schedule Icon 0 min read

Table of content: 

  • What Is Operator In C++?
  • Types Of Operators In C++ With Examples
  • What Are Arithmetic Operators In C++?
  • What Are Assignment Operators In C++?
  • What Are Relational Operators In C++?
  • What Are Logical Operators In C++?
  • What Are Bitwise Operators In C++?
  • What Is Ternary/ Conditional Operator In C++?
  • Miscellaneous Operators In C++
  • Precedence & Associativity Of Operators In C++
  • Conclusion
  • Frequently Asked Questions
expand icon

Operators in C++ are essential basic components for carrying out manipulations and modifications on data in a C++ program. That is, they provide outcomes by performing operations on the input parameters, much like functions, and solving complex algorithms. There are multiple types of operators in C++ programming language, each with its own purpose. In this article, we discuss all these operators and how to use them with the help of symbols/ syntax and code examples.

What Is Operator In C++?

An operator in programming is a symbol (or a set of symbols) that designates a particular operation or action to be carried out on data. Programmers can execute mathematical calculations, value comparisons, value assignments, modifications and other operations by manipulating variables and values with operators.

  • Based on their usefulness, operators in programming languages may be divided into many categories.
  • For example, mathematical operators (such as addition, subtraction, multiplication, and division) that carry out arithmetic operations on the operands.
  • We also have comparison operators that help compare two or more operands, logical operators to perform logical operations/ logical comparisons, assignment operators that are used to assign values to variables, and more.

These different types of operators in C++ language help programmers develop clear, effective code that gives desired results by executing complicated operations on data. Programming in many languages, including C++, Python, Java, and others, requires a fundamental understanding of operators and the ability to use them effectively.

Types Of Operators In C++ With Examples

Operators are a key component of the C++ language that enable us to execute a variety of operations on data. Listed in the table below are the different types of operators most commonly used in C++ programs, along with their kinds.

Arithmetic Operators Addition (+): int result = 5 + 3; // result is 8
Subtraction (-): int result = 7 - 2; // result is 5
Multiplication (*): int result = 4 * 6; // result is 24
Division (/): float result = 10 / 3; // result is 3.333
Modulus (%): int result = 10 % 3; // result is 1
Relational Operators Equal to (==): bool result = (5 == 5); // result is true
Not equal to (!=): bool result = (6 != 3); // result is true
Greater than (>): bool result = (7 > 4); // result is true
Less than (<): bool result = (2 < 8); // result is true
Greater than or equal to (>=): bool result = (5 >= 5); // result is true
Less than or equal to (<=): bool result = (3 <= 4); // result is true
Logical Operators Logical AND (&&): bool result = (true && false); // result is false
Logical OR (||): bool result = (true || false); // result is true
Logical NOT (!): bool result = !true; // result is false
Assignment Operators Simple assignment (=): int x = 5;
Addition assignment (+=): int x = 5; x += 3; // x is now 8
Subtraction assignment (-=): int x = 5; x -= 2; // x is now 3
Multiplication assignment (*=): int x = 5; x *= 4; // x is now 20
Division assignment (/=): int x = 10; x /= 2; // x is now 5
Increment and Decrement Operators Increment (++): int x = 5; x++; // x is now 6
Decrement (--): int x = 5; x--; // x is now 4
Bitwise Operators

Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise Complement (~)
Bitwiese Left Shift(<<)
Bitwise Right Shift (>>)

You may execute a variety of actions on variables and values in your C++ programs by skillfully utilizing these operators. We will discuss these and a few other operators in C++ in the sections ahead.

What Are Arithmetic Operators In C++?

We use arithmetic operators in C++ to execute mathematical operations/ arithmetic manipulations on numerical quantities. These operations include addition, subtraction, multiplication, and division. 

Here is a table listing all the C++ arithmetic operators and their associated syntax:

Symbol

Operator Name

Syntax

+

Addition

result = operand1 + operand2;

-

Subtraction

result = operand1 - operand2;

*

Multiplication

result = operand1 * operand2;

/

Division

result = operand1 / operand2;

%

Modulus (Remainder)

result = operand1 % operand2;

Now, let's take a look at a simple C++ program that illustrates how to use these operators in action.

Code Example:

Output:

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1

Explanation:

In the simple C++ code above, we begin by including the <iostream> header file essential for the input/ output operations. 

  1. We then initiate the main() function, which is the program's entry point for execution.
  2. In main(), declare three variables, num1, num2, and result, all of integer data type. We also assign values 10 and 3 to variables num1 and num2, respectively.
  3. Then, we carry out various operations on these variables using arithmetic operators
    • First, we use the addition operator to calculate the total of num1 and num2.
    • Next, we calculate the difference between num1 and num2, which is 7, using the subtraction operator.
    • Then, we calculate the product of num1 and num2 (which is 30) using the multiplication operator.
    • After that, we use the division operator to carry out the division operation, yielding the value 3 as the result of dividing num1 by num2.
    • Lastly, we directly calculate the remainder when num1 is divided by num2 (which is 1), using the modulus operator (remainder).
  4. All the outcomes are stored in the result variable one by one and printed to the output console, side by side, using the cout command.
  5. Finally, the main() function successfully terminates with a return 0 statement.

What Are Assignment Operators In C++?

Table of assignment operators in C++ language with an example.

Variables can have values assigned to them using assignment operators. They let you carry out an action and save a value in a variable or change its current value concurrently. Depending on the activity they carry out, assignment operators can be further classified into several categories.

The many assignment operators available in C++ are shown in the following table:

Symbol

Operator Name

Syntax

=

Simple assignment

variable = expression

+=

Addition assignment

variable += expression

-=

Subtraction assignment

variable -= expression

*=

Multiplication assignment

variable *= expression

/=

Division assignment

variable /= expression

%=

Modulo assignment

variable %= expression

Let's examine some code to illustrate how assignment operators in C++ are used.

Code Example:

Output:

x += 3: 8
x -= 2: 6
x *= 4: 24
x /= 2: 12
x %= 3: 0

Explanation:

In the C++ code example-

  1. Inside the main() function, we declare an integer variable x and assign the value 5 to it using the basic assignment operator (=).
  2. Then, we use other assignment/ compound assignment operators to carry out various operations on this variable and assign the value back to the variable x.
  3. As mentioned in the code comments, we first use the addition assignment operator (+=) to add the right-hand operand/ value to the initial value of x (5) and assign the result back to x.
  4. We then use the cout command to print the value to the console. Note that at this point, the updated value of x is 8, so the next operation will be carried out on this value and not the initial value of x. 
  5. Then, we use the subtraction assignment operator (-=) to subtract the value on the right-hand side (2) from the current value of x (8). The updated value of x (6) is then printed to the console.
  6. After that, we use the multiplication assignment operator (*=) to multiply the value of x with the right-hand operand (4) and assign the updated value (24) back to x.
  7. Next, we use the division assignment operator (/=) and divide the value of x (24) by 2, then assign the updated value back to x (12).
  8. Lastly, we use the modulo assignment operator (%=) to find the remainder of the division of x by 3. This value is then assigned back to x (0), as shown in the output console.

What Are Relational Operators In C++?

Table of relational operators in C++ language with an example.

The relational operators are employed to assess the connection between two values by comparison. These operators return boolean values, that is, true or false, after they have carried out a relational comparison between the left operand and the right operand. The table below lists the various relational operators in C++ along with the corresponding syntax.

Symbol

Operator Name

Syntax

==

Equal to

operand1 == operand2

!=

Not equal to

operand1 != operand2

>

Greater than

operand1 > operand2

<

Less than

operand1 < operand2

>=

Greater than or equal to

operand1 >= operand2

<=

Less than or equal to

operand1 <= operand2

Now, let's look at an example showcasing the implementation of these relational operators in C++.

Code Example:

Output:

Result 1: 0
Result 2: 1
Result 3: 1
Result 4: 0
Result 5: 1
Result 6: 0

Explanation:

In the example C++ code above-

  1. We initialize two integer variables, x and y, with values 5 and 3 (respectively), inside the main() function.
  2. Then, we compare these values using various relational operators, and the outcomes are stored in boolean variables (result1 to result6).
    • Using the equal to relational operator (==), we check if x is equal to y, and the outcome is stored in result1. This turns out to be false because 5 is not equal to 3.
    • The outcome of not equal to relational operator (!=) is stored in variable result2, which is true because 5 is not equal to 3.
    • Next, we declare a variable result3 and use the greater than relational operator (>) to define it. Its value is true because 5 is greater than 3.
    • Then, using the less than relational operator (<), we define result4 which is false because 5 is not less than 3.
    • After that, we define result5 using the greater than or equal to relational operator (>=), and its value is true because 5 is greater than or equal to 3.
    • Next, we use the less than or equal to relational operator (<=) to get the value of result6, which is false because 5 is not less than or equal to 3.
  3. We then use a set of cout commands to display the values of all result variables along with a formatted string. 
  4. The program shows how to compare values and assess conditions in C++ using relational operators.

Also Read: 6 Relational Operators In C & Precedence Explained (+Examples)

What Are Logical Operators In C++?

Table of logical operators in C++ programming with examples.

C++ logical operators are utilized when working with boolean values (true or false). These operators let you combine many conditions and determine the truth value of each one using a truth table. The three types of logical operators in C++ are logical AND, logical OR, and logical NOT. The result of the logical operators is defined in the truth tables for each operator. They define how the outcome of the whole expression depends on the outcomes of the individual expressions on the left-hand side and the right-hand side. 

The table below shows the three logical operators in C++, along with the symbol and syntax. 

Symbol

Operator Name

Syntax

&&

Logical AND

condition1 && condition2

||

Logical OR

condition1 || condition2

!

Logical NOT

!condition

Let's take a code sample to show how logical operators are used in C++ programming language.

Code Example:

Output:

Condition 1: 1
Condition 2: 1
Condition 3: 0

Explanation:

  1. We begin the C++ example by initializing two integer variables, x and y, with values 5 and 10 (respectively) inside main().
  2. Next, we use logical operators to connect expressions that are made up of other operators and compare the values as stipulated. 
  3. We use the AND logical operator in the first operation, i.e., (x > 0) && (y < 20). It checks if x is greater than 0 and y is less than 20.
  4. If both the expressions return true (yes in this case), then the AND operation also returns true, represented by the value 1. The outcome is stored in the condition1 variable
  5. After that, we use the OR logical operator, which returns true even if one of the expressions is true. The second operation, i.e., (x == 5) || (y > 15) we determines if x equals 5 OR y exceeds 15.
  6. The result is stored in the condition2 variable, whose value is true (i.e., 1) since x is actually equal to 5, meaning at least one of the requirements is met.
  7. Next, we use the NOT logical operator, which inverses the value of the initial condition. Here, in the expression !(x > 0), we check if x is greater than 0, and the outcome of this logical operation will be the opposite.
  8. The initial condition (x>0) is true since x is bigger than 0 and 5 in number. The outcome of the logical NOT is stored in the condition3 variable, which is false, denoted by 0.
  9. Finally, we use a set of cout commands to print the outcome of each operation to the output console.

Learn More: Logical Operators In C++ | Use, Precedence & More (With Examples)

What Are Bitwise Operators In C++?

Table of bitwise operators in C++ programming with syntax example.

As the name suggests, the bitwise operators in C++ are used to modify the value of operands at the bit level. They compare, shift, or manipulate the bits of operand values and carry out required operations on the binary representation of the data values. 

The C++ bitwise operators are shown in the following table:

Symbol

Operator Name

Syntax

&

Bitwise AND operator

result = operand1 & operand2

|

Bitwise OR operator

result = operand1 | operand2

^

Bitwise XOR operator (exclusive OR)

result = operand1 ^ operand2

~

Bitwise NOT operator (complement)

result = ~operand

<<

Bitwise left shift operator

result = operand << n

>>

Bitwise right shift operator

result = operand >> n

Here is a sample code that shows how to use binary bitwise operators in C++.

Code Example:

Output:

Bitwise AND: 1
Bitwise OR: 7
Bitwise XOR: 6
Bitwise NOT: -6
Bitwise left shift: 20
Bitwise right shift: 1

Explanation:

In the C++ code example-

  1. Inside the main() function, we declare and initialize two integer variables, x and y, with values of 5 (binary equivalent 0101) and 3 (binary equivalent 0011), respectively. 
  2. We then use bitwise operators to carry out bitwise operations on these variables.
  3. First, we use the bitwise AND (&) to compare individual bits of the right and left operand values. The operator returns true if either both the bits are 1 or 0.
  4. The outcome of the operation, i.e., 0001 or integer 1, is stored in the result variable and printed to the console using the cout command.
  5. Next, we use the bitwise OR (|) to compare the bits of operands and return 1 even if either of the bits is 1 and 0 otherwise.
  6. The outcome of this operation is binary number 0111 with integer representation 7, which is stored in the result variable and printed to the console.
  7. After that, we use the bitwise XOR (^), which returns 1 only if the bits of the operands are different and 0 otherwise.
  8. The outcome of this operation is 0110, whose integer representation (6) is stored in the result variable and displayed in the output console.
  9. Then, we use the bitwise NOT (~), which reverses the bit values at every position and provides a complement.
  10. Because the two's complement representation of x is subjected to the bitwise NOT operation, the outcome is -6.
  11. Next, we use the bitwise Left Shift (<<), which shifts the bits of the operand by the specified number. Here, x is essentially increased by 2 to the power of the shift count (2). The outcome is 20.
  12. Lastly, we use bitwise Right Shift (>>) to move the bits of y one bit to the right. By doing this, y is divided by 2 increased to power of shift count (1). The outcome is 1.

Know More: Bitwise Operators In C++ Explained In Detail With Examples

What Is Ternary/ Conditional Operator In C++?

The breakdown of the syntax for the ternary operator in C++ language.

The ternary or conditional operator in C++ is a shorthand method for writing conditional control statements in a single line. It is denoted by the equation mark symbol followed by a colon (?:). The table below demonstrates the syntax of the ternary operator.

Symbol

Operator Name

Syntax

?:

Ternary conditional operator

condition ? expression1 : expression2

Here, the expression that evaluates to true or false is represented by the term condition. If the outcome of the condition expression is true, then expression1 is executed; otherwise, expression2 is carried out. Let's look at an example to see how the ternary operator is used.

Code Example:

Output:

Greater than 5

Explanation:

In the code example-

  1. We first initialize an integer variable num with the value of 10.
  2. Then, we define a string variable result using the ternary operator in C++. It is given a value where the initial condition is to check if num is greater than 5, i.e., num > 5.
  3. If the condition is satisfied, which it is in this instance, the result variable is assigned the value in expression, i.e., "Greater than 5".
  4. Otherwise, the expression, i.e., "Less than or equal to 5", is assigned if the criterion is false.
  5. In this case, the result reads "Greater than 5" because 10 is, in fact, greater than 5.

Also Read: Ternary (Conditional) Operator In C Explained With Code Examples

Miscellaneous Operators In C++

In addition to the usual types of operators in C++, some other commonly used operators fulfil special functions. This includes the sizeof() operator, comma operator, and pointer operator. Let us take a closer look at these operators.

What Is The Comma Operator In C++?

The C++ comma operator enables the sequential evaluation of several expressions. It can also be used as a separator when we are defining or initializing variables in a C++ program. The syntax and symbol for this operator are given in the table below.

Symbol

Description

Syntax

,

The comma operator works both as an operator and as a separator.

expr1, expr2

Code Example:

Output:

Result: 15
x: 6, y: 11, z: 16

Explanation:

  1. We first use the comma operator to initialize three variables, x, y, and x, with the values 5, 10, and 15, respectively.
  2. Then, we define another variable result and assign it the expression (x++, y++, z++). This evaluates each expression in order from left to right, separated by commas.
  3. The last expression's value, in this case, z++, determines the value of the entire expression.
  4. The value of z is increased by 1 following the evaluation of the equation. As a consequence, since z has a value of 16 following the increment operator, the outcome is 15.
  5. The values of x and y are likewise increased by 1, making them 6 and 11, respectively.
  6. We use the cout command to print these values, as shown in the output console.

Also Read: Comma Operator In C | Code Examples For Both Separator & Operator

What Is The Sizeof() Operator In C++?

In C++, the sizeof() operator is used to calculate the size in bytes, of a data type or variable. It gives the total amount of bytes that an item takes up, including its contents and any padding.  It can be used with any data type, including basic kinds, user-defined types, arrays, and structures. The syntax and description of the sizeof() operator are shown in the following table.

Operator

Description

Syntax

sizeof

Returns the size, in bytes, of a data type or object

sizeof(type) or sizeof object

Now, let's look at an example demonstrating the use of the sizeof() operator in C++.

Code Example:

Output:

Size of int: 4 bytes
Size of char: 1 byte
Size of double: 8 bytes
Size of number variable: 4 bytes
Size of character variable: 1 byte
Size of decimal variable: 8 bytes

Explanation:

In this example-

  1. We declare and initialize three variables: number (int type) with 10, character (char type) with A, and decimal (double type) with 3.14.
  2. Then, we use the sizeof operator inside the formatted string and cout commands to calculate and print the size in bytes of these variables.
  3. After that, we again use the sizeof operator to calculate the size of the data types instead of variables. The output shows that the size occupied by a variable is the size of the respective data type. 

Also Read: The Sizeof() Operator In C | A Detailed Explanation (+Examples)

The Pointer Operator In C++

To begin with, pointer variables are special variables that store the memory addresses of other variables. In other words, they point to the location of other variables. When working with these variables, we often need to use specific operators, termed pointer operators in C++. We can indirectly access and alter the data stored in a location by using pointer variables with these operators. There are two most commonly used pointer operators in C++:

  • The address-of operator (&): It provides access to a variable's memory location.
  • The dereference operator (*): It is used to access the value stored at a memory address that a pointer is pointing to.

The C++ pointer operators are summarized in the following table:

Operator

Description

Syntax

Address-of (&)

Returns the memory address of a variable

&variable

Dereference (*)

Accesses the value at a memory address

*pointer

Let's look at a code to demonstrate how to use these pointer operators in C++.

Code Example:

Output:

Value of number: 42
Memory address of number: 0x7ffee414e9d4 (address may vary)
Value pointed to by pointer: 42

Explanation:

  1. We declare an integer variable number and assign the value 42 to it in the main() function.
  2. Next, we define an integer pointer variable (i.e., int*) called pointer and use the address-of operator (&) to assign the memory location/ address of the variable number to it. 
  3. Then, we use the dereference operator (*) to access the value kept at the memory address pointed to the pointer variable.
  4. As a result, we indirectly access the value of the integer through the pointer by writing the *pointer in the third cout command.
  5. The value of the number, its memory location, and the value referred to by the pointer—which is the same as the value of the number—are all displayed in the output.
  6. This shows how to use pointer operators in C++ to work with pointers to access and modify data in an indirect manner.

Table showing the precedence of operators in C++ language.

Precedence & Associativity Of Operators In C++

The order in which operators are evaluated in an expression depends on their level of precedence in C++ language. Operators with higher precedence levels are evaluated before those with comparatively lower precedence. The evaluation order of operators with the same precedence is governed by their associativity, which can be either left-to-right or right-to-left.

Listed in the table below are the precedence and associativity levels of several popular operators in C++.

Operators In Descending Order Of Precedence

Associativity

() [] -> . (Highest precedence) 

Left-to-right


 

! ~ ++ -- + - * & sizeof

new delete

Multiplicative operators (* / %)

Additive operators (+ -)

Shift operators (<< >>)

Relational operators (< <= > >=)

Equality operators (== !=)

Bitwise AND (&)

Bitwise XOR (^)

Bitwise OR ()

Logical AND (&&)

Logical OR ()

Conditional operator (?:)

Assignment operators (= += -= *= /= %=)

Right-to-left

Comma operator (,)  (Lowest precedence)

Important note- It's vital to remember that parentheses can be used to impose the preferred evaluation order and override the default precedence.

Operators at the top of the table are given priority, while those at the bottom are given less priority. Look at the example below that illustrates a simple case of how operator precedence works in C++.

Code Example:

Output:

Result: 20

Explanation:

In the example above, we want to evaluate the equation 10 + 5 * 2.

  1. Note that the addition operator + is not evaluated until the multiplication operator * has been evaluated since it has higher precedence.
  2. So, the operation, 5 + 2, yields the number 10.
  3. The ultimate value of the result is 20 as a consequence of performing the addition operation using the multiplication result and the number 10.

Understanding what operators are and their precedence is essential for designing proper and predictable code, especially when expressions contain numerous operators. You may regulate the order of operations and ensure the necessary computations are done correctly.

Precedence Chart For Operators In C++

Here is a complete summary of the relative precedence of operators in the C++ language using an operator precedence chart:

Order Of Precedence:

  • () (Function call, grouping)
  • [] (Array subscript)
  • -> (Member selection through pointer)
  • . (Member selection)
  • ! (Logical NOT)
  • ~ (Bitwise NOT)
  • ++, -- (Post - increment, decrement)
  • ++, -- (Pre - increment, decrement)
  • +, - (Unary plus, minus)
  • * (Indirection, pointer)
  • & (Address-of, reference)
  • sizeof (Size of)
  • new, new[] (Dynamic memory allocation)
  • delete, delete[] (Dynamic memory deallocation)
  • Arithmetic operators
  • Shift operators
  • Relational & equality operators
  • Bitwise operators
  • Logical operators
  • Conditional operator
  • Assignment operators
  • The comma operator (lowest precedence)

 

Arithmetic Operators Precedence:

  • * (Multiplication)
  • / (Division)
  • % (Modulus)
  • + (Addition)
  • - (Subtraction)

Shift Operators Precedence:

  • << (Left shift)
  • >> (Right shift)

Relational and Equality Operators Precedence:

  • < (Less than)
  • <= (Less than or equal to)
  • > (Greater than)
  • >= (Greater than or equal to)
  • == (Equality)
  • != (Inequality)

Precedence in Bitwise Operators:

  • & (Bitwise AND)
  • ^ (Bitwise XOR)
  • | (Bitwise OR)

Logical Operators Precedence:

  • && (Logical AND)
  • || (Logical OR)

Assignment Operators Precedence:

  • = (Simple assignment operators)
  • +=, -=, *=, /=, %= (Compound assignment operators)

Conclusion

We have discussed all relevant operators in C++ in this article. This includes the different operator types, their functions, precedence rules, and typical use cases. It is extremely important to comprehend operators and their appropriate application to write clear and effective code. One must also understand the precedence of operators in C++ and their associativity so as to write expressions that meet the requirements. Programmers can create elegant solutions, optimize code, and create dependable software systems by mastering operators in C++.

Also Read: 51 C++ Interview Questions For Freshers & Experienced (With Answers)

Frequently Asked Questions

Q. What is a unary and binary operator in C++?

The operators in C++ can be classified into types based on the number of operands they work with. This means that we have binary and unary operators.

Unary Operator: An operator that only works with one operand is called a unary operator. It operates on the operand and then provides the outcome. Unary operators in C++ include:

  • Unary minus (-): Negates the value of the operand.
  • Unary plus (+): Represents the identity operation, indicating no change to the operand's value.
  • Increment (++): Increases the value of the operand by one.
  • Decrement (--): Decreases the value of the operand by one.
  • Logical NOT (!): Flips the logical value of the operand.

For example, the unary minus operator returns the negative value for the operand. (Note that the subtraction operator is a binary operator).

int number = 5;
int result = -number; // Unary minus operator applied to 'number'

Binary Operator: An operator that uses two operands is called a binary operator. That is, it operates on the two operands (left operand and right operand) and then returns a result. Binary operators in C++ contain examples like these:

  • Addition (+): Adds two operands together.
  • Subtraction (-): This operator subtracts the second operand from the first.
  • Multiplication (*): This operator multiplies two operands.
  • Division (/): This operator divides the first operand by the second.
  • Assignment (=): Assigns the value of the right operand to the left operand.

Let's look at an example for the addition operator where we have two integer values, and we want to calculate the sum. 

int a = 5;
int b = 3;
int result = a + b; // Binary addition operator applied to 'a' and 'b'

Understanding the differences between unary and binary operators in C++ aids in accurately building expressions and carrying out required actions.

Q. What is the operator formula?

The phrase 'operator formula' is not a widely accepted idea in arithmetics or programming. It appears to be a synthesis of the ideas of operators and formulae.

  • An operator in programming is a symbol that denotes an action to be taken on one or more operands. Data manipulation, computation, value comparison, and other tasks may all be accomplished with operators.
  • On the other hand, a formula is a mathematical phrase that determines a value using variables, constants, and operators. Mathematical operations like addition, subtraction, multiplication, and division are frequently paired with variables and constants to form formulas.

In programming, the classifications of operators inside formulae are used to carry out calculations and produce output. Think about the following formula using C++ operators, for instance:

int result = (a + b) * c / d;

The values of a and b are added together in this formula using the addition operator (+), and the result is then multiplied by the value of c. The outcome is then divided by the value of d using the division operator (/). The structure variable result receives the outcome as its value.

It's vital to remember that a formula's specific operators and their sequence inside the formula affect how operations are performed and the outcome. In conclusion, even if the phrase "operator formula" may not be well defined, programming languages allow you to do computations and change data using operators included within formulae.

Q. What are logical operators in C++?

Programmers utilize logical operators to conduct logical comparisons/ operations and assess the relationship between one or more expressions. With the help of these operators, we may mix and work with boolean values—true or false—to reach conclusions and manage program flow. There are three logical operators in C++:

  • Logical AND (&&): If both operands are true, the logical AND operator returns true; otherwise, it returns false. It is represented by the double ampersand symbol (&&).
  • Logical OR (||): If at least one of the operands is true, the logical OR operator returns true; otherwise, it returns false. It is represented by the double pipe symbol (||).
  • Logical NOT (!): It is a unary operator that negates the value of the single operand. The NOT operator returns false if the operand is true and returns true if the operand is false. It is recognizable by the exclamation symbol (!).

These logical operators are often used in loops, boolean expressions, and conditional statements to control the execution flow based on specific situations. Below is an example illustrating how to use logical operators in C++.

Code Example:

Output:

Condition 1: true
Condition 2: false

Q. What is operator overloading in C++?

The ability to apply the same operator with many types of operations on operands, including user-defined types, is known as operator overloading in the C++ programming language. It gives programmers the ability to change how an operator behaves when used with different kinds of data or objects.

  • An operator's custom implementation, defining how it should act when applied to your user-defined types or existing kinds, can be provided by overloading the operator.
  • Through this, you may effortlessly integrate your own classes with the functionality of a combination of operators.
  • The arithmetic operators (+, -, *, and /), comparison operators (==,!=,, >, =, and >=), assignment operators (=), and more can all be overloaded in C++.
  • You construct a custom function known as an operator function or an overloaded operator function to overload an operator.
  • When an operator is used with objects belonging to the specified class, the associated operator's associated function is called.

Look at the example below, which illustrates operator overloading in a user-defined class named Vector for the addition operator (+).

Code Example:

Output:

Vector(6, 8)

Explanation:

The operator + method is used by the Vector class in the code above to overload the addition operator (+).

  1. The right-side single operand of the addition is represented by the const Vector& argument that is sent to this function.
  2. The matching member variables (x and y) are added within the function, and a new Vector object is created with the total of the values.
  3. Two Vector objects can be added to create a new Vector object that reflects the total of their individual components thanks to the overloaded built-in operator.

This compiles the discussion on operators in C++. Here are some other articles you might be interested in reading:

  1. Storage Classes In C++ & Its Types Explained (With Examples)
  2. New Operator In C++ | Syntax, Usage, Working & More (With Examples)
  3. C++ Function | A Comprehensive Guide (With Code Examples)
  4. OOPs Concept In C++ | A Detailed Guide With Codes & Explanations
  5. Typedef In C++ | Syntax, Application & How To Use (+Code Examples)
Edited by
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

Tags:
Computer Science Engineering C++ Programming Language

Comments

Add comment
No comments Image No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.