In this C++ tutorial, you will learn about logical operators, && operator, || operator, conditional operator, comma operator, bitwise operator and sizeof() operator.
Logical Operators
The logical operators used are: !, &&, ||
The operator ! is called NOT operator. This has a single operand which reverses its value.
Logical Operators
!true gives the value of false
!false gives the value of true
The operator && corresponds with Boolean logical operation AND. This operator returns the value of true only if both its operands are true or else it returns false. The following table reflects the value of && operator:
&& Operator
x | y | x && y |
true | true | true |
true | false | false |
false | true | false |
false | false | false |
The operator || corresponds with Boolean logical operation OR. The operator returns a true value if either one of its two operands is true and returns a false value only when both operands are false. The following table reflects the value of || operator:
|| Operator
x | y | x || y |
true | true | true |
true | false | true |
false | true | true |
false | false | false |
Conditional Operator
The conditional operator evaluates an expression returning value1 if that expression is true and value2 if the expression is evaluated as false.
The syntax is:
condition ? value1 : value2
For example:
7>5 ? x : y
Since 7 is greater than 5, true is returned and hence the value x is returned.
Comma Operator
This is denoted by “,” and it is used to separate two or more expressions.
For example:
exfor = (x=5, x+3);
Here value of 5 is assigned to x and then the value of x+3 is assigned to the variable exfor. Hence, value of the variable exfor is 8.
Bitwise Operators
The following are the bitwise operators available in C++:
- & AND Bitwise AND
- | OR Bitwise Inclusive OR
- ^ XOR Bitwise Exclusive OR
- ~ NOT Unary complement (bit inversion)
- << SHL Shift Left
- >> SHR Shift Right
- Explicit type casting operator
sizeof() Operator
This operator accepts a single parameter and this can be a variable or data type. This operator returns the size in bytes of the variable or data type.
For example:
x = sizeof (char);
This returns the size of char in bytes. In this example, the size is 1 byte which is assigned to variable x.