0% found this document useful (0 votes)
18 views25 pages

Unit-4.1, Notes

Uploaded by

Akshay Dwivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views25 pages

Unit-4.1, Notes

Uploaded by

Akshay Dwivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT-4, OOSD

WHAT IS OOP?
! OOP is a powerful way to approach the task of programming.
! OOP encourages developers to decompose a problem into its constituent parts.
! Each component becomes a self-contained object that contains its own instructions
and data that relate to that object.
! So, complexity is reduced and the programmer can manage larger programs.
! All OOP languages, including C++, share three common de ning traits:
! Encapsulation
! Binds together code and data
! Polymorphism
! Allows one interface, multiple methods
! Inheritance
! Provides hierarchical classi cation
! Permits reuse of common code and data

What is C++ ?
!C++ is the C programmer‟s answer to Object-Oriented Programming (OOP).
!C++ is an enhanced version of the C language.
!C++ adds support for OOP without sacri cing any of C‟s power, elegance, or
exibility.
!C++ was invented in 1979 by Bjarne Stroustrup at Bell Laboratories in Murray
Hill, New Jersey, USA.
!The elements of a computer language do not exist in a void, separate from one
another.
!The features of C++ are highly integrated.
!Both object-oriented and non-object-oriented programs can be developed using
C++.

NAMESPACES
Using namespaces, we can create two variables or member functions having the same name.

#include <iostream>
using namespace std;
// Variable created inside namespace
fl
fi
fi
fi
namespace rst
{
int val = 500;
}

// Global variable
int val = 100;

int main()
{
// Local variable
int val = 200;

// These variables can be accessed from


// outside the namespace using the scope
// operator ::
cout << rst::val << '\n';

return 0;
}

• Namespaces allow us to group named entities that otherwise would have global scope into
narrower scopes, giving them namespace scope. This allows organizing the elements of
programs into di erent logical scopes referred to by names.
• Namespace is a feature added in C++ and not present in C.
• A namespace is a declarative region that provides a scope to the identi ers (names of the
types, function, variables etc) inside it.
• Multiple namespace blocks with the same name are allowed. All declarations within those
blocks are declared in the named scope.
• A namespace de nition begins with the keyword namespace followed by the namespace
name as follows:
namespace namespace_name
{
int x, y; // code declarations where
// x and y are declared in
// namespace_name's scope
}

• Namespace declarations appear only at global scope.


• Namespace declarations can be nested within another namespace.
• Namespace declarations don’t have access speci ers. (Public or private)
• No need to give semicolon after the closing brace of de nition of namespace.
• We can split the de nition of namespace over several units.

using namespace std;


namespace ns1
{
int value() { return 5; }
}
fi
fi
ff
fi
fi
fi
fi
fi
namespace ns2
{
const double x = 100;
double value() { return 2*x; }
}

int main()
{
// Access value function within ns1
cout << ns1::value() << '\n';

// Access value function within ns2


cout << ns2::value() << '\n';

// Access variable x directly


cout << ns2::x << '\n';

return 0;
}

Classes and Namespace

Following is a simple way to create classes in a name space


// A C++ program to demonstrate use of class
// in a namespace
#include <iostream>
using namespace std;

namespace ns
{
// A Class in a namespace
class geek
{
public:
void display()
{
cout << "ns::geek::display()\n";
}
};
}

int main()
{
// Creating Object of geek Class
ns::geek obj;

obj.display();
return 0;
}
ns::geek::display()

Class can also be declared inside namespace and de ned outside namespace using following
syntax

// A C++ program to demonstrate use of class


// in a namespace
#include <iostream>
using namespace std;

namespace ns
{
// Only declaring class here
class geek;
}

// De ning class outside


class ns::geek
{
public:
void display()
{
cout << "ns::geek::display()\n";
}
};

int main()
{
//Creating Object of geek Class
ns::geek obj;
obj.display();
return 0;
}

We can de ne methods also outside the namespace. Following is an example code.

// A C++ code to demonstrate that we can de ne


// methods outside namespace.
#include <iostream>
using namespace std;

// Creating a namespace
namespace ns
{
void display();
class geek
{
public:
fi
fi
fi
fi
void display();
};
}

// De ning methods of namespace


void ns::geek::display()
{
cout << "ns::geek::display()\n";
}
void ns::display()
{
cout << "ns::display()\n";
}

// Driver code
int main()
{
ns::geek obj;
ns::display();
obj.display();
return 0;
}

Identi ers
The C++ identi er is a name used to identify a variable, function, class, module, or any other user-
de ned item.

• The following rules are common to both C and C++.


Only alphabet characters, digits and underscores are permitted. The name cannot start with
a digit.

• Uppercase and lowercase letters are distinct. Manpower and manpower are two di erent
identi ers in C++.

• A declared keyword cannot be used as a variable name.

Variables
• A variable is a name given to a memory location. It is the basic unit of storage in a program.

• The value stored in a variable can be changed during program execution.

• A variable is only a name given to a memory location, all the operations done on the variable
e ects that memory location.

• In C++, all the variables must be declared before use.

How to declare variables?

• A typical variable declaration is of the form:

• // Declaring a single variable


ff
fi
fi
fi
fi
fi
ff
• type variable_name= value;

• // Declaring multiple variables:

• type variable1_name, variable2_name=value, variable3_name;

• datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

• A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‘_’ character. However, the name must not start with a number.

• The variable declaration refers to the part where a variable is rst declared or introduced
before its rst use. A variable de nition is a part where the variable is assigned a memory
location and a value. Most of the times, variable declaration and de nition are done together.

Types of variables

There are three types of variables based on the scope of variables in C++:

• Local Variables

• Instance Variables

• Static Variables

Local Variables: A variable de ned within a block or method or constructor is called local
variable.

These variable are created when the block in entered or the function is called and destroyed after
exiting from the block or when the call returns from the function.

The scope of these variables exists only within the block in which the variable is declared. i.e. we
can access these variable only within that block.

Initialisation of Local Variable is Mandatory.

Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.

As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.

Unlike local variables, we may use access speci ers for instance variables. If we do not specify
any access speci er then the default access speci er will be used.

Initialisation of Instance Variable is not Mandatory.

Instance Variable can be accessed only by creating objects.


fi
fi
fi
fi
fi
fi
fi
fi
Static Variables: Static variables are also known as Class variables.

These variables are declared similarly as instance variables, the di erence is that static variables
are declared using the static keyword within a class outside any method constructor or block.

Unlike instance variables, we can only have one copy of a static variable per class irrespective of
how many objects we create.

Static variables are created at the start of program execution and destroyed automatically when
execution ends.

Initialization of Static Variable is not Mandatory. Its default value is 0

If we access the static variable like Instance variable (through an object), the compiler will show
the warning message and it won’t halt the program. The compiler will replace the object name to
class name automatically.

If we access the static variable without the class name, Compiler will automatically append the
class name.

CONSTANTS
Constants refer to xed values that do not change during the execution of a program. Like C, C+
support several kinds of literal constants. They include integers, characters, oating point
numbers and string.

Named Constant
const double CENTIMETERS_PER_INCH = 2.54; const int INCHES_PER_FOOT = 12;

Every constant has some range. The integers that are too big to t into an int will be taken as
long. Now there are various ranges that di er from unsigned to signed bits. Under the signed bit,
the range of an int varies from -128 to +127, and under the unsigned bit, int varies from 0 to 255.

De ning Constants:
In C/C++ program we can de ne constants in two ways as shown below:

• Using #de ne preprocessor directive: This directive is used to declare an alias name for
existing variable or any value. We can use this to declare a constant as shown below:
fi
fi
fi
fi
ff
ff
fi
fl
#de ne identi erName value

identi erName: It is the name given to constant.

value: This refers to any value assigned to identi erName.

• Using a const keyword: Using const keyword to de ne constants is as simple as de ning


variables, the di erence is you will have to precede the de nition with a const keyword.

Literals: The values assigned to each constant variables are referred to as the literals. Generally,
both terms, constants and literals are used interchangeably. For eg, “const int = 5;“, is a constant
expression and the value 5 is referred to as constant integer literal.

#include <stdio.h>

int main()

// int constant

const int intVal = 10;

// Real constant

const oat oatVal = 4.14;

// char constant

const char charVal = 'A';


fi
fi
fl
fi
fl
ff
fi
fi
fi
fi
// string constant

const char stringVal[10] = "ABC";

printf("Integer constant:%d \n", intVal );

printf("Floating point constant: %.2f\n", oatVal );

printf("Character constant: %c\n", charVal );

printf("String constant: %s\n", stringVal);

return 0;

Enumeration (or enum)


Enumeration (or enum) is a user de ned data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.

enum State {Working = 1, Failed = 0};

• The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an
example of enum declaration.

// The name of enumeration is " ag" and the constant

// are the values of the ag. By default, the values


fl
fl
fi
fl
// of the constants are as follows:

// constant1 = 0, constant2 = 1, constant3 = 2 and

// so on.

enum ag{constant1, constant2, constant3, ....... };

Variables of type enum can also be de ned. They can be de ned in two ways:

// In both of the below cases, "day" is

// de ned as the variable of type week.

enum week{Mon, Tue, Wed};

enum week day;

// Or

enum week{Mon, Tue, Wed}day;

#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()

enum week day;

day = Wed;

printf("%d",day);

return 0;

OUTPUT: 2

In the above example, we declared “day” as the variable and the value of “Wed” is allocated to
day, which is 2. So as a result, 2 is printed.

• Two enum names can have same value. For example, in the following C program both ‘Failed’
and ‘Freezed’ have same value 0.

#include <stdio.h>

enum State {Working = 1, Failed = 0, Freezed = 0};


fi
fl
fi
fi
int main()

printf("%d, %d, %d", Working, Failed, Freezed);

return 0;

OUTPUT; 1,0,0

#include <stdio.h>

enum State {Working = 1, Failed = 0, Freezed = 0};

int main()

printf("%d, %d, %d", Working, Failed, Freezed);

return 0;

Output: The day number stored in d is 4

• We can assign values to some name in any order. All unassigned names get value as value of
previous name plus one.

#include <stdio.h>

enum day {sunday = 1, monday, tuesday = 5,

wednesday, thursday = 10, friday, saturday};

int main()

printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,

wednesday, thursday, friday, saturday);

return 0;

OUTPUT: 1 2 5 6 10 11 12

• The value assigned to enum names must be some integral constant, i.e., the value must be in
range from minimum possible integer value to maximum possible integer value.

• All enum constants must be unique in their scope. For example, the following program fails in
compilation.
enum state {working, failed};

enum result {failed, passed};

int main() { return 0; }

OUTPUT: Compile Error: 'failed' has a previous declaration as 'state failed’

ADVANTAGES:
There are multiple advantages of using enum over macro when many related named
constants have integral values.
a) Enums follow scope rules.
b) Enum variables are automatically assigned values.

DATA TYPES IN C++

OPERATORS
An operator is a symbol which represents a particular operation that can be performed on data.
An operand is the object on which an operation is performed.

By combining the operators and operands we form an expression. An expression is a sequence of


operands and operators that reduces to a single value.

C++ has many built-in operators and can be classi ed into 6 types:

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators
fi
4. Bitwise Operators

5. Assignment Operators

1. Arithmetic Operators:

These operators are used to perform arithmetic/mathematical operations on operands. Examples:


(+, -, *, /, %,++,–). Arithmetic operators are of two types:

a) Unary Operators: Operators that operate or work with a single operand are unary
operators. For example: Increment(++) and Decrement(–) Operators

b) Binary Operators: Operators that operate or work with two operands are binary
operators. For example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators

2. Relational Operators:These are used for the comparison of the values of two operands. For
example, checking if one operand is equal to the other operand or not, an operand is greater than
the other operand or not, etc. Some of the relational operators are (==, >= , <= )(See this article for
more reference).

3. Logical Operators:

Logical Operators are used to combining two or more conditions/constraints or to complement


the evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.

For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the
conditions under consideration are satis ed. Otherwise, it returns false. Therefore, a && b returns
true when both a and b are true (i.e. non-zero)

4. Bitwise Operators:

The Bitwise operators are used to perform bit-level operations on the operands. The operators are
rst converted to bit-level and then the calculation is performed on the operands. The
mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
bit-level for faster processing. For example, the bitwise AND represented as & operator in C or C+
+ takes two numbers as operands and does AND on every bit of two numbers. The result of AND
is 1 only if both bits are 1.

5. Assignment Operators:

Assignment operators are used to assigning value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left side
otherwise the compiler will raise an error.

Di erent types of assignment operators are shown below:


a. “=”: This is the simplest assignment operator. This operator is used to assign the value
on the right to the variable on the left.
b. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator rst adds the
current value of the variable on left to the value on the right and then assigns the result to
the variable on the left.
c. “-=”: This operator is a combination of ‘-‘ and ‘=’ operators. This operator rst subtracts
the value on the right from the current value of the variable on left and then assigns the
result to the variable on the left.

d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator rst multiplies
the current value of the variable on left to the value on the right and then assigns the result
to the variable on the left.
fi
ff
fi
fi
fi
fi
e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator rst divides
the current value of the variable on left by the value on the right and then assigns the result
to the variable on the left. Other Operators

Scope Resolution operator


Scope:-Visibility or availability of a variable in a program is called as scope. There are two types of
scope.
i)Local scope
ii)Global scope

Local scope: visibility of a variable is local to the function in which it is declared.

Global scope: visibility of a variable to all functions of a program Scope resolution operator in
“::” .

This is used to access global variables if same variables are declared as local and global.

TYPE CONVERSION (CASTING)


A type cast is basically a conversion from one type to another. There are two types of type
conversion:
fi
Implicit Type Conversion: Also known as ‘automatic type conversion’.

Done by the compiler on its own, without any external trigger from the user.

Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid loss of data.

All the data types of the variables are upgraded to the data type of the variable with largest data
type.

bool -> char -> short int -> int -> unsigned int ->long -> unsigned -> long long -> oat -> double->
long double

It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and over ow can occur (when long long is implicitly converted
to oat).

Example of Type Implicit Conversion:

#include <iostream>

using namespace std;

int main()

int x = 10; // integer x

char y = 'a'; // character c

// y implicitly converted to int. ASCII

// value of 'a' is 97

x = x + y;

// x is implicitly converted to oat

oat z = x + 1.0;

cout << "x = " << x << endl

<< "y = " << y << endl

<< "z = " << z << endl

return 0;

OUTPUT: x=107
y=a
z=108

Explicit Type Conversion– This process is also called type casting and it is user-de ned. Here
the user can typecast the result to make it of a particular data type.
fl
fl
fl
fl
fl
fi
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly de ning the required type in front of the
expression in parenthesis. This can be also considered as forceful casting.

Syntax: (type) expression

where type indicates the data type to which the nal result is converted.

#include <iostream>

using namespace std;

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

cout << "Sum = " << sum;


return 0;

OUTPUT: SUM=2

Advantages of Type Conversion:

1. This is done to take advantage of certain features of type hierarchies or type representations.

2. It helps to compute expressions containing variables of di erent data types.

CONTROL STUCTURES
There are three types of control structures available in C++

1) Sequence structure (straight line paths)

2) Selection structure (one or many branches)

3)Loop structure (repetition of a set of activities)

The if keyword is used to execute a statement or block only if a condition is ful lled. Its form is:

if (condition) statement

Where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues right after
this conditional structure.

For example, the following code fragment prints x is 100 only if the value stored in the x variable is
indeed 100:
fi
fi
ff
fi
1 if (x == 100)
2 cout << "x is
100";

If we want more than a single statement to be executed in case that the condition is true we can
specify a block using braces { }:

1 if (x == 100)
2{
3 cout << "x is
4 ";
5 cout << x;
}

We can additionally specify what we want to happen if the condition is not ful lled by using the
keyword else. Its form used in conjunction with if is:

if (condition) statement1 else statement2

For example:

1 if (x == 100)
2 cout << "x is 100";
3 else
4 cout << "x is not
100";

prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it
prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values. The
following example shows its use telling if the value currently stored in x is positive, negative or
none of them (i.e. zero):

1 if (x > 0)
2 cout << "x is
3 positive";
4 else if (x < 0)
5 cout << "x is
6 negative";
else
cout << "x is 0";

Remember that in case that we want more than a single statement to be executed, we must
group them in a block by enclosing them in braces { }.
fi
Iteration structures (loops)

Loops have as purpose to repeat a statement a certain number of times or while a condition is
ful lled.

The while loop

Its format is:

while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true.

For example, we are going to make a program to countdown using a while-loop:

1 // custom countdown using Enter the starting number > 8


2 while 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
3
4 #include <iostream>
5 using namespace std;
6
7 int main () E
8 { di
9 int n; t
1 cout << "Enter the starting &
0 number > "; R
1 cin >> n; u
1 n
1 while (n>0) {
2 cout << n << ", ";
1 --n;
3 }
1
4 cout << "FIRE!\n";
1 return 0;
When the program starts the user is prompted to insert a starting number for the countdown.
Then the while loop begins, if the value entered by the user ful lls the condition n>0 (that n is
greater than zero) the block that follows the condition will be executed and repeated while the
condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script
(beginning in main):

User assigns a value to n

The while condition is checked (n>0). At this point there are two possibilities:
* condition is true: statement is executed (to step 3)
* condition is false: ignore statement and continue after it (to step 5)
fi
fi
Execute statement:
cout << n << ", ";
--n;
(prints the value of n on the screen and decreases n by 1)

End of block. Return automatically to step 2

Continue the program right after the block: print FIRE! and end program.

When creating a while-loop, we must always consider that it has to end at some point, therefore
we must provide within the block some method to force the condition to become false at some
point, otherwise the loop will continue looping forever. In this case we have included --n; that
decreases the value of the variable that is being evaluated in the condition (n) by one - this will
eventually make the condition (n>0) to become false after a certain number of loop iterations: to
be more speci c, when n becomes 0, that is where our while-loop and our countdown end.

Of course this is such a simple action for our computer that the whole countdown is performed
instantly without any practical delay between numbers.

The do-while loop

Its format is:

do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never ful lled. For example, the following example program echoes
any number you enter until you enter 0.

1 // number echoer Enter number (0 to end): 12345


2 You entered: 12345
3 #include <iostream> Enter number (0 to end):
4 using namespace std; 160277
5 You entered: 160277 E
6 int main () Enter number (0 to end): 0 di
7 { You entered: 0 t
8 unsigned long n; &
9 do { R
1 cout << "Enter number (0 u
0 to end): "; n
1 cin >> n;
1 cout << "You entered: " <<
1 n << "\n";
2 } while (n != 0);
1 return 0;
fi
fi
The do-while loop is usually used when the condition that has to determine the end of the loop is
determined within the loop statement itself, like in the previous case, where the user input within
the block is what is used to determine if the loop has to end. In fact if you never enter the value 0
in the previous example you can be prompted for more numbers forever.

The for loop

Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But
in addition, the for loop provides speci c locations to contain an initialization statement and an
increase statement. So this loop is specially designed to perform a repetitive action with a counter
which is initialized and increased on each iteration.

It works in the following way:

initialization is executed. Generally it is an initial value setting for a counter variable. This is
executed only once.

condition is checked. If it is true the loop continues, otherwise the loop ends and statement is
skipped (not executed).

statement is executed. As usual, it can be either a single statement or a block enclosed in braces
{ }.

nally, whatever is speci ed in the increase eld is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop:

1 // countdown using a for loop 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,


2 #include <iostream> FIRE!
3 using namespace std; E
4 int main () di
5 { t
6 for (int n=10; n>0; n--) { &
7 cout << n << ", "; R
8 } u
9 cout << "FIRE!\n"; n
1 return 0;
0 }
1

The initialization and increase elds are optional. They can remain empty, but in all cases the
semicolon signs between them must be written. For example we could write: for (;n<10;) if we
wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an
increase eld but no initialization (maybe because the variable was already initialized before).
fi
fi
fi
fi
fi
fi
Optionally, using the comma operator (,) we can specify more than one expression in any of the
elds included in a for loop, like in initialization, for example. The comma operator (,) is an
expression separator, it serves to separate more than one expression where only one is generally
expected. For example, suppose that we wanted to initialize more than one variable in our loop:

1 for ( n=0, i=100 ; n!=i ; n++,


2 i-- )
3{
4 // whatever here...
}

This loop will execute for 50 times if neither n or i are modi ed within the loop:

n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is
increased by one and i decreased by one, the loop's condition will become false after the 50th
loop, when both n and i will be equal to 50.

Jump statements.

break statement

Using break we can leave a loop even if the condition for its end is not ful lled. It can be used to
end an in nite loop, or to force it to end before its natural end. For example, we are going to stop
the count down before its natural end (maybe because of an engine check failure?):
1 // break loop example 10, 9, 8, 7, 6, 5, 4, 3,
2 countdown aborted!
3 #include <iostream>
4 using namespace std;
5
6 int main ()
7 { E
8 int n; di
9 for (n=10; n>0; n--) t
1 { &
0 cout << n << ", "; R
1 if (n==3) u
1 { n
1 cout << "countdown
2 aborted!";
1 break;
3 }
1 }
4 return 0;
1 }
fi
fi
fi
fi
continue statement: The continue statement causes the program to skip the rest of the loop in
the current iteration as if the end of the statement block had been reached, causing it to jump to
the start of the following iteration. For example, we are going to skip the number 5 in our
countdown:

1 // continue loop example 10, 9, 8, 7, 6, 4, 3, 2, 1,


2 #include <iostream> FIRE!
3 using namespace std;
4 E
5 int main () di
6 { t
7 for (int n=10; n>0; n--) { &
8 if (n==5) continue; R
9 cout << n << ", "; u
1 } n
0 cout << "FIRE!\n";
1 return 0;
1 }
1

goto statement: goto allows to make an absolute jump to another point in the program. You
should use this feature with caution since its execution causes an unconditional jump ignoring any
type of nesting limitations.

The destination point is identi ed by a label, which is then used as an argument for the goto
statement. A label is made of a valid identi er followed by a colon (:).

Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may nd for it. For example, here
is our countdown loop using goto:

1 // goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,


2 FIRE!
3 #include <iostream>
4 using namespace std;
5 E
6 int main () di
7 { t
8 int n=10; &
9 loop: R
1 cout << n << ", "; u
0 n--; n
1 if (n>0) goto loop;
1 cout << "FIRE!\n";
1 return 0;
2 }
1
fi
fi
fi
The exit function: exit is a function de ned in the cstdlib library.

The purpose of exit is to terminate the current program with a speci c exit code. Its prototype is:

void exit (int


exitcode);

The exitcode is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program nished normally and any other value
means that some error or unexpected results happened.

selective structure: switch.

The syntax of the switch statement is a bit peculiar. Its objective is to check several possible
constant values for an expression. Something similar to what we did at the beginning of this
section with the concatenation of several if and else if instructions. Its form is the following:

switch (expression)

case constant1:

group of statements 1;

break;

case constant2:

group of statements 2;

break;

default:

default group of statements

It works in the following way: switch evaluates expression and checks if it is equivalent to
constant1, if it is, it executes group of statements 1 until it nds the break statement. When it
nds this break statement the program jumps to the end of the switch selective structure.

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this,
it will execute group of statements 2 until a break keyword is found, and then will jump to the end
of the switch selective structure.
fi
fi
fi
fi
fi
Finally, if the value of expression did not match any of the previously speci ed constants (you can
include as many case labels as values you want to check), the program will execute the
statements included after the default: label, if it exists (since it is optional).

Both of the following code fragments have the same behavior

switch example if-else equivalent


switch (x) {
if (x == 1) {
case 1:
cout << "x is 1";
cout << "x is 1";
}
break;
else if (x == 2) {
case 2:
cout << "x is 2";
cout << "x is 2";
}
break;
else {
default:
cout << "value of x
cout << "value of x
unknown";
unknown";
}
}

The switch statement is a bit peculiar within the C++ language because it uses labels instead of
blocks. This forces us to put break statements after the group of statements that we want to be
executed for a speci c condition. Otherwise the remainder statements -including those
corresponding to other labels- will also be executed until the end of the switch selective block or
a break statement is reached.

For example, if we did not include a break statement after the rst group for case one, the
program will not automatically jump to the end of the switch selective block and it would continue
executing the rest of statements until it reaches either a break instruction or the end of the switch
selective block. This makes it unnecessary to include braces { } surrounding the statements for
each of the cases, and it can also be useful to execute the same block of instructions for di erent
possible values for the expression being evaluated. For example:

1 switch (x) {
2 case 1:
3 case 2:
4 case 3:
5 cout << "x is 1, 2 or 3";
6 break;
7 default:
8 cout << "x is not 1, 2 nor
9 3";
}

Notice that switch can only be used to compare an expression against constants. Therefore we
cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):)
because they are not valid C++ constants.
fi
fi
fi
ff

You might also like