Operators In C++

Topic asked in December 2022 (CBCS) and July 2022 (CBCS) question paper.

Operators are symbols that perform specific mathematical or logical operations on operands. Consider the expression 2 + 3 = 5, here 2 and 3 are operands and + is called operator.

Types Of Operators

  • Unary operator
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operator
  • Ternary or Conditional Operator

Unary Operators

Unary operators are operators which are used to calculate the result on only one operand. Unary operators are used on a single operand in order to calculate the new value of that variable. Unary operators can be used either in the prefix position or the postfix position of the operand.

Types of Unary Operators

  1. Unary Plus (+) - This Unary Operator is denoted by the + sign and it does not make any difference to the value of the operand. It is just used to denote that the operand is of a positive value.

    #include <iostream>
    using namespace std;
     
    int main()
    {
        cout<<"Unary Plus (+) Operator"<<endl;
        int y = +10;   //Unary Plus (+) Operator
        cout<<"Value of y is: " <<y;
     
        return 0;
    }

    Output:-

    Unary Plus (+) Operator
    Value of y is: 10
  2. Unary Minus (-) - The - sign is used in this Unary Operator type and its main function is that it changes the sign value of the operand. It has the function of converting a positive value to a negative value and vice versa.

    #include <iostream>
    using namespace std;
     
    int main()
    {
        cout<<"Unary Minus (-) Operator"<<endl;
        int x = 10;
        x = -x;      //Unary Minus (-) Operator
        cout<<"Value of x is: "<<x<<endl;
     
        return 0;
    }

    Output:-

    Unary Minus (-) Operator
    Value of x is: -10
  3. sizeof() - sizeof Unary Operator is used to return the size of the operand, in bytes. For example, in C++, the int data type is of the size 4 bytes. This value will be returned by the sizeof operator. The sizeof() operator is used as a function in the program.

    #include <iostream>
    using namespace std;
     
    int main()
    {
        cout<<"sizeof Operator"<<endl;
        int a = 7;
        double b = 5;
     
        cout<<"Size of a and b is: "<<sizeof(a)<<" "<<sizeof(b)<<endl;
     
        return 0;
    }

    Output:-

    sizeof Operator
    Size of a and b is: 4 8
  4. Addressof Operator (&) - In this type, the operator returns the address of the variable stored in the memory location. It returns the address value of the memory location where the variable is stored.

     #include <iostream>
     using namespace std;
     
     int main()
     {
        cout<<"\nAddressof Operator (&)"<<endl;
        int z;
        int *ptr;
     
        ptr = &z;
        cout<<"Address of z is: "<<ptr<<endl;
     
        return 0;
     }

    Output:-

    Addressof Operator (&)
    Address of z is: 0x7fff5b1f924c
  5. Indirection Operator (*) - This type of operator returns the value stored in the memory location by pointing it to the memory location of the variable.

    #include <iostream>
    using namespace std;
     
    int main()
    {
        cout<<"Indirection Operator (*)"<<endl;
        int count = 9;
        int *p = &count;
     
        cout<<"Value of *p is: "<<*p<<endl;
     
        return 0;
    }

    Output:-

    Indirection Operator (*)
    Value of *p is: 9

Unary Increment (++)

Topic asked in February 2022 (CBCS) question paper.

Increment Operator is used to increase the value of the operand by 1. They are used only with Integer Variables and Operands having Numerical values. They cannot be used with a Variable containing the values of a Character or String.

They can be used in both the Prefix and the Postfix position of the operand. The Position used by the Increment Operator in the program statement decides how the operator will function.

If the Increment Operators are being used in the Prefix position, then, the Increment function will be done before the evaluation of the expression. If the Increment Operators are being used in the Postfix position, then, the Increment function will be done after the evaluation of the expression.

Example:-

#include <iostream>
using namespace std;
 
int main()
{
   int x =  10 ;
   int a ;
   x = ++x ;  //Pre-Increment (Prefix Position)
 
   cout <<"Value of x = "<< x << endl ;
 
   a = x++ ;  //Post-Increment (Postfix Position)
 
   cout <<"Value of a = "<< a << endl ;
   cout <<"New Value of x = "<< x << endl ;
 
   return 0;
}

Output:-

Value of x = 11
Value of a = 11
New Value of x = 12

Explanation:- In our First cout statement, the Pre-Increment Operator is used. Thus, the value of x is incremented by 1 i.e., x = x + 1 = 10 + 1 = 11

Then we assign value to the variable a in the expression a = x++. Here, Post-Increment Operator is used.

This means that First the value of x will be assigned to a and then x will be incremented by 1. Hence the Output a = 11, new value of x = 12

Unary Decrement (--)

Topic asked in February 2022 (CBCS) question paper.

The main function of the Decrement Operator is to decrease the numerical count of the variable by a value of 1. They are also used only with Integer Variables and Operands having Numerical values and cannot be used with a Variable containing the values of a Character or String.

They are also used in both the Prefix and the Postfix position of the operand. The Position used by the Decrement Operator in the program statement decides how the operator will function.

If the Decrement Operator is being used in the Prefix position, then, the Decrement function will be done before the the evaluation of the expression. If the Decrement Operator is being used in the Postfix position, then, the Decrement function will be done after the evaluation of the expression.

Example:-

#include <iostream>
using namespace std;
 
int main()
{
 
   int x = 10;
   int a;
 
   cout <<"Value of x = "<< --x << endl ;  //Pre-Decrement (Prefix Position)
 
   a = x--  ;  //Post-Decrement (Postfix Position)
 
   cout <<"Value of a = "<< a << endl ;
   cout <<"New Value of x = "<< x << endl ;
 
   return 0;
 
}

Output:-

Value of x = 9
Value of a = 9
New Value of x = 8

Explanation:- In our First cout statement, the Pre-Decrement Operator is used. Thus, the value of x will be decremented by 1 i.e., x = x - 1 = 10 - 1 = 9

Then we assign value to the variable a in the expression a = x--. Here, Post-Decrement Operator is used.

This means that First the value of x will be assigned to a and then x will be decremented by 1. Hence the Output a = 9, new value of x = 8

The Postfix Operator position has a higher precedence level than the Prefix Operator position. Postfix Operators are evaluated from left-to-right associativity and the Prefix Operators are evaluated from right-to-left associativity.

Arithmetic Operators

Topic asked in July 2022 (CBCS) question paper.

In C++, Arithmetic Operators are symbols used to perform common arithmetic operations like addition, subtraction, multiplication, division, modulus, etc. They are used within the equation to perform a number of basic mathematical calculations.

Types Of Arithmetic Operators

Arithmetic Operators use two operands and an operator between them in order to calculate the result

OperatorOperation
+Addition
-Subtraction
*Multiplication
/Division
%Modulo Operation (Remainder After Division)

Arithmetic Operator example:-

#include <iostream>
using namespace std;
 
int main() {
    int a, b;
    a = 7;
    b = 5;
 
    // printing the sum of a and b
    cout << "a + b = " << (a + b) << endl;
 
    // printing the difference of a and b
    cout << "a - b = " << (a - b) << endl;
 
    // printing the product of a and b
    cout << "a * b = " << (a * b) << endl;
 
    // printing the division of a by b
    cout << "a / b = " << (a / b) << endl;
 
    // printing the modulo of a by b
    cout << "a % b = " << (a % b) << endl;
 
    return 0;
}

Output:-

a + b = 12
a - b = 2
a * b = 35
a / b = 1
a % b = 2

Note: The % operator can only be used with integers.

Relational Operators

These operators are used for the comparison of the values of two operands. For example, '>' checks if one operand is greater than the other operand or not, etc. The result returns a Boolean value, i.e., true or false.

Types Of Relational Operators

OperatorMeaningExample
==Is Equal To7 == 9 gives us false
!=Not Equal To7 != 9 gives us true
>Greater Than7 > 9 gives us false
<Less Than7 < 9 gives us true
>=Greater Than or Equal To7 >= 9 gives us false
<=Less Than or Equal To7 <= 9 gives us true

Relational Operator example:-

#include <iostream>
using namespace std;
 
int main() {
    int a, b;
    a = 7;
    b = 9;
    bool result;
 
    result = (a == b);   // false
    cout << "7 == 9 is " << result << endl;
 
    result = (a != b);  // true
    cout << "7 != 9 is " << result << endl;
 
    result = a > b;   // false
    cout << "7 > 9 is " << result << endl;
 
    result = a < b;   // true
    cout << "7 < 9 is " << result << endl;
 
    result = a >= b;  // false
    cout << "7 >= 9 is " << result << endl;
 
    result = a <= b;  // true
    cout << "7 <= 9 is " << result << endl;
 
    return 0;
}

Output:-

7 == 9 is 0
7 != 9 is 1
7 > 9 is 0
7 < 9 is 1
7 >= 9 is 0
7 <= 9 is 1

Note: Relational operators are used in decision-making and loops.

Logical Operators

Topic asked in July 2022 (CBCS) question paper.

Logical operators are used to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0.

Types Of Logical Operators

OperatorMeaningExample
&&Logical AND. True only if all operands are true.expression1 && expression2
||Logical OR. True if at least one operand is true.expression1 || expression2
!Logical NOT. True only if the operand is false.!expression

Logical Operator example:-

#include <iostream>
using namespace std;
 
int main() {
    bool result;
 
    //Logical AND (&&)
    result = (7 != 9) && (7 < 9);     // true
    cout << "(7 != 9) && (7 < 9) is " << result << endl;
 
    result = (7 == 9) && (7 < 9);    // false
    cout << "(7 == 9) && (7 < 9) is " << result << endl;
 
    result = (7 == 9) && (7 > 9);    // false
    cout << "(7 == 9) && (7 > 9) is " << result << endl;
 
    //Logical OR (||)
    result = (7 != 9) || (7 < 9);    // true
    cout << "(7 != 9) || (7 < 9) is " << result << endl;
 
    result = (7 != 9) || (7 > 9);    // true
    cout << "(7 != 9) || (7 > 9) is " << result << endl;
 
    result = (7 == 9) || (7 > 9);    // false
    cout << "(7 == 9) || (7 > 9) is " << result << endl;
 
    //Logical NOT (!)
    result = !(9 == 2);    // true
    cout << "!(9 == 2) is " << result << endl;
 
    result = !(9 == 9);    // false
    cout << "!(9 == 9) is " << result << endl;
 
    return 0;
}

Output:-

(7 != 9) && (7 < 9) is 1
(7 == 9) && (7 < 9) is 0
(7 == 9) && (7 > 9) is 0
(7 != 9) || (7 < 9) is 1
(7 != 9) || (7 > 9) is 1
(7 == 9) || (7 > 9) is 0
!(9 == 2) is 1
!(9 == 9) is 0

Explanation:-

Logical AND (&&)

  • (7 != 9) && (7 < 9) evaluates to 1 because both operands (7 != 9) and (7 < 9) are 1 (true).
  • (7 == 9) && (7 < 9) evaluates to 0 because the operand (7 == 9) is 0 (false).
  • (7 == 9) && (7 > 9) evaluates to 0 because both operands (7 == 9) and (7 > 9) are 0 (false).

Logical OR (||)

  • (7 != 9) || (7 < 9) evaluates to 1 because both operands (7 != 9) and (7 < 9) are 1 (true).
  • (7 != 9) || (7 > 9) evaluates to 1 because the operand (7 != 9) is 1 (true).
  • (7 == 9) || (7 > 9) evaluates to 0 because both operands (7 == 9) and (7 > 9) are 0 (false).

Logical NOT (!)

  • !(9 == 2) evaluates to 1 because the operand (9 == 2) is 0 (false).
  • !(9 == 9) evaluates to 0 because the operand (9 == 9) is 1 (true).

Assignment Operator

In C++, assignment operators are used to assign values to variables.

Types Of Assignment Operators

OperatorExampleEquivalent to
=a = ba = b
+=a += ba = a + b
-=a -= ba = a - b
*=a *= ba = a * b
/=a /= ba = a / b
%=a %= ba = a % b
Simple Assignment Operator

Here, = is also called Simple-assignment operator and assigns its right operand to its left operand. In easy terms, this operator is used to assign the value on the right to the variable on the left.

Example:-

#include <iostream>
using namespace std;
 
int main() {
    int a, b;
 
    // 5 is assigned to a
    a = 5;
 
    // 9 is assigned to b
    b = 9;
 
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
 
    return 0;
}

Output:-

a = 5
b = 9
Shorthand Assignment Operator

Here, +=, -=, *=, /=, %= are also called Shorthand Assignment Operators and they combines one of the arithmetic or bitwise operators with the assignment operator. They are also called as compound assignment operators. A Shorthand Assignment Operator is a shorter way of expressing something that is already available in the programming statements.

Example:-

#include <iostream>
using namespace std;
 
int main() {
    int a = 5;
    int b = 10;
 
    // Shorthand assignment operators
 
    a += b;  // equivalent to a = a + b;
    cout << "a += b: " << a << endl;
 
    a -= b;  // equivalent to a = a - b;
    cout << "a -= b: " << a << endl;
 
    a *= 2;  // equivalent to a = a * 2;
    cout << "a *= 2: " << a << endl;
 
    a /= 2;  // equivalent to a = a / 2;
    cout << "a /= 2: " << a << endl;
 
    a %= 3;  // equivalent to a = a % 3;
    cout << "a %= 3: " << a << endl;
 
    return 0;
}

Output:-

a += b: 15
a -= b: 5
a *= 2: 10
a /= 2: 5
a %= 3: 2

Assignment Statement

An Assignment statement is a statement that is used to set a value to the variable name in a program. The symbol used in an assignment statement is = and is called assignment operator.

Note: The Assignment Operator = should not be confused with == which is relational operator and is used for equality purpose.

The Basic Syntax of Assignment Statement in C++ is :

variable = expression;

where,

  • variable = variable name
  • expression = it could be either a direct value or a math expression/formula or a function call

For example:-

int a = 10;
float b;
b = 22.3;

In the above-given example, Variable 'a' is assigned a value in the same statement as per its defined data type. A data type is only declared for Variable 'b'. The 3rd line of code assigns the value for Variable 'b'.

Assignment Statement Forms
  1. Basic Form - This is one of the most common forms of Assignment Statements. Here the Variable name is defined, initialized, and assigned a value in the same statement. This form is generally used when we want to use the Variable quite a few times and we do not want to change its value very frequently.

    int rollNo = 51;
    cout<<rollNo;  //Prints 51
  2. Tuple Assignment - Generally, we use this form when we want to define and assign values for more than 1 variable at the same time. This saves time and is an easy method. Note that here every individual variable has a different value assigned to it.

    int a = 7, b = 9;
    cout<<a<<" ";
    cout<<b; //Prints 7 9
  3. Sequence Assignment or Chain Assignment - In this format, a single value is assigned to two or more variables.

    int a,b;
    a = b = 4;
    cout<<a<<" ";
    cout<<b; //Prints 4 4
  4. Augmented Assignment - In this format, we use the combination of mathematical expressions and values for the Variable. Other augmented Assignment forms are: &=, -=, **=, etc.

    int speed = 40;
    speed+=10;
    cout<<speed; //Prints 50

Bitwise Operators

In C++, bitwise operators are used to perform operations on individual bits. The operators are first converted to bit-level and then the calculation is performed on the operands.

Types Of Bitwise Operators

OperatorName
&Bitwise AND Operator
|Bitwise OR Operator
^Bitwise XOR Operator
~Bitwise Complement Operator
<<Bitwise Left Shift Operator
>>Bitwise Right Shift Operator

1. Bitwise AND Operator - The bitwise AND & operator returns 1 if and only if both the operands are 1. Otherwise, it returns 0.

The following table demonstrates the working of the bitwise AND operator. Let a and b be two operands that can only take binary values i.e. 1 and 0.

aba & b
000
010
100
111

Let's take a look at the bitwise AND operation of two integers 12 and 25:

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

//Bitwise AND Operation of 12 and 25

     00001100
&    00011001
     _________
     00001000  = 8 (In decimal)

Example Program:-

#include <iostream>
using namespace std;
 
int main() {
    // declare variables
    int a = 12, b = 25;
 
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "a & b = " << (a & b) << endl;  //Bitwise AND Operation
 
    return 0;
}

Output:-

a = 12
b = 25
a & b = 8

2. Bitwise OR Operator - The bitwise OR | operator returns 1 if at least one of the operands is 1. Otherwise, it returns 0.

The following truth table demonstrates the working of the bitwise OR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0.

aba | b
000
011
101
111

Let us look at the bitwise OR operation of two integers 12 and 25:

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25
    00001100
|   00011001
    _________
    00011101  = 29 (In decimal)

Example Program:-

#include <iostream>
using namespace std;
 
int main() {
    int a = 12, b = 25;
 
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "a | b = " << (a | b) << endl;
 
    return 0;
}

Output:-

a = 12
b = 25
a | b = 29

3. Bitwise XOR Operator - The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1. However, if both the operands are 0, or if both are 1, then the result is 0.

The following truth table demonstrates the working of the bitwise XOR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0.

aba ^ b
000
011
101
110

Let us look at the bitwise XOR operation of two integers 12 and 25:

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25
    00001100
^   00011001
    _________
    00010101  = 21 (In decimal)

Example Program:-

#include <iostream>
using namespace std;
 
int main() {
    int a = 12, b = 25;
 
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "a ^ b = " << (a ^ b) << endl;
 
    return 0;
}

Output:-

a = 12
b = 25
a ^ b = 21

4. Bitwise Complement Operator - The bitwise complement operator is a unary operator (works on only one operand). It is denoted by ~ that changes binary digits 1 to 0 and 0 to 1.

Bitwise Complement

It is important to note that the bitwise complement of any integer N is equal to -(N + 1). For example,

Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36. Now, let's see if we get the correct answer or not.

35 = 00100011 (In Binary)

// Using bitwise complement operator
~ 00100011
 __________
  11011100

In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here, if we convert the result into decimal we get 220.

However, it is important to note that we cannot directly convert the result into decimal and get the desired output. This is because the binary result 11011100 is also equivalent to -36.

To understand this we first need to calculate the binary output of -36. We use 2's complement to calculate the binary of negative integers.

2's Complement

The 2's complement of a number N gives -N.

In binary arithmetic, 1's complement changes 0 to 1 and 1 to 0.

And, if we add 1 to the result of the 1's complement, we get the 2's complement of the original number.

For example,

36 = 00100100 (In Binary)
 
1's Complement = 11011011
 
2's Complement :
11011011
 +     1
_________
11011100

Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the bitwise complement of 35 that we have calculated in the previous section.

Hence, we can say that the bitwise complement of 35 = -36.

Example Program:-

#include <iostream>
using namespace std;
 
int main() {
    int num1 = 35;
    int num2 = -150;
    cout << "~(" << num1 << ") = " << (~num1) << endl;
    cout << "~(" << num2 << ") = " << (~num2) << endl;
 
    return 0;
}

Output:-

~(35) = -36
~(-150) = 149

In the above example, we declared two integer variables num1 and num2, and initialized them with the values of 35 and -150 respectively.

We then computed their bitwise complement with the codes (~num1) and (~num2) respectively and displayed them on the screen.

The bitwise complement of 35 = - (35 + 1) = -36
i.e. ~35 = -36

The bitwise complement of -150 = - (-150 + 1) = - (-149) = 149
i.e. ~(-150) = 149

This is exactly what we got in the output.

5. C++ Right Shift Operator - The right shift operator shifts all bits towards the right by a certain number of specified bits. It is denoted by >>.

When we shift any number to the right, the least significant bits are discarded, while the most significant bits are replaced by zeroes.

Right Shift

As we can see from the image above, we have a 4-bit number. When we perform a one-bit right shift operation on it, each individual bit is shifted to the right by 1 bit.

As a result, the right-most bit is discarded, while the left-most bit remains vacant. This vacancy is replaced by a 0.

6. C++ Left Shift Operator - The left shift operator shifts all bits towards the left by a certain number of specified bits. It is denoted by <<.

Left Shift

As we can see from the image above, we have a 4-bit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.

As a result, the left-most bit is discarded, while the right-most bit remains vacant. This vacancy is replaced by a 0.

Example Program:-

#include <iostream>
using namespace std;
 
int main() {
 
    // declaring two integer variables
    int num = 212, i;
 
    // Shift Right Operation
    cout << "Shift Right:" << endl;
 
    // Using for loop for shifting num right from 0 bit to 3 bits
    for (i = 0; i < 4; i++) {
        cout << "212 >> " << i << " = " << (212 >> i) << endl;
    }
 
    // Shift Left Operation
    cout << "\nShift Left:" << endl;
 
    // Using for loop for shifting num left from 0 bit to 3 bits
    for (i = 0; i < 4; i++) {
        cout << "212 << " << i << " = " << (212 << i) << endl;
    }
 
    return 0;
}

Output:-

Shift Right:
212 >> 0 = 212
212 >> 1 = 106
212 >> 2 = 53
212 >> 3 = 26

Shift Left:
212 << 0 = 212
212 << 1 = 424
212 << 2 = 848
212 << 3 = 1696

From the output of the program above, we can infer that, for any number N, the results of the shift right operator are:

N >> 0 = N
N >> 1 = (N >> 0) / 2
N >> 2 = (N >> 1) / 2
N >> 3 = (N >> 2) / 2
and so on.

Similarly, the results of the shift left operator are:

N << 0 = N
N << 1 = (N << 0) * 2
N << 2 = (N << 1) * 2
N << 3 = (N << 2) * 2
and so on.

Hence we can conclude that,

N >> m = [ N >> (m-1) ] / 2
N << m = [ N << (m-1) ] * 2

Ternary or Conditional Operators

The conditional operator (also known as the ternary operator) in C++ is a shorthand way of writing an if-else statement. It allows you to evaluate a condition and return one value if the condition is true and another value if the condition is false.

The syntax of the conditional operator is:-

condition ? Expression 1 : Expression 2

The ternary operator ? determines the answer on the basis of the evaluation of condition. If it is true, then Expression 1 gets evaluated and is used as the answer for the expression. If condition is false, then Expression 2 gets evaluated and is used as the answer for the expression.

This operator takes three operands, therefore it is known as a Ternary Operator.

Ternary Operator Example

#include <iostream>
using namespace std;
 
int main()
{
    int a = 7, b = 9;
 
    // Conditional Operator
    int result = (a < b) ? b : a;
    cout << "The greatest number is " << result << endl;
 
    return 0;
}

Output:-

The greatest number is 9

Precedence of Operators

The precedence of operators in C++ determines the order in which operators are evaluated within an expression. Operators with higher precedence are evaluated before operators with lower precedence. If operators have the same precedence, the associativity of the operators comes into play, determining the order of evaluation.

Here, higher the category in table higher the precedence.

CategoryOperatorAssociativity
Postfix() [] . ->Left to Right
Unary++ -- + - ! ~ * & sizeofRight to Left
Multiplicative* / %Left to Right
Additive+ -Left to Right
Shift<< >>Left to Right
Relational< <= > >=Left to Right
Equality== !=Left to Right
Bitwise AND&Left to Right
Bitwise XOR^Left to Right
Bitwise OR|Left to Right
Logical AND&&Left to Right
Logical OR||Left to Right
Conditional? :Right to Left
Assignment= += -= *= /= %= &= ^= |= <<= >>=Right to Left
Comma,Left to Right

Examples:-

Example Program 1

#include <iostream>
using namespace std;
 
int main()
{
// declare variables
int a = 10, b = 22, c = 2, x;
// expression
x = a + b / c;
// display result
cout<<"The result of the expression is = "<<x;
 
return 0;
}

Output:-

The result of the expression is = 21

Explanation: In the expression x = a + b / c, the division operation b / c is performed before the addition operation a + .... Therefore, b / c is evaluated as 11, and then a + 11 results in 21, not 16.

Example Program 2

#include<iostream>
using namespace std;
 
int main()
{
// declare variables
int a = 10, b = 22, c = 2, x;
// expression
x = ( a + b ) / c;
// display result
cout<<"The result of the expression is = "<<x;
 
return 0;
}

Output:-

The result of the expression is = 16

Explanation: In the code, the expression (a + b) / c is evaluated. According to the operator precedence rules in C++, parentheses () have the highest precedence. Therefore, a + b is first evaluated inside the parentheses to give 32, and then 32 is divided by 2, resulting in 16. Hence, the output is 16.

Example Program 3

#include <iostream>
using namespace std;
 
int main()
{
// declare variables
int a = 10, b=22, c=2, x;
// expression
x = a == b != c;
// display result
cout<<"The result of the first expression is = "<< x <<endl;
x = a == ( b != c );
cout<<"The result of the second expression is = "<<x <<endl;
 
return 0;
}

Output:-

The result of the first expression is = 1
The result of the second expression is = 0

Explanation: As in the above code the first expression operators == and != have the same precedence and the associativity is left to right so first == and then != operator performed. And in the second expression first != (due to ( )) and then == operator performed. So first expression is solve as:

  • x = a == b != c
  • x = 10 == 22 != 2
  • x=0 != 2
  • x=1

And second expression is solve as -

  • x = a == (b != c)
  • x = 10 == (22 != 2)
  • x=10 == 1
  • x=0

Example Program 4

#include <iostream>
using namespace std;
 
int main()
{
// declare variables
int a = 10, b=22, c=2, x;
// expression
x = a > b > c;
// display result
cout<<"The result of the first expression is = "<< x <<endl;
x = a < b < c;
cout<<"The result of the second expression is = "<<x <<endl;
 
return 0;
}

Output:-

The result of the first expression is = 0
The result of the second expression is = 1

Explanation: As in the above code, the first expression contains > operator whose associativity is left to right. Therefore the expression becomes ((a > b) > c), which becomes ((0) > 2) as (10 is not greater than 22 so it returns 0 and 0 is not greater than 2) , so output is 0. And the second expression contains <operator whose associativity is also left to right. Therefore the expression becomes ((a < b) < c) , which becomes ((1) < 2) as (10 is greater than 22 and 1 is less than 2) , so output is 1.

Comments In C++

In C++, comments are used to temporarily disable certain lines of code.

  1. Single-line comments: These comments begin with "//" and continue until the end of the line.
// This is a single-line comment
int x = 5; // This comment is at the end of the line
  1. Multi-line comments: These comments start with /* and end with */. They can span multiple lines.
/* This is a
   multi-line comment */
int y = 10;

Single-line comments are generally preferred for short comments and commenting out single lines, while multi-line comments are useful for longer comments or commenting out blocks of code.

How's article quality?

Last updated on -

Page Contents