Category: C++ Operators

https://zain.sweetdishy.com/wp-content/uploads/2026/02/C-Operators-.png

  • Scope Resolution Operator in C++

    In C++, scope resolution operator is used to define a function outside the class and access the static variables of a class. It accesses the identifiers such as classes and functions and is denoted by double colon (::).

    Here is the syntax of a scope resolution operator −

    scope_name :: identifier
    

    Here,

    • scope − It can be a class name, namespace, or, global.
    • identifier − The identifier can be a variable, function, type, or, constant.

    Read this chapter to get a better understanding of various applications of scope resolution operator.

    Application of Scope Resolution Operator

    The scope resolution operator is used for multiple purposes that are mentioned below −

    namespace Resolution

    namespace is used to differentiate similar functions, classes, variables, etc., with the same name available in different libraries. To access members which are defined inside a namespace, we use the scope resolution operator ‘::’.

    In this example, we have used the scope resolution operator with cout to print the message.

    #include <iostream>intmain(){
       std::cout <<"This message is printed using std::"<< std::endl;}

    The output of the above code is as follows:

    This message is printed using std::
    

    Defining a Function Outside Class

    To define a function outside the class, we use the scope resolution operator. It is used to differentiate a global function from a function that belongs to a class. Here is an example −

    In this example, we have declared a function display in the class Example. To define this function outside the class, we have used the scope resolution operator. This function displays the value of the num.

    #include <iostream>usingnamespace std;classExample{int num =10;public:voiddisplay();};voidExample::display()// Defining Function outside class{
       cout <<"The value of num is: "<< num;}intmain(){
       Example obj;
       obj.display();return0;}

    The output of the above code is as follows −

    The value of num is: 10
    

    Accessing Global Variable

    To access a global variable that is already locally present in a function, we use the scope resolution operator with the global variable.

    The following example prints the value stored inside the variable num. The ‘num’ variable is used as local as well as a global variable, and we have used the scope resolution operator to access the global variable.

    #include<iostream>usingnamespace std;int num =7;intmain(){int num =3;
       cout <<"Value of local variable num is: "<< num;
       cout <<"\nValue of global variable num is: "<<::num;return0;}

    The output of the above code is as follows −

    Value of local variable num is: 3
    Value of global variable num is: 7
    

    Accessing static Member Variables

    To access or define a static member variable, we use a scope resolution operator. The static members belongs to class and are object-independent so they must be defined outside the class. They can be accessed using a class name with the help of the scope resolution operator.

    Here is an example to define and access the static member variable name. We have used a class with a scope resolution operator to access the static variable −

    #include <iostream>usingnamespace std;classCompany{public:static string name;//Declaring static variable};
    
    string Company::name ="Tutorials Point";//Defining static variableintmain(){//Accessing static variable using Scope Resolution Operator 
       cout <<"Welcome to "<< Company::name << endl;return0;}

    The output of the above code is as follows −

    Welcome to Tutorials Point
    

    Iterator Declaration

    An iterator in C++ is used with container like vectorlistmap etc. to traverse, access, and modify the container elements. To declare an iterator, we must use the scope resolution operator (::) with the container name.

    In this example, we have used an iterator it to traverse and print the vector elements using (::).

    #include <iostream>#include <vector>usingnamespace std;intmain(){
    
         vector<int> numbers ={10,20,30,40,50};// Declaring iterator using scope resolution operator
         vector<int>::iterator it;
    
         cout <<"Given vector: ";for(it = numbers.begin(); it != numbers.end();++it){
            cout <<*it <<" ";}return0;}

    The output of the above code is as follows −

    Given vector: 10 20 30 40 50
    

    Calling Parent Class Function in Overriding

    The function overriding allows a derived or child class to redefine a function that is already defined in the base or parent class. We use the scope resolution operator when we want to access the function of the parent class that is also present in the child class using the child class object.

    In this example, we have used the child object to print the output of the parent class function using the scope resolution operator.

    #include <iostream>usingnamespace std;classParent{public:voidshow(){
            cout <<"This is Parent class show() function"<< endl;}};classChild:public Parent{public:voidshow(){
            cout <<"This is Child class show() function"<< endl;}};intmain(){
        Child child1;
        child1.show();
        child1.Parent::show();// Calling parent class function using ::}

    The output of the above code is as follows −

    This is Child class show() function
    This is Parent class show() function
    

    Demonstrating Inheritance

    The scope resolution operator helps you to access base class members from a derived class in inheritance. You can use scope resolution operator in single and multiple inheritance but it serves different purposes in both conditions. The following examples explain different uses of scope resolution operator in single and multiple inheritance:

    Example: Single Inheritance

    In this example, we have used the scope resolution operator to access the base class function display() from the derived class.

    #include <iostream>usingnamespace std;classBase{public:voiddisplay(){
              cout <<"Base class function called"<< endl;}};classDerived:public Base{public:voiddisplay(){
              cout <<"Derived class function called"<< endl;}voidshowBoth(){Base::display();// Base class function using SROdisplay();// derived class function}};intmain(){
         Derived d;
         d.showBoth();return0;}
    Base class function called
    Derived class function called
    

    Example: Multiple Inheritance

    In multiple inheritance, there can be more than one function or variable with same name in different base classes that can cause ambiguity. This can be solved using scope resolution operator. Here is an example where display() function is called using (::) to solve this ambiguity.

    #include <iostream>usingnamespace std;classClassA{public:voiddisplay(){
              cout <<"Display function from ClassA"<< endl;}};classClassB{public:voiddisplay(){
              cout <<"Display function from ClassB"<< endl;}};// Multiple InheritanceclassClassC:public ClassA, public ClassB{public:voidshowAll(){ClassA::display();// Calling ClassA's display using SROClassB::display();// Calling ClassB's display using SRO}};intmain(){
       ClassC obj;
       obj.showAll();return0;}

    The output of the above code is as follows −

    Display function from ClassA
    Display function from ClassB
    

    Conclusion

    In this chapter, we discussed about the scope resolution operator and its various applications. Like other operators, scope resolution operator can not be overloaded. The main purpose of (::) operator is to solve the ambiguity if the variable or the functions are having same name. At compile time, scope resolution operator tells compiler about the variables and functions where they are used in the code. This solves the ambiguity caused by similar names.

  • Unary Operators in C++

    A unary operator is operators that act upon a single operand to produce a new value, It manipulates or modifies only the single operand or value. It is used to perform operations like incrementing, negating, or changing the sign of a value.

    The term “unary” is derived as these operators require only one operand to perform an operation. Which makes it different from binary operators, that requires two operands to perform.

    List of Unary Operators

    OperatorDescriptionExampleResult
    Unary plus operator (+)This indicates a positive value, which results in no actual change in the operand.x = +5x = 5
    Unary negation operator (-)This negates the value of the operand, which changes the sign of an operand.x = -(+5)x = -5
    Increment operator (++)This operator adds one to its operand, which results in an increment of operand by one.x = 5;
    x++
    x = 6
    Decrement operator (–)This operator subtracts one from its operand, which results in a decrement of the operand by one.x = 5;
    x–
    x = 4
    Logical NOT/ Logical negation operator (!)This operator reverses the meaning of its operand. The operand must be of arithmetic or pointer type (or an expression that evaluates to arithmetic or pointer type). The operand is implicitly converted to type bool.x = True;
    !x
    x = False
    Bitwise NOT Operator (~)The Bitwise NOT is sometimes also called the “bitwise complement” or one’s complement operator.x = 5 (binary 0101);
    ~x
    x = -6 (0101 + 1 = 0110)
    Indirection operator (*)/ DereferenceIt operates on a pointer variable and returns an l-value equivalent to the value at the pointer address. Which is also called dereferencing the pointer.*p = 5Dereference and assign value
    Address-of operator (&)This operator takes the address of its operand.int* ptr = &a;ptr = address of a
    Cast operator ()This operator provides a method for explicit conversion of the type of an object in a specific situation.int i = (int) 9.57;i = 9
    sizeof operatorIt is a compile-time unary operator which is used to compute the size of its operand.sizeof(int)4 bytes
    new operatorIt is a memory allocation operator that is used to allocate memory dynamically.int* ptr = new int;Allocates memory
    delete operatorIt is a memory allocation operator that is used to deallocate memory that was dynamically allocated.delete ptr;Frees the memory allocated

    Unary Arithmetic Operators in C++

    In C++, Unary arithmetic operators, are the operators, that operate on a single operand to perform arithmetic operations like changing signs, incrementing, or decrementing.

    Here is the following list of unary arithmetic operators in C++:

    • Unary Plus (+)
    • Unary Minus (-)
    • Increment (++)
    • Decrement (–)

    Unary Plus (+) Operator

    This operator doesn’t change the value of the operand, it just simply returns the operand as it is, whether the operand is negative or positive.

    Syntax

    +operand;

    Example Code

    #include <iostream>usingnamespace std;intmain(){int x =5;int y =-4;
        cout <<"Returning values using Unary plus"<< endl;
        cout <<+x <<" "<<+y << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Returning values using Unary plus
    5 -4

    Unary Minus (-) Operator

    The Unary minus or Unary negation operator is used to change the sign of the operand. If the operand is negative, it will become positive, and vice versa, where the operand can have any arithmetic type.

    Syntax

    -operand;

    Example Code

    #include usingnamespace std;intmain(){int x =6;int y =-12;
        cout <<-x <<" "<<-y << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    -6 12

    Increment (++) Operator

    The increment operator in C++ is used to increase the value of the operand by one. It has two forms:

    • Prefix increment (++x): First increases the value of the operand, then assigns the new value.
    • Postfix increment (x++): First assigns the value, then increments the operand.

    Syntax for Prefix increment

    ++operand;

    Syntax for Postfix increment

    operand++;

    Example Code

    #include <iostream>usingnamespace std;intmain(){int x =5;// Prefix incrementint y =++x;// x is incremented first, then assigned to y
        cout <<"Prefix increment:"<< endl;
        cout <<"x = "<< x <<", y = "<< y << endl;int a =5;// Postfix incrementint b = a++;// b is assigned the value of a first, then a is incremented
        cout <<"Postfix increment:"<< endl;
        cout <<"a = "<< a <<", b = "<< b << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Prefix increment:
    x = 6, y = 6
    Postfix increment:
    a = 6, b = 5

    Decrement (–) Operator

    The decrement operator in C++ is used to decrement the value of an operand by one and also has two forms:

    • Prefix decrement (–x): First decreases the value of the operand, then assigns the new value.
    • Postfix decrement (x–): First assigns the value, then decrements the operand.

    Syntax for Prefix decrement

    --operand;

    Syntax for Postfix decrement

    operand--;

    Example Code

    #include <iostream>usingnamespace std;intmain(){int x =5;int y =--x;// First, x is decremented to 4, then assigned to y
        cout <<"x = "<< x <<" y = "<< y << endl;int a =5;int b = a--;// First, a is assigned to b, then decremented to 4
        cout <<"a = "<< a <<" b = "<< b << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    x = 4 y = 4
    a = 4 b = 5

    Unary Logical Operators

    Unary logical operators in C++, are operators which deal with Boolean values, here it reverses the meaning of their operand. The operand must be of arithmetic or pointer type (or an expression that evaluates to arithmetic or pointer type). Here the operand is implicitly converted to type bool.

    Syntax

    !operand;

    Example Code

    #include <iostream>usingnamespace std;intmain(){int x =10;// non-zero value, considered Trueint y =0;// zero, considered False
    
        cout <<"!x = "<<!x << endl;// x is True, so !x will become false (0)
        cout <<"!y = "<<!y << endl;// y is False, so !y will become true (1)return0;}

    When the above code is compiled and executed, it produces the following result −

    !x = 0
    !y = 1

    Bitwise NOT Operator (~)

    Unary bitwise NOT also known as a bitwise complement or one’s complement operator in C++ is used to perform bit-level operations. This manipulates and operates on individual bits of a variable, and produces the bitwise one’s complement of its operand. The operand must be of integral type.

    Syntax

    ~operand;

    Example Code

    #include <iostream>usingnamespace std;intmain(){int x =5;// In binary: 0000000000000101 (16-bit representation)// Applying the Unary Bitwise NOT (~) operatorint result =~x;// Output the result
        cout <<"x = "<< x << endl;       
        cout <<"~x = "<< result << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    x = 5
    ~x = -6

    Explanation

    Firstly, x is assigned the value 5, in binary 5 is represented as 0000000000000101 (16-bit signed integer representation).
    Applying the Unary Bitwise NOT (~) operator flips each bit of the operand, where 0 becomes 1 and 1 becomes 0.

    • x = 5 => 0000000000000101 (binary of 5)
    • ~x = -6 => 1111111111111010 (bitwise complement of 5)

    When working with signed integers in two’s complement, the most significant bit (leftmost bit) determines the sign of the number.

    • When it’s 0, the number is positive.
    • When it’s 1, the number is negative.

    So, The binary number 1111111111111010 will give a negative decimal number.
    Now, to check its decimal number, add 1, which equals 0000000000000110.
    So, the result is -6.

    Pointer Operators

    Pointer operators are used to work with pointers in C++, these two pointer operators come under unary because it operates only in single operands.

    Dereference (*) Operator

    Dereference also known as an Indirection operator, operates on a pointer variable, which accesses the value stored at the address by a pointer and returns the value of the object that the pointer is pointing to.

    Syntax

    *pointer;

    Address-of (&) Operator

    Whereas, the Address-of operator returns the memory address of a variable. It returns the address memory where that variable is located.

    Syntax

    &operand;

    Example Code

    #include <iostream>usingnamespace std;intmain(){int num =10;// Using the Address-of operator to get the address of numint* ptr = #  // ptr now holds the address of num// Using the Dereference operator to access the value stored at 
        cout <<"The value of num: "<< num << endl;        
        cout <<"The address of num: "<<&num << endl;          
        cout <<"The address stored in ptr: "<< ptr << endl;      
        cout <<"The value pointed to by ptr: "<<*ptr << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    The value of num: 10
    The address of num: 0x7fff08fa2814
    The address stored in ptr: 0x7fff08fa2814
    The value pointed to by ptr: 10

    Typecast Operator (C++ Style)

    The Typecast operator in C++ is a method used for explicit conversion of one data type into another.

    Here, C++ provides several methods for type casting, including C and C++-style casts:

    • static_cast: It is used for conversion between related types (e.g. int to float, float to double, char to int, and derived class to base class).
    • dynamic_cast: It is used for downcasting in polymorphic class hierarchies, with runtime checking.
    • const_cast: It is used to add/remove the const qualifier.
    • reinterpret_cast: It is used for low-level pointer conversions.

    Syntax

    (type)operand;// C-style cast

    Example Code

    #include <iostream>usingnamespace std;intmain(){double a =10.78;// C-style cast: Convert double to int (fractional part is discarded)int b =(int)a;
        cout <<"Original value of a = "<< a << endl;
        cout <<"After C-style cast = "<< b << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Original value of a = 10.78
    After C-style cast = 10

    Sizeof Operator

    The sizeof operator in C++ is used to determine the size(in bytes) of any data type, variable, or data structure. It is a compile-time unary operator. This is often used for finding the memory consumption of data types, calculating the size of arrays or structures, and allocating memory dynamically using malloc or new.

    Syntax

    sizeof(type);

    Example Code

    #include <iostream>usingnamespace std;intmain(){int a =10;double b =5.75;char c ='X';// Display the size of each data type and variable
        cout <<"Size of int: "<<sizeof(a)<<" bytes"<< endl;
        cout <<"Size of double: "<<sizeof(b)<<" bytes"<< endl;
        cout <<"Size of char: "<<sizeof(c)<<" byte"<< endl;
        cout <<"Size of bool: "<<sizeof(true)<<" byte"<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Size of int: 4 bytes
    Size of double: 8 bytes
    Size of char: 1 byte
    Size of bool: 1 byte

    Type-Specific Operators

    Type-Specific Operators in C++, are the operators, which is used for dynamic memory allocation and deallocation.

    • new: This is used to allocate memory for any single object or an array of objects.
    • delete: This is used to deallocate the memory allocated with new.

    Syntax for new Operator

    // Single object
    pointer =new type;//Array of objects
    pointer =new type[size];

    Syntax for delete Operator

    // Single objectdelete pointer;//Array of objectsdelete[] pointer;

    Example Code

    #include <iostream>usingnamespace std;intmain(){int* ptr =newint;*ptr =25;          
        cout <<"Dynamically allocated integer: "<<*ptr << endl;// Deallocate the memory using deletedelete ptr;return0;}

    When the above code is compiled and executed, it produces the following result −

    Dynamically allocated integer: 25
  • Operators Precedence in C++

    C++ Operators Precedence

    The operator precedence determines the order in which operations are performed in an expression. Operators with higher precedence are evaluated first.

    Example

    Consider the following expression:

    int x =10+4*3;

    Here, the multiplication has higher precedence than addition, so 4 * 3 is evaluated first, resulting in x = 10 + 12, which gives x = 22.

    To change the order, use parentheses:

    int x =(10+4)*3;

    Now 10 + 4 is evaluated first, resulting in x = 14 * 3, which gives x = 42.

    C++ Operator Precedence Table

    The operators are listed from top to bottom in descending order of precedence:

    OperatorDescriptionExample
    () [] -> .Function call, Subscript, Member accessarr[0], obj.method(), ptr->member
    ++ —Increment/Decrementx++, –y
    ! ~ – +Logical/Bitwise NOT, Unary plus/minus!flag, ~num, -value, +value
    * / %Multiplication, Division, Modulusa * b, x / y, n % 2
    + –Addition, Subtractiona + b, x – y
    << >>Bitwise shiftx > 3
    < <= > >=Relational operatorsa = y
    == !=Equality operatorsa == b, x != y
    &Bitwise ANDa & b
    ^Bitwise XORx ^ y
    |Bitwise ORa | b
    &&Logical ANDx && y
    ||Logical ORa || b
    ?:Ternary conditionalx ? y : z
    = += -= *= /= %= &= ^= |= >=Assignment and compound assignmenta = b, x += y, z >>= 2
    ,Commax = (a, b, c)

    Example of Operators Precedence

    Try the following example to understand operators precedence concept available in C++. Copy and paste the following C++ program in test.cpp file and compile and run this program.

    Check the simple difference with and without parenthesis. This will produce different results because (), /, * and + have different precedence. Higher precedence operators will be evaluated first −

    #include <iostream>usingnamespace std;intmain(){int a =20;int b =10;int c =15;int d =5;int e;
     
       e =(a + b)* c / d;// ( 30 * 15 ) / 5
       cout <<"Value of (a + b) * c / d is :"<< e << endl ;
    
       e =((a + b)* c)/ d;// (30 * 15 ) / 5
       cout <<"Value of ((a + b) * c) / d is  :"<< e << endl ;
    
       e =(a + b)*(c / d);// (30) * (15/5)
       cout <<"Value of (a + b) * (c / d) is  :"<< e << endl ;
    
       e = a +(b * c)/ d;//  20 + (150/5)
       cout <<"Value of a + (b * c) / d is  :"<< e << endl ;return0;}

    When the above code is compiled and executed, it produces the following result −

    Value of (a + b) * c / d is :90
    Value of ((a + b) * c) / d is  :90
    Value of (a + b) * (c / d) is  :90
    Value of a + (b * c) / d is  :50
  • C++ Pointer Operators

    C++ provides two pointer operators, which are (a) Address of Operator & and (b) Indirection Operator *.

    A pointer is a variable that contains the address of another variable or you can say that a variable that contains the address of another variable is said to “point to” the other variable. A variable can be any data type including an object, structure or again pointer itself.

    The . (dot) operator and the -> (arrow) operator are used to reference individual members of classes, structures, and unions.

    The Address of Operator &

    The & is a unary operator that returns the memory address of its operand. For example, if var is an integer variable, then &var is its address. This operator has the same precedence and right-to-left associativity as the other unary operators.

    You should read the & operator as “the address of” which means &var will be read as “the address of var”.

    The Indirection Operator *

    The second operator is indirection Operator *, and it is the complement of &. It is a unary operator that returns the value of the variable located at the address specified by its operand.

    The following program executes the two operations

    #include <iostream>usingnamespace std;intmain(){int  var;int*ptr;int  val;
    
       var =3000;// take the address of var
       ptr =&var;// take the value available at ptr
       val =*ptr;
       cout <<"Value of var :"<< var << endl;
       cout <<"Value of ptr :"<< ptr << endl;
       cout <<"Value of val :"<< val << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Value of var :3000
    Value of ptr :0xbff64494
    Value of val :3000
  • C++ Casting Operators

    Casting Operators in C++

    A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator.

    Syntax

    The most general cast supported by most of the C++ compilers is as follows −

    (type) expression 
    

    C++ Type Casting Operators

    Where type is the desired data type. There are other casting operators supported by C++, they are listed below −

    • const_cast<type> (expr) − The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed.
    • dynamic_cast<type> (expr) − The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object.
    • reinterpret_cast<type> (expr) − The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa.
    • static_cast<type> (expr) − The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer.

    Example of Casting Operators

    All of the above-mentioned casting operators will be used while working with classes and objects. For now, try the following example to understand a simple cast operators available in C++. Copy and paste the following C++ program in test.cpp file and compile and run this program.

    #include <iostream>usingnamespace std;main(){double a =21.09399;float b =10.20;int c ;
     
       c =(int) a;
       cout <<"Line 1 - Value of (int)a is :"<< c << endl ;
       
       c =(int) b;
       cout <<"Line 2 - Value of (int)b is  :"<< c << endl ;return0;}

    When the above code is compiled and executed, it produces the following result −

    Line 1 - Value of (int)a is :21
    Line 2 - Value of (int)b is  :10
  • C++ Member (dot & arrow) Operators

    The . (dot) operator and the -> (arrow) operator are used to reference individual members of classes, structures, and unions.

    The dot operator is applied to the actual object. The arrow operator is used with a pointer to an object. For example, consider the following structure −

    structEmployee{char first_name[16];int  age;}  emp;

    The (.) dot operator

    To assign the value “zara” to the first_name member of object emp, you would write something as follows −

    strcpy(emp.first_name,"zara");

    Example

    #include <iostream>#include <cstring>usingnamespace std;structEmployee{char first_name[20];};intmain(){
        Employee emp;// Using dot operator to assign a valuestrcpy(emp.first_name,"zara");
    
        cout <<"First Name: "<< emp.first_name << endl;return0;}

    When executed, this program outputs:

    First Name: zara
    

    The (->) arrow operator

    If p_emp is a pointer to an object of type Employee, then to assign the value “zara” to the first_name member of object emp, you would write something as follows −

    strcpy(p_emp->first_name,"zara");

    The -> is called the arrow operator. It is formed by using the minus sign followed by a greater than sign.

    Example

    #include <iostream>#include <cstring>usingnamespace std;structEmployee{char first_name[20];};intmain(){
        Employee emp;
        Employee* p_emp =&emp;// Using arrow operator to assign a valuestrcpy(p_emp->first_name,"zara");
    
        cout <<"First Name: "<< p_emp->first_name << endl;return0;}

    When executed, this program outputs:

    First Name: zara
    

    Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.

  • C++ Comma Operator

    The purpose of comma operator is to string together several expressions. The value of a comma-separated list of expressions is the value of the right-most expression. Essentially, the comma’s effect is to cause a sequence of operations to be performed.

    How Comma Operator Works?

    The values of the other expressions will be discarded. This means that the expression on the right side will become the value of the entire comma-separated expression. For example −

    var =(count =19, incr =10, count+1);

    Here first assigns count the value 19, assigns incr the value 10, then adds 1 to count, and finally, assigns var the value of the rightmost expression, count+1, which is 20. The parentheses are necessary because the comma operator has a lower precedence than the assignment operator.

    Example of Comma Operator

    To see the effects of the comma operator, try running the following program −

    #include <iostream>usingnamespace std;intmain(){int i, j;
       
       j =10;
       i =(j++, j+100,999+j);
    
       cout << i;return0;}

    When the above code is compiled and executed, it produces the following result −

    1010
    

    Here is the procedure how the value of i gets calculated: j starts with the value 10. j is then incremented to 11. Next, j is added to 100. Finally, j (still containing 11) is added to 999, which yields the result 1010.

    Use Cases of Comma Operator

    1. Using Comma Operator in Variable Initialization

    In the following example, we use the comma operator to initialize multiple variables in a single statement.

    #include <iostream>usingnamespace std;intmain(){int a, b, c;// Using comma operator for initialization
        a =(b =10, c =20);
    
        cout <<"Value of a: "<< a << endl;
        cout <<"Value of b: "<< b << endl;
        cout <<"Value of c: "<< c << endl;return0;}

    When executed, this program outputs:

    Value of a: 20
    Value of b: 10
    Value of c: 20
    

    2. Using Comma Operator in Loops

    The comma operator can be used in loops to update multiple variables.

    #include <iostream>usingnamespace std;intmain(){// Using comma operator in a for loopfor(int i =0, j =5; i <5; i++, j--){
            cout <<"i: "<< i <<", j: "<< j << endl;}return0;}

    When executed, this program outputs:

    i: 0, j: 5
    i: 1, j: 4
    i: 2, j: 3
    i: 3, j: 2
    i: 4, j: 1
    

    3. Using Comma Operator in Function Arguments

    The comma operator can be used in function calls where multiple expressions are evaluated, but only the last value is passed as an argument.

    #include <iostream>usingnamespace std;// Function that takes an integer parametervoiddisplay(int x){
        cout <<"Received value: "<< x << endl;}intmain(){int a =5, b =10;// Using comma operator in function argumentsdisplay((a +=5, b +=20));return0;}

    When executed, this program outputs:

    Received value: 30
    

    4. Using Comma Operator in if Statements

    The comma operator can be useful in conditional statements when multiple expressions need to be checked.

    #include <iostream>usingnamespace std;intmain(){int x =10, y =20;// Using comma operator in if conditionif(x +=5, y -=10, x > y){
            cout <<"x is greater than y"<< endl;}else{
            cout <<"y is greater than or equal to x"<< endl;}return0;}

    When executed, this program outputs:

    x is greater than y
  • C++ Conditional ? : Operator

    Exp1 ? Exp2 : Exp3;
    

    where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

    The ? is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form −

    if(condition){
       var = X;}else{
       var = Y;}

    For example, consider the following code −

    if(y <10){ 
       var =30;}else{
       var =40;}

    Above code can be rewritten like this −

    var =(y <10)?30:40;

    Here, x is assigned the value of 30 if y is less than 10 and 40 if it is not. You can the try following example −

    #include <iostream>usingnamespace std;intmain(){// Local variable declaration:int x, y =10;
    
       x =(y <10)?30:40;
       cout <<"value of x: "<< x << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    value of x: 40
  • C++ sizeof Operator

    The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type.

    The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type.

    Syntax of sizeof Operator

    The syntax of using sizeof is as follows −

    sizeof(data type)

    Where data type is the desired data type including classes, structures, unions and any other user defined data type.

    Example of sizeof Operator

    Try the following example to understand all the sizeof operator available in C++. Copy and paste following C++ program in test.cpp file and compile and run this program.

    #include <iostream>usingnamespace std;intmain(){
       cout <<"Size of char : "<<sizeof(char)<< endl;
       cout <<"Size of int : "<<sizeof(int)<< endl;
       cout <<"Size of short int : "<<sizeof(shortint)<< endl;
       cout <<"Size of long int : "<<sizeof(longint)<< endl;
       cout <<"Size of float : "<<sizeof(float)<< endl;
       cout <<"Size of double : "<<sizeof(double)<< endl;
       cout <<"Size of wchar_t : "<<sizeof(wchar_t)<< endl;return0;}

    When the above code is compiled and executed, it produces the following result, which can vary from machine to machine −

    Size of char : 1
    Size of int : 4
    Size of short int : 2
    Size of long int : 4
    Size of float : 4
    Size of double : 8
    Size of wchar_t : 4
    

    More Examples of sizeof in C++

    The following examples demonstrate the common usage of the sizeof operator in C++:

    Find the Size of Different Variables

    In the following example, we are finding the memory size occupied by different variables.

    #include <iostream>usingnamespace std;intmain(){int age =25;float price =99.99;char grade ='A';// Printing size of variables
        cout <<"Size of age (int): "<<sizeof(age)<<" bytes"<< endl;
        cout <<"Size of price (float): "<<sizeof(price)<<" bytes"<< endl;
        cout <<"Size of grade (char): "<<sizeof(grade)<<" bytes"<< endl;return0;}

    When executed, this program outputs:

    Size of age (int): 4 bytes
    Size of price (float): 4 bytes
    Size of grade (char): 1 bytes
    

    Find the Size of an Array Using sizeof

    In the following example, we are finding the total size of an integer array and the number of elements it contains.

    #include <iostream>usingnamespace std;intmain(){int scores[]={85,90,78,92,88};// Finding the number of elements in the arrayint totalSize =sizeof(scores);int elementSize =sizeof(scores[0]);int length = totalSize / elementSize;
    
        cout <<"Total size of array: "<< totalSize <<" bytes"<< endl;
        cout <<"Size of one element: "<< elementSize <<" bytes"<< endl;
        cout <<"Number of elements: "<< length << endl;return0;}

    When executed, this program outputs:

    Total size of array: 20 bytes
    Size of one element: 4 bytes
    Number of elements: 5
    

    Find the Size of a Class

    In the following example, we are finding the memory size occupied by an object of a class.

    #include <iostream>usingnamespace std;classStudent{int rollNumber;double marks;public:Student(int r =1,double m =95.5):rollNumber(r),marks(m){}};intmain(){// Finding size of class Student
        cout <<"Size of Student class: "<<sizeof(Student)<<" bytes"<< endl;return0;}

    When executed, this program outputs:

    Size of Student class: 16 bytes
  • C++ Assignment Operators

    C++ assignment operators are used to assign values to variables. These operators allow you to set or update the value stored in a variable.

    List of C++ Assignment Operators

    There are following assignment operators supported by C++ language

    OperatorDescriptionExample
    =Simple assignment operator, Assigns values from right side operands to left side operand.C = A + B will assign value of A + B into C
    +=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand.C += A is equivalent to C = C + A
    -=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand.C -= A is equivalent to C = C – A
    *=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand.C *= A is equivalent to C = C * A
    /=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand.C /= A is equivalent to C = C / A
    %=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand.C %= A is equivalent to C = C % A
    <<=Left shift AND assignment operator.C <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operator.C >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operator.C &= 2 is same as C = C & 2
    ^=Bitwise exclusive OR and assignment operator.C ^= 2 is same as C = C ^ 2
    |=Bitwise inclusive OR and assignment operator.C |= 2 is same as C = C | 2

    Example of Assignment Operators

    Try the following example to understand all the assignment operators available in C++.

    Copy and paste the following C++ program in test.cpp file and compile and run this program.

    #include <iostream>usingnamespace std;main(){int a =21;int c ;
    
       c =  a;
       cout <<"Line 1 - =  Operator, Value of c = : "<<c<< endl ;
    
       c +=  a;
       cout <<"Line 2 - += Operator, Value of c = : "<<c<< endl ;
    
       c -=  a;
       cout <<"Line 3 - -= Operator, Value of c = : "<<c<< endl ;
    
       c *=  a;
       cout <<"Line 4 - *= Operator, Value of c = : "<<c<< endl ;
    
       c /=  a;
       cout <<"Line 5 - /= Operator, Value of c = : "<<c<< endl ;
    
       c  =200;
       c %=  a;
       cout <<"Line 6 - %= Operator, Value of c = : "<<c<< endl ;
    
       c <<=2;
       cout <<"Line 7 - <<= Operator, Value of c = : "<<c<< endl ;
    
       c >>=2;
       cout <<"Line 8 - >>= Operator, Value of c = : "<<c<< endl ;
    
       c &=2;
       cout <<"Line 9 - &= Operator, Value of c = : "<<c<< endl ;
    
       c ^=2;
       cout <<"Line 10 - ^= Operator, Value of c = : "<<c<< endl ;
    
       c |=2;
       cout <<"Line 11 - |= Operator, Value of c = : "<<c<< endl ;return0;}

    When the above code is compiled and executed, it produces the following result −

    Line 1 - =  Operator, Value of c = : 21
    Line 2 - += Operator, Value of c = : 42
    Line 3 - -= Operator, Value of c = : 21
    Line 4 - *= Operator, Value of c = : 441
    Line 5 - /= Operator, Value of c = : 21
    Line 6 - %= Operator, Value of c = : 11
    Line 7 - <<= Operator, Value of c = : 44
    Line 8 - >>= Operator, Value of c = : 11
    Line 9 - &= Operator, Value of c = : 2
    Line 10 - ^= Operator, Value of c = : 0
    Line 11 - |= Operator, Value of c = : 2