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:
[ ] ( ) { } , ; : … * #
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
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