Exforsys

Home arrow Technical Training arrow C++ Tutorials

C++ Operators Part II

Author: Sripriya R     Published on: 27th Aug 2007    |   Last Updated on: 25th Jul 2011

In this C++ tutorial, you will learn about logical operators, && operator, || operator, conditional operator, comma operator, bitwise operator and sizeof() operator.

Ads

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:

Sample Code
  1. condition ? value1 : value2
Copyright exforsys.com


For example:

Sample Code
  1. 7>5 ? x : y
Copyright exforsys.com


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:

Sample Code
  1. exfor = (x=5, x+3);
Copyright exforsys.com


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

Ads

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:

Sample Code
  1. x = sizeof (char);
Copyright exforsys.com


This returns the size of char in bytes. In this example, the size is 1 byte which is assigned to variable x.

Read Next: C++ Manipulators


 
 

Comments