Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter - 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

Chapter Three

Basic concept of C++ programming


Constants, Variables, data Types and Operators
In C++ every statement is made up of smallest individual elements called tokens. Tokens are the
basic lexical elements. Tokens in C++ include the following.
A. Keywords C. Constants
B. Identifiers D. Operators
1. Keywords
Keywords are also called reserved, which have a predefined meaning in C++ and cannot be used
as names for variables or anything else. The letters that make up a reserved word are always
lowercase. Every keyword will perform a specific operation in C++. Keywords in C++ cannot be
redefined by a programmer. Some predefined words, such as cin and cout, are not keywords.
These predefined words are not part of the core C++ language, and you are allowed to redefine
them. Although these predefined words are not keywords, they are defined in libraries required
by the C++ language standard.

2. Identifiers
Identifiers are names of things that appear in programs, such as variables, constants, and
functions. In C++ all variables must be declared before they are used identifier. A C++ identifier
consists of letters, digits, and the underscore character (_) and must begin with a letter or
underscore.
Some identifiers are predefined; others are defined by the user. Identifiers are case sensitive, i.e.,
first name is different from First name

1
Legal Identifiers
Here are some specific rules that must be followed with all identifiers.
• The first character must be one of the letters a through z, A through Z, or an
underscore character (_).
• After the first character you may use the letters a through z or A through Z, the digits 0
through 9, or underscores.
• Uppercase and lowercase characters are distinct. This means ItemsOrdered is not the
same as itemsordered.
• Key words should not be used as names for identifiers.
Examples of invalid Identifiers
 12B Invalid variable name since its starts with a number.
 Basic pay Invalid variable name since it has a space
 ABC, 1 Invalid variable name since, is a special character
 Employee Salary There can be no space between employee and Salary.
 Hello! The exclamation mark cannot be used in an identifier.
 One + two the symbol + cannot be used in an identifier.
 2nd An identifier cannot begin with a digit.
3. Constants
Constants refer to values that do not change during the execution of the program. A constant is
any expression that has a fixed value.
 Constants are data storage locations in the computer memory. But, constants, unlike
variables their content cannot be changed after the declaration.
 Constants must be initialized when they are created by the program, and the programmer
can’t assign a new value to a constant later.
 C++ provides two types of constants: literal and symbolic constants.
I. Literal constant: is a value typed directly into the program wherever it is needed.
E.g.: int num = 43;
43 is a literal constant in this statement:
II. Symbolic constant: is a constant that is represented by a name, similar to that of a variable.
But unlike a variable, its value can’t be changed after initialization.
E.g. int studentPerClass =15;

2
students = classes * studentPerClass;
studentPerClass is a symbolic constant having a value of 15.
And 15 is a literal constant directly typed in the program.
 In C++, we can declare a symbolic constant by using the const key word.
E.g. const double PI = 3.141592;
const double RATE = 6.9;
Examples for constants are:
1998 Integer constant
25.789 Floating point constant
“Hello World” String constant
‘a’ Character constant
III. The const Keyword
You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
Following example uses const keywords.
#include <iostream>
using namespace std; 
int main()
{
const int LENGTH = 12;
const int WIDTH = 8;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0; }
3.1. Data Types
The data type indicates what kind of data can be stored, thus setting the size of that location. The
amount of memory space necessary to store a variable is also referred to as a data type.
A data type provides two valuable pieces of information to the compiler:

3
What amount of space the variable will use?
What kind of information will be allowed in that space?
3.1.1. Integer Data Types
Integers are whole numbers that do not contain any fractional component. They take up less
memory than numbers with fractional components. C++ has three data types that are integers:
short, int and long. The difference is strictly in the amount of memory (bytes) they reserve:
short reserving the least and long reserving the most. Larger integers may need the long data
type.
The following three statements define integer variables in C++:
short count;
int sum;
long total;
No commas are used within an integer. Recall that in C++, commas are used to separate items in
a list. So 36,782 would be interpreted as two integers: 36 and 782.
3.1.2. Floating Point Data Type
In C++ program, 3 = 3.0 is not a true statement. The number on the left is an integer and the
number on the right is a real, or floating point, number (a number that has a fractional
component). Although mathematically the two are equal, the computer stores them as different
data types. C++ uses both float and double to indicate floating point numbers, with double using
more memory than float.
Float: The data type float is used in C++ to represent any real number between -3.4E+38 and
3.4E+38. The memory allocated for a value of the float data type is four bytes.
Double: The data type double is used in C++ to represent any real number between -1.7E+308
and 1.7E+308. The memory allocated for a value of the double data type is eight bytes.
The maximum number of significant digits—that is, the number of decimal places—in float
values is six or seven. The maximum number of significant digits in values belonging to the
double type is 15.
The maximum number of significant digits is called the precision. Sometimes float values are
called single precision, and values of type double are called double precision.
The following two statements define floating point variables in C++.
float average;

4
double balance;
3.1.3. Character Data Type
The data type char is the smallest integral data type. It is mainly used to represent
characters —that is, letters, digits, and special symbols. Thus, the char data type can
represent every key on your keyboard. When using the char data type, you enclose each
character represented within single quotation marks.
Thus '8' is different than 8. The first is a character while the second is an integer.
Note that a blank space is a character and is written as ' ', with a space between the single
quotation marks. The data type char allows only one symbol to be placed between the single
quotation marks. Thus, the value 'abc' is not of the type char. The following statement defines a
C++ character variable initialized to 'a'.
char letter = 'a';
Examples of values belonging to the char data type include the following:
I. Letters : A-Z, a-z
II. Digits: 0-9
III.Special Characters Space + - * / ^ \ ( ) [ ] { } =! = < > . ‘ " $ , ; : % ! & ? _ # <= > = @
IV. White spaces Horizontal tab (—>), Blank space, Carriage return (<) Newline, form feed.
3.1.4. Boolean Data Type
The data type bool has only two values: true and false. Also, true and false are called the logical
(Boolean) values. The central purpose of this data type is to manipulate logical (Boolean)
expressions. In C++, bool, true, and false are reserved words.
bool found = false;
Following table lists down seven basic C++ data types:
Type Keyword
Boolean Bool
Character Char
Integer Int
Floating point Float
Double floating Double
point

5
Valueless Void

Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers:
 signed
 unsigned
 short
 long
The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.

The sizes of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.
Following is the example, which will produce correct size of various data types on your
computer.

6
#include <iostream>

int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0; }
This example uses endl, which inserts a new-line character after every line and << operator is
being used to pass multiple values out to the screen. We are also using sizeof() function to get
size of various data types.
3.2. Variable in C++

The amount of memory space necessary to store a variable is also referred to as a data type. A
data type provides two valuable pieces of information to the compiler: what amount of space the
variable will use, what kind of information will be allowed in that space. After declaring a
variable, the compiler reserves a space in memory for that variable:

A variable, any variable, occupies more that one small “cell” of space in memory. It will always
be your responsibility to decide how much space a variable needs, based on your goal. A
variable is memory location whose content may change during program execution. The syntax
for declaring one variable or multiple variables is:

Data Type identifier, identifier,


 All variables have three important properties:

7
 Data Type: a type which is established when the variable is defined. (e.g. integer, real,
character etc). Data type describes the property of the data and the size of the reserved
memory. As a general rule, a variable is defined by specifying its type first, followed by
the variable name, followed by a semicolon.
 Name: a name which will be used to refer to the value in the variable. A unique identifier
for the reserved memory location
 Value: a value which can be changed by assigning a new value to the variable.(e.g. 2,3, 5)

3.3. Variable Definition in C++

A variable definition means to tell the compiler where and how much to create the storage for the
variable. A variable definition specifies a data type, and contains a list of one or more variables
of that type as follows:

Type variable _ list;

Here, type must be a valid C++ data type including char, int, float, double, bool or any user-
defined object, etc., and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here:

int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler
to create variables named i, j and k of type int.

3.4. Variable Declaration in C++

When a variable is declared, memory is allocated for it. Variables can be created in a process
known as declaration. The syntax to declare a new variable is to write the specifies of the
desired data type (like int, bool, float...) followed by a valid variable identifier

8
There are two places you can declare a variable:
 Before the code that uses the variable
 Before a function name (such as before main() in the program)

Example1 Try the following example where a variable has been declared at the top, but it has
been defined inside the main function:

#include <iostream>
// Variable declaration:

int a, b;
int c;
float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0; }

When the above code is compiled and executed, it produces the following result:
30 and 23.3333

The name of a variable:

9
 Starts with an underscore “_” or a letter, lowercase or uppercase, such as a letter from a
to z or from A to Z. Examples are Name, gender, _Students, pRice
 Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction,
Player1, total_grade, _Score_Side1
 Cannot include special characters such as !, %, ], or $
 Cannot include an empty space
 Cannot be any of the reserved words
 Should not be longer than 32 characters (although allowed)

C++ programmers typically use lowercase letters to declare variables. If a variable name is a
combination of more than one word, then the first letter of each word, except the first word, is
uppercase.
3.5. Initialization of variables
Variables are initialized to a specific value at the time of declaration. Initialization is done only
once. For example:
int num = 10;
int fun (5)
In statement (1) the variable num is initialized to 10, whereas in the second statement the
variable fun is initialized to 5 through a constructor.
Variables can be initialized (assigned an initial value) in their declaration. A variable is said to be
initialized the first time a value is placed in the variable. Because the assignment operator, =, is
evaluated from right to left, the associatively of the assignment operator is said to be from right
to left. In C++, = is called the assignment operator.

Type variable name = value


Some examples are:

int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

10
More than one variable of the same data type can be declared in a single declaration statement.
But every variable should be separated by comma.
Example: int a,b,c,d; or double i,j;
3.6. Assigning values to variables
In C++, you can place data into a variable in two ways:
1. Use C++’s assignment statement.
2. Use input (read) statements.
The assignment statement takes the following form:

Variable=expression;
The expression is any variable, literal, expression, or combination that produces a resulting data
type that is the same as the variable’s data.
Think of the equal sign as a left-pointing arrow. The equal sign means you want to take the
number, variable, or expression on the right side of the equal sign and put it into the variable on
the left side of the equal sign.
In an assignment statement, the value of the expression should match the data type of the
variable. The expression on the right side is evaluated, and its value is assigned to the variable
(and thus to a memory location) on the left side. A variable is said to be initialized the first time a
value is placed in the variable.
In C++, = is called the assignment operator. The next three statements assign values to the
variables.
age = 32;
salary = 25000.00;
Height = 2;
Example1: int num;
num = 5;
The statement int num; may be interpreted as “num is a variable of the type integer “. The
assignment statement num = 5 may be interpreted as the value 5 is stored in the variable num.

11
An l value is anything that can appear on the left-hand side of an assignment operator (=), which
means any kind of variable. An rvalue is anything that can appear on the right-hand side of an
assignment operator, which means any expression that evaluates to a value.
Lvalue = left value rvalue = right value

3.5. C++ Literals (constants)

Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values. Again, constants are treated
just like regular variables except that their values cannot be modified after their definition.

3.5.1. Integer literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or
radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals:

212 // Legal.
215u // Legal.
0xFeeL // Legal.
078 // illegal: 8 is not an octal digit.
032UU // illegal: cannot repeat a suffix.

Following are other examples of various types of Integer literals:

85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int

12
30u // unsigned int
30l // long
30ul // unsigned long

3.5.2. Floating-point literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or
both and while representing using exponential form; you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals:

3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction

3.5.3. Boolean literals

There are two Boolean literals and they are part of standard C++ keywords:
 A value of true representing true.
 A value of false representing false.
You should not consider the value of true equal to 1 and value of false equal to 0.

3.5.4. Character literals


Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is
a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise, it
is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').

13
There are certain characters in C++ when they are preceded by a backslash they will have special
meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some
of such escape sequence codes:

Escape Meaning
sequence
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits

Following is the example to show few escape sequence characters:

#include <iostream>
Using namespace std;
int main()
{
cout << "Hello\tWorld\n\n";
return 0; }
When the above code is compiled and executed, it produces the following result:
Hello World

3.5.5. String literals:

14
String literals are enclosed in double quotes. A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separate them using
whitespaces.
Here are some examples of string literals. All the three forms are identical strings.

"hello, dear" dear"

"hello, \ "hello, " "d" "ear"


3.5.6. Expressions and Statements
A. Statement: A statement is a block of code that does something or some action to be carried
out. An assignment statement assigns a value to a variable. A for statement performs a loop.
All C++ statements end with a semicolon.
E.g.: x = a + b; //The meaning is: assign the value of the sum of a and b to x.
B. Block: A block (or a compound statement) is a group of statements surrounded by braces
{ }. All the statements inside the block are treated as one unit. Blocks are used as the body in
constructs like function, if-else and loop, which may contain multiple statements but are
treated as one unit.
// each of the followings is a "complex" statement comprising one or more blocks of
statements.
// No terminating semi-colon needed after the closing brace to end the "complex" statement.
// Take note that a "complex" statement is usually written over a few lines for readability.
if (mark >= 50)
{
cout << "PASS" << endl;
cout << "Well Done!" << endl;
cout << "Keep it Up!" << endl;
}
if (number == 88) {
cout << "Got it" << endl;
} else {

15
cout << "Try Again" << endl; }
C. White spaces: Blank, tab and new-line are collectively called white spaces. C++, like most
of the computing languages, ignores extra white spaces. That is, multiple contiguous white
spaces are treated as a single white space. You need to use a white space to separate two
keywords or tokens, e.g.,
int sum=0; // Need a white space between int and sum
double average; // Need a white space between double and average
average=sum/100.0;

Additional white spaces and extra lines are, however, ignored, e.g.,

// same as above
int sum
= 0;
double average ;
average = sum / 100.0;
D. Expressions: an expression is a computation which yields a value. It can also be viewed as
any statement that evaluates to a value (returns a value). Expression is a combination of
literals, variables, operators and functions that is evaluated and returns a value.
E.g.: the statement 3+2; returns the value 5 and thus is an expression.
Some examples of an expression:
E.g.1:
3.2 returns the value 3.2
PI float constant that returns the value 3.14 if the constant is defined.
secondsPerMinute integer constant that returns 60 if the constant is declared
E.g.2: complicated expressions:
x = a + b;
y = x = a + b;
The second line is evaluated in the following order:
1. Add a to b.
2. Assign the result of the expression a + b to x.
3. Assign the result of the assignment expression x = a + b to y.

16
If all operands (that is, numbers) in an expression are integers, the expression is called an integral
expression. If all operands in an expression are floating-point numbers, the expression is called a
floating-point or decimal expression.
E. PUNCTUATORS
Punctuators are also called as separators The Followings are used as punctuators
 Brackets []  Colon :
 Parantheses ()  Asterisk *
 Braces {}  Ellipsis …
 Comma ,  Equal Sign =
 Semicolon ;  Pound Sign #

3.6. Operators and operator

An operation is an action performed on one or more values either to modify the value held by
one or both of the variables or to produce a new value by combining variables. Therefore, an
operation is performed using at least one symbol and one value. The symbol used in an operation
is called an operator. A variable or a value involved in an operation is called an operand.

A unary operator is an operator that performs its operation on only one operand.
An operator is referred to as binary if it operates on two operands

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides the following types of operators:

 Assignment Operators  Bitwise Operators


 Arithmetic Operators  Conditional Operator (? :)
 Increment and Decrement Operators
 Coma Operator
 Relational Operators
 Precedence of operators
 Logical Operators
 Explicit type casting operators.

3.6.1. Assignment Operators (=)

The assignment operator assigns a value to a variable.

x = 5;

17
This statement assigns the integer value 5 to the variable x. The assignment operation always
takes place from right to left, and never the other way around:

x = y;
This statement assigns to variable x the value contained in variable y. The value of x at the
moment this statement is executed is lost and replaced by the value of y.
Consider also that we are only assigning the value of y to x at the moment of the assignment
operation. Therefore, if y changes at a later moment, it will not affect the new value taken by x.
For example, let's have a look at the following code - I have included the evolution of the content
stored in the variables as comments:

// assignment operator
#include <iostream>
Using namespace std;
int main () {
int a, b; // a:?, b:?
a = 10; // a: 10, b:
b = 4; // a:10, b:4
a:4 b:7
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
}

This program prints on screen the final values of a and b (4 and 7, respectively). Notice how a
was not affected by the final modification of b, even though we declared a = b earlier.
Assignment operations are expressions that can be evaluated. That means that the assignment
itself has a value, and -for fundamental types- this value is the one assigned in the operation. For
example:

18
y = 2 + (x = 5);
In this expression, y is assigned the result of adding 2 and the value of another assignment
expression (which has itself a value of 5). It is roughly equivalent to:

x = 5;
y = 2 + x;
With the final result of assigning 7 to y. The following expression is also valid in C++:

x = y = z = 5;

It assigns 5 to the all three variables: x, y and z; always from right-to-left.

3.6.2. Arithmetic operators (+, -, *, /, %)


The five arithmetical operations supported by C++ are:

operator description
+ addition
- subtraction
* multiplication
/ division
% modulo

Operations of addition, subtraction, multiplication and division correspond literally to their


respective mathematical operators
The module(%) is an operator that gives the remainder of a division of two integer values. For
instance, 13 % 3 is calculated by integer dividing 13 by 3 to give an outcome of 4 and a
remainder of 1; the result is therefore 1. E.g.:
a = 11 % 3 a is 2 //The modulus operator, %, takes only integer operands.
It is possible for the outcome of an arithmetic operation to be too large for storing in a designated
variable. This situation is called an overflow. The outcome of an overflow is machine-dependent
and therefore undefined. For example:
unsigned char k = 10 * 92; // overflow: 920 > 255
3.6.3. Increment and Decrement Operators

19
These operators are used frequently by C++ programmers and are useful programming tools.
Suppose count is an int variable. The statement:
count = count + 1; increments the value of count by 1. To execute this assignment statement, the
computer first evaluates the expression on the right, which is count + 1. It then assigns this value
to the variable on the left, which is count.
C++ provides the increment operator, ++, which increases the value of a variable by 1, and the
decrement operator, ––, which decreases the value of a variable by 1.
Increment and decrement operators each have two forms, pre and post. The syntax of the
increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
Let’s look at some examples. The statement:
++count;
or:
count++;
increments the value of count by 1. Similarly, the statement:
––count;
or:
count––;
decrements the value of count by 1.
Because both the increment and decrement operators are built into C++, the value of the variable
is quickly incremented or decremented without having to use the form of an assignment
statement.
If ++x is used in an expression, first the value of x is incremented by 1, and then the new value
of x is used to evaluate the expression. On the other hand, if x++ is used in an expression, first
the current value of x is used in the expression, and then the value of x is incremented by 1. The
following example clarifies the difference between the pre- and post-increment operators.
Suppose that x and y is int variables. Consider the following statements:

20
x = 5;
y = ++x;
The first statement assigns the value 5 to x. To evaluate the second statement, which uses
the pre-increment operator, first the value of x is incremented to 6, and then this value,
6, is assigned to y. After the second statement executes, both x and y have the value 6.
x = 5;
y = x++;
As before, the first statement assigns 5 to x. In the second statement, the post-increment operator
is applied to x. To execute the second statement, first the value of x, which is 5, is used to
evaluate the expression, and then the value of x is incremented to 6. Finally, the value of the
expression, which is 5, is stored in y. After the second statement executes, the value of x is 6, and
the value of y is 5.

3.6.4. Relational Operators

There are following relational operators supported by C++ language.

Assume variable A holds 10 and variable B holds 20, then:

Operato Description Example


r
== Checks if the values of two operands (A == B) is not true.
are equal or not, if yes then condition
becomes true.
!= Checks if the values of two operands (A != B) is true.
are equal or not, if values are not equal
then condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand,
if yes then condition becomes true.
< Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if

21
yes then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of
right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is (A <= B) is true.
less than or equal to the value of right
operand, if yes then condition becomes
true.

The following example shows the rational operators.


#include <iostream>
Using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
cout << "Line 1 - a is equal to b" << endl ; }
else {
cout << "Line 1 - a is not equal to b" << endl ; }
if ( a < b ) {
cout << "Line 2 - a is less than b" << endl ; }
else {
cout << "Line 2 - a is not less than b" << endl ; }
if ( a > b ) {
cout << "Line 3 - a is greater than b" << endl ; }
else {
cout << "Line 3 - a is not greater than b" << endl ; }
/* Let's change the values of a and b */
a = 5;

22
b = 20;
if ( a <= b ) {
cout << "Line 4 - a is either less than \
or euqal to b" << endl ; }
if ( b >= a ) {
cout << "Line 5 - b is either greater than \
or equal to b" << endl ; }
return 0; }

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

Line 1 - a is not equal to b


Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

3.6.5. Logical Operators (! &&, ||)

The operator is the C++ operator for the Boolean operation NOT. It has only one operand, to its
right, and inverts it, producing false if its operand is true and true if its operand is false.
Basically, it returns the opposite Boolean value of evaluating its operand. For example:

1 !(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true


2 !(6 <= 4) // evaluates to true because (6 <= 4) would be false
3 !true // evaluates to false
4 !false // evaluates to true
The logical operators && and || are used when evaluating two expressions to obtain a single
relational result. The operator && corresponds to the Boolean logical operation AND, which
yields true if both its operands are true, and false otherwise. The following panel shows the result
of operator && evaluating the expression a&&b:

&& OPERATOR (and)

23
a b a && b
true true true
true false false
false true false
false false false

The operator || corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results
of a||b:

|| OPERATOR (or)
a b a || b
true true true
true false true
false true true
false false false

For example:
1 ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false )
2 ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false )
When using the logical operators, C++ only evaluates what is necessary from left to right to
come up with the combined relational result, ignoring the rest. Therefore, in the last example
((5==5) || (3>6)), C++ evaluates first whether 5==5 is true, and if so, it never checks whether
3>6 is true or not. This is known as short-circuit evaluation, and works like this for these
operators:

operato short-circuit
r
&& If the left-hand side expression is false, the combined result is false (the right-hand
side expression is never evaluated).
|| If the left-hand side expression is true, the combined result is true (the right-hand side

24
expression is never evaluated).

This is mostly important when the right-hand expression has side effects, such as altering values:

if ( (i<10) && (++i<n) ) { /*...*/ } // note that the condition increments i


Here, the combined conditional expression would increase i by one, but only if the condition on
the left of && is true, because otherwise, the condition on the right-hand side (++i<n) is never
evaluated.

3.6.6. Bitwise Operators:

Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, and ^
are as follows:

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

25
The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then:

Operato Description Example


r
& Binary AND Operator copies a bit to the (A & B) will give 12 which is 0000 1100
result if it exists in both operands.
| Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011 1101
exists in either operand.
^ Binary XOR Operator copies the bit if it (A ^ B) will give 49 which is 0011 0001
is set in one operand but not both.
~ Binary Ones Complement Operator is (~A) will give -61 which is 1100 0011 in
unary and has the effect of 'flipping' bits. 2's complement form due to a signed
binary number.
<< Binary Left Shift Operator. The left A << 2 will give 240 which is 1111 0000
operands value is moved left by the
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left A >> 2 will give 15 which is 0000 1111
operands value is moved right by the
number of bits specified by the right
operand.

The following examples shows bitwise operator

#include <iostream>
main() {
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;
c = a & b; // 12 = 0000 1100
cout << "Line 1 - Value of c is : " << c << endl ;

26
c = a | b; // 61 = 0011 1101
cout << "Line 2 - Value of c is: " << c << endl ;
c = a ^ b; // 49 = 0011 0001
cout << "Line 3 - Value of c is: " << c << endl ;
c = ~a; // -61 = 1100 0011
cout << "Line 4 - Value of c is: " << c << endl ;
c = a << 2; // 240 = 1111 0000
cout << "Line 5 - Value of c is: " << c << endl ;
c = a >> 2; // 15 = 0000 1111
cout << "Line 6 - Value of c is: " << c << endl ;
return 0; }
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is: 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15
3.6.7. Conditional Operator (? :)
The conditional operator takes three operands. It has the general form: Syntax:
operand1? operand2: operand3
First operand1 is a relational expression and will be evaluated. If the result of the evaluation is
non zero (which means TRUE), then operand2 will be the final result. Otherwise, operand3 is the
final result.
E.g.: General Example
Z=(X<Y? X : Y)
This expression means that if X is less than Y the value of X will be assigned to Z otherwise (if
X>=Y) the value of Y will be assigned to Z.
E.g.: int m=1,n=2,min;
min = (m < n ? m : n);
The value stored in min is 1.

27
E.g.: (7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5

3.6.8. Comma operator (,)


The comma operator (,) is used to separate two or more expressions that are included where only
one expression is expected. When the set of expressions has to be evaluated for a value, only the
right-most expression is considered.
For example, the following code:
a = (b=3, b+2);
would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a
would contain the value 5 while variable b would contain value 3.

3.6.9. Sizeof
This operator accepts one parameter, which can be either a type or a variable, and returns the size
in bytes of that type or object:

x = sizeof (char);
Here, x is assigned the value 1, because char is a type with a size of one byte. The value returned
by sizeof is a compile-time constant, so it is always determined before program execution.
3.6.9. Precedence of operators
From greatest to smallest priority, C++ operators are evaluated in the following order.
Level Precedence group Operator Description Grouping
1 Scope :: scope qualifier Left-to-right
2 Postfix (unary) ++ -- postfix increment / Left-to-right
decrement
() functional forms
[] Subscript
. -> member access
3 Prefix (unary) ++ -- prefix increment / Right-to-left
decrement
~! bitwise NOT / logical NOT
+- unary prefix
&* reference / dereference

28
new delete allocation / deallocation
sizeof parameter pack
(type) C-style type-casting
4 Pointer-to-member .* ->* access pointer Left-to-right
5 Arithmetic: scaling */% multiply, divide, modulo Left-to-right
6 Arithmetic: +- addition, subtraction Left-to-right
addition
7 Bitwise shift << >> shift left, shift right Left-to-right
8 Relational < > <= >= comparison operators Left-to-right
9 Equality == != equality / inequality Left-to-right
10 And & bitwise AND Left-to-right
11 Exclusive or ^ bitwise XOR Left-to-right
12 Inclusive or | bitwise OR Left-to-right
13 Conjunction && logical AND Left-to-right
14 Disjunction || logical OR Left-to-right
15 Assignment-level = *= /= %= += - assignment / Right-to-left
expressions = compound assignment
>>= <<= &= ^= |
=
?: conditional operator
16 Sequencing , comma separator Left-to-right

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>
Using namespace std;
main() {
int a = 20;
int b = 10;

29
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 ;
return 0; }

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
3.7. Explicit and implicit type casting operators.
The built-in type identifiers can be used as type operators. Type operators are unary (i.e., take
one operand) and appear inside brackets to the left of their operand. This is called explicit type
conversion.
When the type name is just one word, an alternate notation may be used in which the brackets
appear around the operand:
E.g. int (3.14) // same as: (int) 3.14

(int) 3.14 // converts 3.14 to an int to give 3


(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is 122
(unsigned short) 3.14 // gives 3 as an unsigned short

30
In some cases, C++ also performs implicit type conversion. This happens when values of
different types are mixed in an expression. For example:
double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d; // means: i = int(double(i) + d)
In the last example, i + d involves mismatching types, so i is first converted to double (promoted)
and then added to d. The result is a double which does not match the type of i on the left side of
the assignment, so it is converted to int (demoted) before being assigned to i.

*****************************End *************************

31

You might also like