SlideShare a Scribd company logo
OBJECT ORIENTED PROGRAMMING
WITH C++
Tokens, Expressions and
Control Structures
Tokens
A token is a language element that can be used in
constructing higher-level language constructs.
C++ has the following Tokens:
 Keywords (Reserved words)
 Identifiers
 Constants
 Strings (String literals)
 Punctuators
 Operators
Keywords
Implements specific C++ language features.
They are explicitly reserved identifiers and cannot be used as
names for the program variables or other user-defined program
elements.
Following table is a list of keywords in C++:
asm delete if return try
auto do inline short typedef
break double int signed union
case else long sizeof unsigned
catch enum new static virtual
char extern operator struct void
class float private switch volatile
const for protected template while
continue friend public this
default goto register throw
Identifiers
Identifiers refer to the names of variables, functions, arrays, classes
etc.
Rules for constructing identifiers:
 Only alphabetic characters, digits and underscores are permitted.
 The name cannot start with a digit.
 Uppercase and lowercase letters are distinct.
 A declared keyword cannot be used as a variable name.
 There is virtually no length limitation. However, in many
implementations of C++ language, the compilers recognize only the first
32 characters as significant.
 There can be no embedded blanks.
Constants
Constants are entities that appear in the program code as fixed
values.
There are four classes of constants in C++:
 Integer
 Floating-point
 Character
 Enumeration
Integer Constants
 Positive or negative whole numbers with no fractional part.
 Commas are not allowed in integer constants.
 E.g.: const int size = 15;
const length = 10;
 A const in C++ is local to the file where it is created.
 To give const value external linkage so that it can be referenced from
another file, define it as an extern in C++.
 E.g.: extern const total = 100;
Constants
Floating-point Constants
 Floating-point constants are positive or negative decimal numbers with
an integer part, a decimal point, and a fractional part.
 They can be represented either in conventional or scientific notation.
 For example, the constant 17.89 is written in conventional notation. In
scientific notation it is equivalent to 0.1789X102. This is written as
0.1789E+2 or as 0.1789e+2. Here, E or e stands for ‘exponent’.
 Commas are not allowed.
 In C++ there are three types of floating-point constants:
float - f or F 1.234f3 or 1.234F3
double - e or E 2.34e3 or 2.34E3
long double - l or L 0.123l5 or 0.123L5
Character Constant
 A Character enclosed in single quotation marks.
 E.g. : ‘A’, ‘n’
Constants
Enumeration
 Provides a way for attaching names to numbers.
 E.g.:
enum {X,Y,Z} ;
 The above example defines X,Y and Z as integer constants with values
0,1 and 2 respectively.
 Also can assign values to X, Y and Z explicitly.
enum { X=100, Y=50, Z=200 };
Strings
A String constant is a sequence of any number of characters
surrounded by double quotation marks.
E.g.:
“This is a string constant.”
Punctuators
Punctuators in C++ are used to delimit various syntactical units.
The punctuators (also known as separators) in C++ include the
following symbols:
[ ] ( ) { } , ; : … * #
Basic Data Types
Size and Range of Data Types
Basic Data Types
ANSI C++ added two more data types
 bool
 wchar_t
Data Type - bool
A variable with bool type can hold a Boolean value true
or false.
Declaration:
bool b1; // declare b1 as bool type
b1 = true; // assign true value to b1
bool b2 = false; // declare and initialize
The default numeric value of true is 1 and
false is 0.
Data Type – wchar_t
The character type wchar_t has been defined to
hold 16-bit wide characters.
wide_character uses two bytes of memory.
wide_character literal in C++
begin with the letter L
L‘xy’ // wide_character literal
Built-in Data Types
int, char, float, double are known as basic or
fundamental data types.
Signed, unsigned, long, short modifier for integer
and character basic data types.
Long modifier for double.
Built-in Data Types
Type void was introduced in ANSI C.
Two normal use of void:
o To specify the return type of a function when it is
not returning any value.
o To indicate an empty argument list to a function.
o eg:- void function-name ( void )
Built-in Data Types
Type void can also used for declaring generic pointer.
A generic pointer can be assigned a pointer value of any
basic data type, but it may not be de-referenced.
void *gp; // gp becomes generic pointer
int *ip; // int pointer
gp = ip; // assign int pointer to void pointer
Assigning any pointer type to a void pointer is allowed
in C .
Built-in Data Types
void *gp; // gp becomes generic pointer
int *ip; // int pointer
ip = gp; // assign void pointer to int pointer
This is allowed in C. But in C++ we need to use a cast
operator to assign a void pointer to other type
pointers.
ip = ( int * ) gp; // assign void pointer to int pointer
// using cast operator
*ip = *gp;  is illegal
User-Defined Data Types
Structures & Classes:
struct
union
class
Legal data types in C++.
Like any other basic data type to declare variables.
The class variables are known as objects.
User-Defined Data Types
User-Defined Data Types
Enumerated DataType:
Enumerated data type provides a way for attaching
names to numbers.
enum keyword automatically enumerates a list of
words by assigning them values 0, 1, 2, and so on.
enum shape {circle, square, triangle};
enum colour {red, blue, green, yellow};
enum position {off, on};
User-Defined Data Types
Enumerated DataType:
enum colour {red, blue, green, yellow};
In C++ the tag names can be used to declare
new variables.
colour background;
In C++ each enumerated data type retains its
own separate type.C++ does not permit an int
value to be automatically converted to an enum
value.
User-Defined Data Types
Enumerated DataType:
colour background = blue; // allowed
colour background = 1; // error in C++
colour background = (colour) 1; // OK
int c = red; // valid
Derived Data Types
Arrays
The application of arrays in C++ is similar to that
in C.
Functions
top-down - structured programming ; to reduce
length of the program ; reusability ; function
over-loading.
Derived Data Types
Pointers
Pointers can be declared and initialized as in C.
int * ip; // int pointer
ip = &x; // address of x assigned to ip
*ip = 10; // 10 assigned to x through indirection
Derived Data Types
Pointers
C++ adds the concept of constant pointer and
pointer to a constant.
char * const ptr1 = “GOODS”; // constant pointer
int const * ptr2 = &m; // pointer to a constant
Symbolic Constants
Two ways of creating symbolic constant in C++.
Using the qualifier const
Defining a set of integer constants using enum
keyword.
Any value declared as const can not be modified by
the program in any way. In C++, we can use const in
a constant expression.
const int size = 10;
char name[size]; //This is illegal in C.
Symbolic Constants
const allows us to create typed constants.
#define - to create constants that have no type
information.
The named constants are just like variables except that
their values can not be changed. C++ requires a const to
be initialized.
A const in C++ defaults, it is local to the file where it is
declared.To make it global the qualifier extern is used.
Symbolic Constants
extern const int total = 100;
enum { X,Y, Z };
This is equivalent to
const int X = 0;
const intY = 1;
const int Z = 2;
Reference Variables
A reference variable provides an alias for a
previously defined variable.
For eg., if we make the variable sum a reference to
the variable total, then sum and total can be used
interchangeably to represent that variable.
data-type & reference-name = variable-name
float total = 100;
float &sum = total;
Reference Variables
A reference variable must be initialized at the time
of declaration.This establishes the correspondence
between the reference and the data object which it
names.
int x ;
int *p = &x ;
int & m = *p ;
continue…
Reference Variables
void f ( int & x )
{
x = x + 10;
}
int main ( )
{
int m = 10;
f (m);
}
continue…
When the function call f(m) is
executed,
int & x = m;
Operators
Operators are tokens that result in some kind of computation or
action when applied to variables or other elements in an expression.
Some examples of operators are:
( ) ++ -- * / % + - << >> < <= > >= ==
!= = += -= *= /= %=
Operators act on operands. For example, CITY_RATE,
gross_income are operands for the multiplication operator, * .
An operator that requires one operand is a unary operator, one that
requires two operands is binary, and an operator that acts on three
operands is ternary.
Dynamic initialization of variables
Dynamic Initialization refers to initializing a variable at
runtime. If you give a C++ statement as shown below, it
refers to static initialization, because you are assigning
a constant to the variable which can be resolved at
compile time.
Int x = 5;
Whereas, the following statement is called dynamic
initialization, because it cannot be resolved at compile
time.
In x = a * b;
Initializing x requires the value of a and b. So it can be
resolved only during run time.
Arithmetic Operators
The basic arithmetic operators in C++ are the same as in most other
computer languages.
Following is a list of arithmetic operators in C++:
Modulus Operator: a division operation where two integers are divided and
the remainder is the result.
E.g.: 10 % 3 results in 1, 12 % 7 results in 5 and 20 % 5 results in 0.
Integer Division: the result of an integer divided by an integer is always an
integer (the remainder is truncated).
E.g.: 10/3 results in 3, 14/5 results in 2 and 1/2 results in 0.
1./2. or 1.0/2.0 results in 0.5
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Assignment Operators
E.g.:
x = x + 3; x + = 3;
x = x - 3; x - = 3;
x = x * 3; x * = 3;
x = x / 3; x / = 3;
Increment & Decrement Operators
Name of the operator Syntax Result
Pre-increment ++x Increment x by 1 before use
Post-increment x++ Increment x by 1 after use
Pre-decrement --x Decrement x by 1 before use
Post-decrement x-- Decrement x by 1 before use
E.g.:
int x=10, y=0;
y=++x; ( x = 11, y = 11)
y=x++;
y=--x;
y=x--;
y=++x-3; y=x+++5; y=--x+2; y=x--+3;
Relational Operators
Using relational operators we can direct the computer to compare two
variables.
Following is a list of relational operators:
E.g.: if (thisNum < minimumSoFar) minimumSoFar = thisNum
if (numberOfLegs != 8) thisBug = insect
In C++ the truth value of these expressions are assigned numerical values:
a truth value of false is assigned the numerical value zero and the value
true is assigned a numerical value best described as not zero.
Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operators
Logical operators in C++, as with other computer languages, are used to
evaluate expressions which may be true or false.
Expressions which involve logical operations are evaluated and found to be
one of two values: true or false.
Examples of expressions which contain relational and logical operators
if ((bodyTemp > 100) && (tongue == red)) status = flu;
Operator Meaning Example of use Truth Value
&& AND (exp 1) && (exp 2) True if exp 1 and exp 2 are BOTH true.
|| OR (exp 1) || (exp 2) True if EITHER (or BOTH) exp 1 or exp 2
are true.
! NOT ! (exp 1) Returns the opposite truth value of exp 1;
if exp 1 is true, ! (exp 1) is false; if exp 1
is false, ! (exp 1) is true.
Operator Precedence
Following table shows the precedence and associativity of all the
C++ operators. (Groups are listed in order of decreasing
precedence.)
Operator Associativity
:: left to right
-> . ( ) [ ] postfix ++ postfix -- left to right
prefix ++ prefix -- ~ ! unary + unary –
Unary * unary & (type) sizeof new delete
right to left
->* * left to right
* / % left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right
^ left to right
| left to right
Operator Precedence Contd…
Operator Associativity
&& left to right
|| left to right
?: left to right
= *= /= %= += -=
<<= >>= &= ^= |=
right to left
, left to right

More Related Content

PPTX
Introduction to java
DOC
E drejta detyrimore 10 teste
PPTX
Course outline for c programming
PPTX
Programming Fundamentals With OOPs Concepts (Java Examples Based)
PDF
Chap 2 c++
PDF
2 expressions (ppt-2) in C++
PPT
Key Concepts of C++ computer language.ppt
PDF
Keywords, identifiers ,datatypes in C++
Introduction to java
E drejta detyrimore 10 teste
Course outline for c programming
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Chap 2 c++
2 expressions (ppt-2) in C++
Key Concepts of C++ computer language.ppt
Keywords, identifiers ,datatypes in C++

Similar to Object Oriented Programming with C++ (20)

PPT
Data Handling
PDF
2.Types_Variables_Functions.pdf
PDF
PPT
Basic of c &c++
PDF
BASIC C++ PROGRAMMING
PPTX
Concept of c data types
PPT
Cpp tokens (2)
PPT
01 c++ Intro.ppt
PDF
Introduction to c++ ppt
PPT
Lecture+06-TypesVars.ppt
PPT
Lecture06-TypesVarsConsts variables data types
PPTX
INTRODUCTION TO C++.pptx
PPT
Basics of c++
PPTX
Datatype in c++ unit 3 -topic 2
PPTX
Programming Fundamentals
PDF
THE C++ LECTURE 2 ON DATA STRUCTURES OF C++
PPTX
introductiontocprogramming datatypespp.pptx
PPTX
Introduction to c++ programming language
PDF
Introduction of C++ By Pawan Thakur
PPTX
Chapter 2.datatypes and operators
Data Handling
2.Types_Variables_Functions.pdf
Basic of c &c++
BASIC C++ PROGRAMMING
Concept of c data types
Cpp tokens (2)
01 c++ Intro.ppt
Introduction to c++ ppt
Lecture+06-TypesVars.ppt
Lecture06-TypesVarsConsts variables data types
INTRODUCTION TO C++.pptx
Basics of c++
Datatype in c++ unit 3 -topic 2
Programming Fundamentals
THE C++ LECTURE 2 ON DATA STRUCTURES OF C++
introductiontocprogramming datatypespp.pptx
Introduction to c++ programming language
Introduction of C++ By Pawan Thakur
Chapter 2.datatypes and operators
Ad

More from Rokonuzzaman Rony (20)

PPTX
PPTX
Operator Overloading & Type Conversions
PPTX
Constructors & Destructors
PPTX
Classes and objects in c++
PPTX
Functions in c++
PPTX
Humanitarian task and its importance
PPTX
PPTX
PPTX
Introduction to C programming
PPTX
Constants, Variables, and Data Types
PPTX
C Programming language
PPTX
User defined functions
PPTX
Numerical Method 2
PPT
Numerical Method
PPTX
Data structures
PPT
Data structures
PPTX
Data structures
PPTX
Counting DM
Operator Overloading & Type Conversions
Constructors & Destructors
Classes and objects in c++
Functions in c++
Humanitarian task and its importance
Introduction to C programming
Constants, Variables, and Data Types
C Programming language
User defined functions
Numerical Method 2
Numerical Method
Data structures
Data structures
Data structures
Counting DM
Ad

Recently uploaded (20)

PPTX
Cell Structure & Organelles in detailed.
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Business Ethics Teaching Materials for college
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Onica Farming 24rsclub profitable farm business
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PDF
01-Introduction-to-Information-Management.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Structure & Organelles in detailed.
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Insiders guide to clinical Medicine.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Week 4 Term 3 Study Techniques revisited.pptx
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Business Ethics Teaching Materials for college
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharma ospi slides which help in ospi learning
Onica Farming 24rsclub profitable farm business
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
01-Introduction-to-Information-Management.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Open Quiz Monsoon Mind Game Final Set.pptx
Renaissance Architecture: A Journey from Faith to Humanism
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
STATICS OF THE RIGID BODIES Hibbelers.pdf

Object Oriented Programming with C++

  • 1. OBJECT ORIENTED PROGRAMMING WITH C++ Tokens, Expressions and Control Structures
  • 2. Tokens A token is a language element that can be used in constructing higher-level language constructs. C++ has the following Tokens:  Keywords (Reserved words)  Identifiers  Constants  Strings (String literals)  Punctuators  Operators
  • 3. Keywords Implements specific C++ language features. They are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements. Following table is a list of keywords in C++: asm delete if return try auto do inline short typedef break double int signed union case else long sizeof unsigned catch enum new static virtual char extern operator struct void class float private switch volatile const for protected template while continue friend public this default goto register throw
  • 4. Identifiers Identifiers refer to the names of variables, functions, arrays, classes etc. Rules for constructing identifiers:  Only alphabetic characters, digits and underscores are permitted.  The name cannot start with a digit.  Uppercase and lowercase letters are distinct.  A declared keyword cannot be used as a variable name.  There is virtually no length limitation. However, in many implementations of C++ language, the compilers recognize only the first 32 characters as significant.  There can be no embedded blanks.
  • 5. Constants Constants are entities that appear in the program code as fixed values. There are four classes of constants in C++:  Integer  Floating-point  Character  Enumeration Integer Constants  Positive or negative whole numbers with no fractional part.  Commas are not allowed in integer constants.  E.g.: const int size = 15; const length = 10;  A const in C++ is local to the file where it is created.  To give const value external linkage so that it can be referenced from another file, define it as an extern in C++.  E.g.: extern const total = 100;
  • 6. Constants Floating-point Constants  Floating-point constants are positive or negative decimal numbers with an integer part, a decimal point, and a fractional part.  They can be represented either in conventional or scientific notation.  For example, the constant 17.89 is written in conventional notation. In scientific notation it is equivalent to 0.1789X102. This is written as 0.1789E+2 or as 0.1789e+2. Here, E or e stands for ‘exponent’.  Commas are not allowed.  In C++ there are three types of floating-point constants: float - f or F 1.234f3 or 1.234F3 double - e or E 2.34e3 or 2.34E3 long double - l or L 0.123l5 or 0.123L5 Character Constant  A Character enclosed in single quotation marks.  E.g. : ‘A’, ‘n’
  • 7. Constants Enumeration  Provides a way for attaching names to numbers.  E.g.: enum {X,Y,Z} ;  The above example defines X,Y and Z as integer constants with values 0,1 and 2 respectively.  Also can assign values to X, Y and Z explicitly. enum { X=100, Y=50, Z=200 };
  • 8. Strings A String constant is a sequence of any number of characters surrounded by double quotation marks. E.g.: “This is a string constant.”
  • 9. Punctuators Punctuators in C++ are used to delimit various syntactical units. The punctuators (also known as separators) in C++ include the following symbols: [ ] ( ) { } , ; : … * #
  • 11. Size and Range of Data Types
  • 12. Basic Data Types ANSI C++ added two more data types  bool  wchar_t
  • 13. Data Type - bool A variable with bool type can hold a Boolean value true or false. Declaration: bool b1; // declare b1 as bool type b1 = true; // assign true value to b1 bool b2 = false; // declare and initialize The default numeric value of true is 1 and false is 0.
  • 14. Data Type – wchar_t The character type wchar_t has been defined to hold 16-bit wide characters. wide_character uses two bytes of memory. wide_character literal in C++ begin with the letter L L‘xy’ // wide_character literal
  • 15. Built-in Data Types int, char, float, double are known as basic or fundamental data types. Signed, unsigned, long, short modifier for integer and character basic data types. Long modifier for double.
  • 16. Built-in Data Types Type void was introduced in ANSI C. Two normal use of void: o To specify the return type of a function when it is not returning any value. o To indicate an empty argument list to a function. o eg:- void function-name ( void )
  • 17. Built-in Data Types Type void can also used for declaring generic pointer. A generic pointer can be assigned a pointer value of any basic data type, but it may not be de-referenced. void *gp; // gp becomes generic pointer int *ip; // int pointer gp = ip; // assign int pointer to void pointer Assigning any pointer type to a void pointer is allowed in C .
  • 18. Built-in Data Types void *gp; // gp becomes generic pointer int *ip; // int pointer ip = gp; // assign void pointer to int pointer This is allowed in C. But in C++ we need to use a cast operator to assign a void pointer to other type pointers. ip = ( int * ) gp; // assign void pointer to int pointer // using cast operator *ip = *gp;  is illegal
  • 19. User-Defined Data Types Structures & Classes: struct union class Legal data types in C++. Like any other basic data type to declare variables. The class variables are known as objects.
  • 21. User-Defined Data Types Enumerated DataType: Enumerated data type provides a way for attaching names to numbers. enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2, and so on. enum shape {circle, square, triangle}; enum colour {red, blue, green, yellow}; enum position {off, on};
  • 22. User-Defined Data Types Enumerated DataType: enum colour {red, blue, green, yellow}; In C++ the tag names can be used to declare new variables. colour background; In C++ each enumerated data type retains its own separate type.C++ does not permit an int value to be automatically converted to an enum value.
  • 23. User-Defined Data Types Enumerated DataType: colour background = blue; // allowed colour background = 1; // error in C++ colour background = (colour) 1; // OK int c = red; // valid
  • 24. Derived Data Types Arrays The application of arrays in C++ is similar to that in C. Functions top-down - structured programming ; to reduce length of the program ; reusability ; function over-loading.
  • 25. Derived Data Types Pointers Pointers can be declared and initialized as in C. int * ip; // int pointer ip = &x; // address of x assigned to ip *ip = 10; // 10 assigned to x through indirection
  • 26. Derived Data Types Pointers C++ adds the concept of constant pointer and pointer to a constant. char * const ptr1 = “GOODS”; // constant pointer int const * ptr2 = &m; // pointer to a constant
  • 27. Symbolic Constants Two ways of creating symbolic constant in C++. Using the qualifier const Defining a set of integer constants using enum keyword. Any value declared as const can not be modified by the program in any way. In C++, we can use const in a constant expression. const int size = 10; char name[size]; //This is illegal in C.
  • 28. Symbolic Constants const allows us to create typed constants. #define - to create constants that have no type information. The named constants are just like variables except that their values can not be changed. C++ requires a const to be initialized. A const in C++ defaults, it is local to the file where it is declared.To make it global the qualifier extern is used.
  • 29. Symbolic Constants extern const int total = 100; enum { X,Y, Z }; This is equivalent to const int X = 0; const intY = 1; const int Z = 2;
  • 30. Reference Variables A reference variable provides an alias for a previously defined variable. For eg., if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent that variable. data-type & reference-name = variable-name float total = 100; float &sum = total;
  • 31. Reference Variables A reference variable must be initialized at the time of declaration.This establishes the correspondence between the reference and the data object which it names. int x ; int *p = &x ; int & m = *p ; continue…
  • 32. Reference Variables void f ( int & x ) { x = x + 10; } int main ( ) { int m = 10; f (m); } continue… When the function call f(m) is executed, int & x = m;
  • 33. Operators Operators are tokens that result in some kind of computation or action when applied to variables or other elements in an expression. Some examples of operators are: ( ) ++ -- * / % + - << >> < <= > >= == != = += -= *= /= %= Operators act on operands. For example, CITY_RATE, gross_income are operands for the multiplication operator, * . An operator that requires one operand is a unary operator, one that requires two operands is binary, and an operator that acts on three operands is ternary.
  • 34. Dynamic initialization of variables Dynamic Initialization refers to initializing a variable at runtime. If you give a C++ statement as shown below, it refers to static initialization, because you are assigning a constant to the variable which can be resolved at compile time. Int x = 5; Whereas, the following statement is called dynamic initialization, because it cannot be resolved at compile time. In x = a * b; Initializing x requires the value of a and b. So it can be resolved only during run time.
  • 35. Arithmetic Operators The basic arithmetic operators in C++ are the same as in most other computer languages. Following is a list of arithmetic operators in C++: Modulus Operator: a division operation where two integers are divided and the remainder is the result. E.g.: 10 % 3 results in 1, 12 % 7 results in 5 and 20 % 5 results in 0. Integer Division: the result of an integer divided by an integer is always an integer (the remainder is truncated). E.g.: 10/3 results in 3, 14/5 results in 2 and 1/2 results in 0. 1./2. or 1.0/2.0 results in 0.5 Operator Meaning + Addition - Subtraction * Multiplication / Division % Modulus
  • 36. Assignment Operators E.g.: x = x + 3; x + = 3; x = x - 3; x - = 3; x = x * 3; x * = 3; x = x / 3; x / = 3;
  • 37. Increment & Decrement Operators Name of the operator Syntax Result Pre-increment ++x Increment x by 1 before use Post-increment x++ Increment x by 1 after use Pre-decrement --x Decrement x by 1 before use Post-decrement x-- Decrement x by 1 before use E.g.: int x=10, y=0; y=++x; ( x = 11, y = 11) y=x++; y=--x; y=x--; y=++x-3; y=x+++5; y=--x+2; y=x--+3;
  • 38. Relational Operators Using relational operators we can direct the computer to compare two variables. Following is a list of relational operators: E.g.: if (thisNum < minimumSoFar) minimumSoFar = thisNum if (numberOfLegs != 8) thisBug = insect In C++ the truth value of these expressions are assigned numerical values: a truth value of false is assigned the numerical value zero and the value true is assigned a numerical value best described as not zero. Operator Meaning > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to != Not equal to
  • 39. Logical Operators Logical operators in C++, as with other computer languages, are used to evaluate expressions which may be true or false. Expressions which involve logical operations are evaluated and found to be one of two values: true or false. Examples of expressions which contain relational and logical operators if ((bodyTemp > 100) && (tongue == red)) status = flu; Operator Meaning Example of use Truth Value && AND (exp 1) && (exp 2) True if exp 1 and exp 2 are BOTH true. || OR (exp 1) || (exp 2) True if EITHER (or BOTH) exp 1 or exp 2 are true. ! NOT ! (exp 1) Returns the opposite truth value of exp 1; if exp 1 is true, ! (exp 1) is false; if exp 1 is false, ! (exp 1) is true.
  • 40. Operator Precedence Following table shows the precedence and associativity of all the C++ operators. (Groups are listed in order of decreasing precedence.) Operator Associativity :: left to right -> . ( ) [ ] postfix ++ postfix -- left to right prefix ++ prefix -- ~ ! unary + unary – Unary * unary & (type) sizeof new delete right to left ->* * left to right * / % left to right + - left to right << >> left to right < <= > >= left to right == != left to right & left to right ^ left to right | left to right
  • 41. Operator Precedence Contd… Operator Associativity && left to right || left to right ?: left to right = *= /= %= += -= <<= >>= &= ^= |= right to left , left to right