The C++ standard provides operator keywords (Fig. 21.4) that can be used in place of several C++ operators. You can use operator keywords if you have keyboards that do not support certain characters such as !
, &
, ^
, ~
, |
, etc.
Figure 21.5 demonstrates the operator keywords. Microsoft Visual C++ 2010 requires the header <ciso646>
(line 4) to use the operator keywords. In GNU C++ and LLVM, the operator keywords are always defined and this header is not required.
1 // Fig. 21.5: fig21_05.cpp
2 // Demonstrating operator keywords.
3 #include <iostream>
4 #include <ciso646> // enables operator keywords in Microsoft Visual C++
5 using namespace std;
6
7 int main()
8 {
9 bool a = true;
10 bool b = false;
11 int c = 2;
12 int d = 3;
13
14 // sticky setting that causes bool values to display as true or false
15 cout << boolalpha;
16
17 cout << "a = " << a << "; b = " << b
18 << "; c = " << c << "; d = " << d;
19
20 cout << "
Logical operator keywords:";
21 cout << "
a and a: " << ( a and a );
22 cout << "
a and b: " << ( a and b );
23 cout << "
a or a: " << ( a or a );
24 cout << "
a or b: " << ( a or b );
25 cout << "
not a: " << ( not a );
26 cout << "
not b: " << ( not b );
27 cout << "
a not_eq b: " << ( a not_eq b );
28
29 cout << "
Bitwise operator keywords:";
30 cout << "
c bitand d: " << ( c bitand d );
31 cout << "
c bitor d: " << ( c bitor d );
32 cout << "
c xor d: " << ( c xor d );
33 cout << "
compl c: " << ( compl c );
34 cout << "
c and_eq d: " << ( c and_eq d );
35 cout << "
c or_eq d: " << ( c or_eq d );
36 cout << "
c xor_eq d: " << ( c xor_eq d ) << endl;
37 } // end main
a = true; b = false; c = 2; d = 3
Logical operator keywords:
a and a: true
a and b: false
a or a: true
a or b: true
not a: false
not b: true
a not_eq b: true
Bitwise operator keywords:
c bitand d: 2
c bitor d: 3
c xor d: 1
compl c: -3
c and_eq d: 2
c or_eq d: 3
c xor_eq d: 0
The program declares and initializes two bool
variables and two integer variables (lines 9–12). Logical operations (lines 21–27) are performed with bool
variables a
and b
using the various logical operator keywords. Bitwise operations (lines 30–36) are performed with the int
variables c
and d
using the various bitwise operator keywords. The result of each operation is output.