C++ Operators
In this tutorial, we will learn about the different types of operators in C++ with the help of examples. In programming, an operator is a symbol that operates on a value or a variable.
Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2 .Assignment Operators
3 .Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
1. C++ Arithmetic Operators
a + b;
Operator | Operation |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo Operation (Remainder after division) |
2. C++ Assignment Operators
// assign 5 to a
a = 5;
Operator | Example | Equivalent to |
---|---|---|
= | a = b; | a = b; |
+= | a += b; | a = a + b; |
-= | a -= b; | a = a - b; |
*= | a *= b; | a = a * b; |
/= | a /= b; | a = a / b; |
%= | a %= b; | a = a % b; |
3. C++ Relational Operators
a > b;
Operator | Meaning | Example |
---|---|---|
== | Is Equal To | 3 == 5 gives us false |
!= | Not Equal To | 3 != 5 gives us true |
> | Greater Than | 3 > 5 gives us false |
< | Less Than | 3 < 5 gives us true |
>= | Greater Than or Equal To | 3 >= 5 give us false |
<= | Less Than or Equal To | 3 <= 5 gives us true
|
4. C++ Logical Operators
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.
Operator | Example | Meaning |
---|---|---|
&& | expression1 && expression2 | Logical AND. True only if all the operands are true. |
|| | expression1 || expression2 | Logical OR. True if at least one of the operands is true. |
! | !expression | Logical NOT. True only if the operand is false. |
5. C++ Bitwise Operators
In C++, bitwise operators are used to perform operations on individual bits. They can only be used alongside char
and int
data types.
Operator | Description |
---|---|
& | Binary AND |
| | Binary OR |
^ | Binary XOR |
~ | Binary One's Complement |
<< | Binary Shift Left |
>> | Binary Shift Right |
6. Other C++ Operators
Here's a list of some other common operators available in C++. We will learn about them in later tutorials.
Operator | Description | Example |
---|---|---|
sizeof | returns the size of data type | sizeof(int); // 4 |
?: | returns value based on the condition | string result = (5 > 0) ? "even" : "odd"; // "even" |
& | represents memory address of the operand | # // address of num |
. | accesses members of struct variables or class objects | s1.marks = 92; |
-> | used with pointers to access the class or struct variables | ptr->marks = 92; |
<< | prints the output value | cout << 5; |
>> | gets the input value | cin >> num; |
0 comments:
Post a Comment