You are on page 1of 56

II Unit

Tokens, Expressions and Control


Structures

1
Tokens
A token is the smallest element of a C++ program that is meaningful to
the compiler. The C++ parser recognizes these kinds of tokens:
identifiers, keywords, literals, operators, and other separators.
A stream of these tokens makes up a translation unit. Tokens are usually
separated by "white space." White space can be one or more:

•Blanks

•Horizontal or vertical tabs

•New lines

•Comments

2
C++ Identifiers
An identifier is a sequence of characters used to denote one of the
following:

•Object or variable name


•Class, structure, or union name
•Enumerated type name
•Member of a class, structure, union, or enumeration
•Function or class-member function
•typedef name
•Label name
•Macro name
•Macro parameter
3
The following characters are legal as the first character of an identifier,
or any subsequent character:
a b c d e f g h i j k l m
n o p q r s t u v w x y z
A B C D E F G H I J K L M
N O P Q R S T U V W X Y Z

The following characters are legal as any character in an identifier


except the first:
0 1 2 3 4 5 6 7 8 9

4
EYWORDS

ywords are the reserved words that have predefined meanin


C++. They cannot be used as programmer defined identifier
ce keywords are all lower case, it is possible to utilize an
percase keyword as an identifier. The table lists some of the
++ keywords.

5
KEYWORDS
asm double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typedef
class rand return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while

6
Constant
Constants are used in a C++ program to store information that will not
change while the program is running. They can be one of two general
types:

•literal
•symbolic

These are defined by:

•using the #define key word in the preprocessor


•using the const key word
•creating enumerators

7
Literals
Invariant program elements are called "literals" or "constants." The terms
"literal" and "constant“ are used interchangeably here. Literals fall into
four major categories: integer, character, floating-point, and string literals
A literal may be any of the following:
integer-constant
character-constant
floating-constant
string-literal
Examples
57 // integer constant
0xFE // integer constant
'c' // character constant
0.2 // floating constant
0.2eֿº¹// floating constant
8
"dog" // string literal
Defining C++ Constants with the
Preprocessor
•The preprocessor is run before the program is compiled. It
will look for any lines starting with a hash (#) and will then
modify the code according to what it finds. An example of a
constant defined in the preprocessor is:
•#define pi_val 3.1416
•When the preprocessor runs it will search the code for all
instances of pi_val and replace it with the number 3.1416.

9
Defining C++ Constants with the
const Key Word

• C++ constants can also be defined in the same


way as C++ variables. The only difference is that
the const key word is required:
• const float pi_val = 3.1416;
• One important advantage of using the const key
word to define constants is that the data type will
always be enforced.

10
Defining Enumerated Constants
An enumerated type is a series of named integer values created
by using the enum key word,
for example:
enum DAY {SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
In this example SUNDAY will have the value 0 and
SATURDAY will be 6. However, the values can be initialized:
enum DAY {MONDAY = 1, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY};
This time MONDAY will be 1 and SUNDAY will be 7.

The use of enumerators is clarified by seeing a working example


given in next slide:
11
#include
enum DAY {MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY, SUNDAY};
int main () {
int day;
cout << "Enter day number: ";
cin >> day;
if ((day == SATURDAY) || (day == SUNDAY))
{
cout << "Weekend"; }
else if ((day >= MONDAY) && (day <= FRIDAY))
{
cout << "Working Day";
} else {
cout << "Invalid Number";
}
return 0;
}
If 1 - 5 are input as the day number then the program will output "Working Day" or
"Weekend" for 6 or 7.
12
Operators
The following list contains C++ operators organized by
category.
Additive
Addition: + Subtraction: –
Assignment
Addition Assignment: += Assignment: =
Bitwise AND Assignment: &=
Bitwise exclusive OR Assignment: ^=
Bitwise inclusive OR Assignment: |=
Division Assignment: /=
Left shift assignment: <<=
Modulus Assignment: %=
13
Multiplication Assignment: *=
Right shift assignment: >>=
Subtraction Assignment: –=
Bitwise
Bitwise AND: & Bitwise exclusive OR: ^ Bitwise inclusive OR: |

Logical
Logical AND: && Logical OR: ||

Miscellaneous
Comma: , Conditional: ? : Pointer-to-member: .* or –>*
Reference: & Scope resolution: ::

Multiplicative
Division: / Modulus: % Multiplication: *
Postfix
Subscript: [ ] Function call: ( ) Member access: . and –>
Postfix decrement: –– Postfix increment: ++
14
Relational and Equality
Equality: == Greater than or equal to: >= Greater than: >
Less than or equal to: <= Less than: < Not equal: !=

Shift
Left shift: << Right shift: >>

Unary
Address-of: & delete Indirection: *
Logical Negation: ! new One's Complement: ~
Prefix decrement: –– Prefix increment: ++ sizeof
Unary Plus Operator: + Unary Negation Operator: -

15
String

A string is an array of characters whose last character is \0.


A typical string, such as Pacifique, is graphically
represented as follows:

P A C I F I Q U E \0

The last character \0 is called the null-terminating character.


For this reason, a string is said to be null-terminated.
16
Output statements
cout << variable-name;
Meaning: print the value of variable <variable-name> to the user
cout << “any message ”;
Meaning: print the message within quotes to the user
cout << endl; Meaning: print a new line

Screen

Cout << My-character


Object
Insertion Operator/
String
Example: Put-to Operator
cout << a;
cout << b << c;
cout << “This is my character: “ << my-character <<
endl; 17
Input statements
cin >> variable-name;
Meaning: read the value of the variable called <variable-name> from the
user

Keyboard

cin >> My-character


Example:
Object cin >>Extraction
a; Operator/ String
cin >> b >> c; Get-from Operator
cin >> my-character;

18
Variable declaration
type variable-name;
Meaning: variable <variable-name> will be a variable of type
<type>

Where type can be:


– int //integer
– double //real number
– char //character

Example:
int a, b, c;
double x;
int sum;
char my-character; 19
int main()
{
long aCount;
double theTotal;
...
}

20
Variables will be declared in three basic places: inside functions, in the
definition of function parameters, and outside of all functions. These are
local variables and global variables.

Local Variables
Variables that are declared inside a function are called local variables.
Local variables may be referenced only by statements that are inside the
block in which the variables are declared. In other words, local variables
are not known outside their own code block. Remember, a block of code
begins with an opening curly brace and terminates with a closing curly
brace.
Local variables exist only while the block of code in which they are
declared is executing. That is, a local variable is created upon entry into
its block and destroyed upon exit.

21
void func1(void)
{
int x;
x = 10;
}

22
Global Variables
Unlike local variables, global variables are
known throughout the program and may be
used by any piece of code. Also, they will
hold their value throughout the program's
execution. You create global variables by
declaring them outside of any function.

23
#include <iostream.h>
int count; /* count is global */
void func1(void);
void func2(void);
int main(void)
{
count = 100;
func1();
return 0;
}

24
Dynamic Initialization of variables
C++, permits initialization of the variables at run time. This
referred to as dynamic initialization. In C++, a variable can be
initialized at run time using expressions at the place of declaration.
float area = 3.1416 * rad *rad;
The initialization of a variable can be done simultaneously at the
place where the variable is used for the first time.
float average;//declare where it is necessary
Average = sum/i;
Can be combined into a single statement:
float average =sum/i; // initialize dynamically at run time.

25
Reference Variables
Reference variable provides an alias(alternative name) for a previously defined variable.
data-type & reference-name =variable-name
Example:
float total =100;
float sum =total;
A reference variable must be initialized at the time of declaration.
& is not an address operator. The notation float & means reference to float.
int n[10];
int & x=n[10]; //x is alias for n[10]
char & a =‘\n’;//initialize reference to a literal

26
A major application of reference variables is in passing arguments to
functions.
void f(int & x) //uses references
{
x=x+10; //x is incremented; so also m
}
int main()
{
int m =10;
f(m); //function call
….
}
When the function call f(m) is executed, the initialization occurs: int & x
=m;
Thus x becomes an alias of m after executing the statement f(m);
27
Such function calls are known as call by reference.

int m=10; m
10
The call by reference mechanism is useful in object-oriented programming because it
call of objects by reference, and eliminates the copying of object
permits the manipulation
parameters back and
f(m)forth. References can be created
x not only for built-in data types
but also for user defined data types like structures and classes.
int & x=m;

28
Operator Precedence

29
Scope resolution Operator
The scope resolution operator can allow access to a name in an
enclosing scope
that is "hidden" by a local declaration of the same name. For
example,
int i; // global i
void f()
{
int i; // local i
i = 10; // uses local i
.
}
the assignment i = 10 refers to the local i. But what if
function f() needs to access the global version of i?
30
It may do so by preceding the i with the :: operator,
as shown here.
int i; // global i
void f()
{
int i; // local i
::i = 10; // now refers to global i
.
}

31
Memory Management operator
C++ provides two dynamic allocation operators: new and delete. These operators
are used to allocate and free memory at run time. The new operator allocates
memory and returns a pointer to the start of it. The delete operator frees memory
previously allocated using new. The general forms of new and delete are shown
here:
pointer_variable = new data-type.
Here, pointer variable is a pointer of type data-type. The new operator allocates
sufficient memory to hold a data object of type data-type and returns the address
of the object.
P = new int;
int *p = new int;
float *q = new float;
delete pointer-variable; like: delete p; delete q;

32
Type Cast Operator
C++ permits explicit type conversion of variables or
expressions using the type cast operator.
Type-name (expression)
Examples
average = sum/float(i);
A type-name behaves as if it is a function for converting
values to a designated type. The function call notation
usually leads to simplest expressions. But, it can be used
only if the type is an identifier.
p = int * (q);
is illegal.
p = (int *)q; 33
We can use typedef to create an identifier of the
required type and use it in the functional notation.

typedef int * int_pt;


p= int_pt(q);

34
Basic Data Type
C++ Data Type

Built-in type Derived Type


User Defined data Types
Array
Structure
Function
Class
Pointer
Enumeration

Integral type Void Floating type

int char float double

35
36
Modifying the Basic Types

Except for type void, the basic data types may have various modifiers
preceding them.
You use a modifier to alter the meaning of the base type to fit various
situations more precisely. The list of modifiers is shown here:

Signed
Unsigned
Long
short

37
Derived Data Type
Array
An array is a collection of variables of the same type that are referred
to through a common name. A specific element in an array is
accessed by an index. In C/C++, all arrays consist of contiguous
memory locations.

The lowest address corresponds to the first element and the highest
address to the last element.

Arrays may have from one to several dimensions. The most common
array is the null-terminated string, which is simply an array of
characters terminated by a null.
38
Pointer
A pointer is a variable that holds a memory address. This address is
the location of another object (typically another variable) in memory.
For example, if one variable contains the address of another variable,
the first variable is said to point to the second.

39
Pointer Variables
The pointer declaration consists of a base type, an *, and the variable
name. The general form for declaring a pointer variable is
type *name;
where type is the base type of the pointer and may be any valid type. The
name of the pointer variable is specified by name.

The base type of the pointer defines what type of variables the pointer
can point to.

Technically, any type of pointer can point anywhere in memory.


However, all pointer arithmetic is done relative to its base type, so it is
important to declare the pointer correctly.

40
Function
Function is defined as a procedure that returns a value.
The General Form of a Function is
ret-type function-name(parameter list)
{
body of the function
}
The ret-type specifies the type of data that the function returns.
A function may return any type of data except an array. The
parameter list is a comma-separated list of variable names and
their associated types that receive the values of the arguments
when the function is called. A function may be without
parameters, in which case the parameter list is empty. However,
even if there are no parameters, the parentheses are still
41
required.
User defined data types
• Structure
A structure contains a no. of data types grouped together. These data type may
or may not be of the same type.
• General form of structure
struct<structure name>
{ struct book
structure element1; {
structure element2; char name;
. float price;
int pages;
.
};
};
struct book b1,b1,b3;

42
• Class
A group of objects that share common properties and
relationships. Iin C++ a class is a new data type that contains
member variables and member functions that operate on the
variables. A class is defined with the keyword class. Or we
can say that Class is a collection of similar objects.
Class class_name
{
Private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
43
Compiler Directives

include
Compiler directive
Processed at compilation time
Instructs compiler on what you want in
the program
#include <iostream>
Adds library files to program
Used with < >
Also “ ”user defined

44
Compiler Directives

Stream data type


Object that is a stream of characters
Defined in iostream
Entered on the keyboard (cin)
Displayed on monitor (cout)

45
Expressions
An expression is a combination of operators, constants
and variables arranged as per rules of the language.
It may also include function calls.

46
A C++ program
//include headers; these are modules that include functions that you
may use in your
//program; we will almost always need to include the header that
// defines cin and cout; the header is called iostream.h
#include <iostream.h>

int main() {
//variable declaration
//read values input from user
//computation and print output to user
return 0;
}
After you write a C++ program you compile it; that is, you run a program called
compiler that checks whether the program follows the C++ syntax
– if it finds errors, it lists them
– If there are no errors, it translates the C++ program into a program in machine
language which you can execute
47
Notes
• what follows after // on the same line is considered comment

• indentation is for the convenience of the reader; compiler ignores


all spaces and new line ; the delimiter for the compiler is the
semicolon

• all statements ended by semicolon

• Lower vs. upper case matters!!


– Void is different than void
– Main is different that main

48
Hello world program
When learning a new language, the first program people
usually write is one that salutes the world :)

Here is the Hello world program in C++.

#include <iostream.h>
int main() {
cout << “Hello world!”;

return 0;
}
49
If statements
True False
condition
if (condition) {
S1;
}
S1 S2
else {
S2;
}
S3;
S3

50
Boolean conditions
..are built using
• Comparison operators
== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

• Boolean operators
&& and
|| or
! not
51
Examples
Assume we declared the following variables:
int a = 2, b=5, c=10;

Here are some examples of boolean conditions we can use:


• if (a == b) …
• if (a != b) …
• if (a <= b+c) …
• if(a <= b) && (b <= c) …
• if !((a < b) && (b<c)) …

52
If example
#include <iostream.h>

void main() {
int a,b,c;
cin >> a >> b >> c;

if (a <=b) {
cout << “min is “ << a << endl;
}
else {
cout << “ min is “ << b << endl;
}
cout << “happy now?” << endl;
} 53
While statements
True False
while (condition) { condition

S1;
} S1

S2;
S2

54
While example
//read 100 numbers from the user and output their sum
#include <iostream.h>

void main() {
int i, sum, x;
sum=0;
i=1;
while (i <= 100) {
cin >> x;
sum = sum + x;
i = i+1;
}
cout << “sum is “ << sum << endl;
} 55
C++ Comments
A comment is text that the compiler ignores but that is useful for
programmers. Comments are normally used to annotate code for future
reference. The compiler treats them as white space. You can use
comments in testing to make certain lines of code inactive; however,
#if/#endif preprocessor directives work better for this because you can
surround code that contains comments but you cannot nest comments.
A C++ comment is written in one of the following ways:
•The /* (slash, asterisk) characters, followed by any sequence of
Characters (including new lines), followed by the */ characters. This
syntax is the same as ANSI C.
•The // (two slashes) characters, followed by any sequence of characters.
A new line not immediately preceded by a backslash terminates this form
of comment. Therefore, it is commonly called a "single-line comment."
The comment characters (/*, */, and //) have no special meaning
within a character constant, string literal, or comment. Comments using
the first syntax, therefore, cannot be nested. 56

You might also like