0% found this document useful (0 votes)
5 views120 pages

unit 1 oocp

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 120

OOCP C++

C++ is an object-oriented programming


language.

Developed by Bjarne Stroustrup at AT&T


Bell Laboratories, USA in the early 1980’s.

1997 November ANSI/ISO standards


committee standardized C++.

For developing editors, compilers,


databases, communication systems, etc.
C++ works by giving (separate) instructions to
the computer.

These instructions can be written as functions.


The primary function used in C++ is called main.

The body of a function starts with an opening


curly bracket "{" and closes with a closing curly
bracket "}".
Software technology is dynamic as continuous new
approach to software design and development.

Software product should be evaluated carefully for


their quality before they are delivered and
implemented.

Some quality issues that considered as……


1. Correctness
2. Security
3. Maintainability
4. Integrity
5. Reusability 6. User Friendliness 7 Portability
Applications of OOP
A Simple C++ Program
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}

 iostream is just like we include stdio.h in c program.


 It contains declarations for the identifier cout and the insertion
operator <<.
 iostream should be included at the beginning of all programs
that use input/output statements.
A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}
 A namespace is a declarative region.
 A namespace is a part of the program in which certain names are
recognized; outside of the namespace they’re unknown.
 namespace defines a scope for the identifies that are used in a
program.
 using and namespace are the keywords of C++.
A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}
 std is the namespace where ANSI C++ standard class libraries are
defined.
 Various program components such as cout, cin, endl are
defined within std namespace.
 If we don’t use the using directive at top, we have to add the std
followed by :: in the program before identifier.
std::cout << “Hello World”;
A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
return 0;
}
 In C++, main() returns an integer type value.
 Therefore, every main() in C++ should end with a return 0;
statement; otherwise error will occur.
 The return value from the main() function is used by the
runtime library as the exit code for the process.
Insertion Operator <<
cout << "Hello World";

 The operator << is called the


insertion operator.
 It inserts the contents of the
variable on its right to the object
on its left.
 The identifier cout is a predefined
object that represents standard
output stream in C++.
 Here, Screen represents the
output. We can also redirect the
output to other output devices. Output Using Insertion Operator
 The operator << is used as bitwise
left shift operator also.
Program: Basic C++ program
Write a C++ Program to print following

Name: xyz
City: Rajkot
Country: India
Program: Basic C++ program
#include <iostream>
using namespace std;
int main()
{
cout << "Name: xyz";
cout << "City: Rajkot";
cout << "Country: India";
return 0;
}

Output
Name: DarshanCity: RajkotCountry: India
Program: Basic C++ program(Cont…)
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
cout << "Name: xyz\n"; cout << "Name: xyz"<<endl;
cout << "City: Rajkot\n"; cout << "City: Rajkot"<<endl;
cout << "Country: India"; cout << "Country: India"<<endl;
return 0; return 0;
} }

Output  The endl manipulator and \n has same


Name: xyz effect. Both inserts new line to output.
City: Rajkot
Country: India
 But, difference is endl immediate flush to the
output while \n do not.
Extraction Operator >>
cin >> number1;
 The operator >> is called the
extraction operator.
 It extracts (or takes) the value Object Extraction Operator
from keyboard and assigns it to
cin >> number1
the variable on its right.
 The identifier cin is a predefined Variable
object that represents standard
input stream in C++.
 Here, standard input stream KeyBoard
represents the Keyboard.
 The operator >> is used as
bitwise right shift operator also.
Program: Basic C++ program
#include<iostream>
using namespace std;
int main()
{
int number1,number2;

cout<<"Enter First Number: ";


cin>>number1; //accept first number

cout<<"Enter Second Number: ";


cin>>number2; //accept first number

cout<<"Addition : ";
cout<<number1+number2; //Display Addition
return 0;
}
C++ Tokens
C++ Tokens
C++ Tokens
C++ Tokens
 The smallest individual unit of a program is known as token.
 C++ has the following tokens:
− Keywords
#include <iostream>
− Identifiers using namespace std;
int main()
− Constants
{
− Strings cout << "Hello World";
− Special Symbols return 0;
}
− Operators
Keywords and Identifier
 C++ reserves a set of 84 words for its own use.
 These words are called keywords (or reserved words), and each of
these keywords has a special meaning within the C++ language.
 Identifiers are names that are given to various user defined
program elements, such as variable, function and arrays.
 Some of Predefined identifiers are cout, cin, main

 We cannot use Keyword as user defined identifier.


Keywords in C++
asm double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typeof
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
Rules for naming identifiers in C++
1. First Character must be an alphabet or underscore.
2. It can contain only letters(a..z A..Z), digits(0 to 9) or
underscore(_).
3. Identifier name cannot be keyword.
4. Only first 31 characters are significant.
Valid, Invalid Identifiers
1) Darshan Valid 12) xyz123 Valid
2) A Valid 13) part#2 Invalid
3) Age Valid 14) "char" Invalid
4) void Reserved word 15) #include Invalid
5) MAX-ENTRIES Invalid 16) This_is_a_ Valid
6) double Reserved word 17) _xyz Valid
7) time Valid 18) 9xyz Invalid
8) G Valid 19) main Standard identifier
9) Sue's Invalid 20) mutable Reserved word
10) return Reserved word 21) double Reserved word
11) cout Standard identifier 22) max?out Invalid
Constants / Literals
 Constants in C++ refer to fixed values that do not change during
execution of program.

CONSTANTS

NUMERIC CHARACTER
CONSTANTS CONSTANTS

SINGLE
INTEGER REAL STRING
CHARACTER
CONSTANTS CONSTANTS CONSTANTS
CONSTANTS
i.e. i.e. i.e.
i.e.
123,-321, 6543 0.0083, -0.75 “Hello”, “197”
‘5’, ‘X’, ‘;’
C++ Operators
C++ Operators
 All C language operators are valid in C++.
1. Arithmetic operators (+, - , *, /, %)
2. Relational operators (<, <=, >, >=, ==, !=)
3. Logical operators (&&, ||, !)
4. Assignment operators (+=, -=, *=, /=)
5. Increment and decrement operators (++, --)
6. Conditional operators (?:)
7. Bitwise operators (&, |, ^, <<, >>)
8. Special operators ()
Arithmetic Operators

Operator example Meaning


+ a+b Addition
- a–b Subtraction
* a*b Multiplication
/ a/b Division
% a%b Modulo division- remainder
Relational Operators

Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Equal to
!= Not equal to
Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
a b a && b a || b
true true true true
true false false true
false true false true
false false false false

 a && b : returns false if any of the expression is false


 a || b : returns true if any of the expression is true
Assignment operator
 We assign a value to a variable using the basic assignment
operator (=).
 Assignment operator stores a value in memory.
 The syntax is
leftSide = rightSide ;

It is either a literal |
Always it is a
a variable identifier |
variable identifier.
an expression.

Literal: ex. i = 1;
Variable identifier: ex. start = i;
Expression: ex. sum = first + second;
Assignment Operators (Shorthand)
Syntax:
leftSide Op= rightSide ;

It is an arithmetic
operator.

Ex: Simple assignment


Shorthand operator
x=x+3; operator
x+=3; a = a+1 a += 1
a = a-1 a -= 1
a = a * (m+n) a *= m+n
a = a / (m+n) a /= m+n
a = a % b a %= b
Increment and Decrement Operators
 Increment ++
The ++ operator used to increase the value of the variable by one
 Decrement ─ ─
The ─ ─ operator used to decrease the value of the variable by one
Example:
x=100;
x++;
After the execution the value of x will be 101.
Example:
x=100;
x--;
After the execution the value of x will be 99.
Pre & Post Increment operator
Operator Description
Pre increment operator (++x) value of x is incremented before assigning
it to the variable on the left

x = 10 ; After execution
p = ++x; x will be 11
First increment value of p will be 11
x by one

Operator Description
Post increment operator (x++) value of x is incremented after assigning it
to the variable on the left

x = 10 ; After execution
p = x++; x will be 11
p will be 10
First assign value of x
What is the output of this program?
#include <iostream>
using namespace std;
int main ()
{
int x, y;
x = 5;
y = ++x * ++x;
cout << x << y;
x = 5;
y = x++ * ++x;
cout << x << y;
}

(A) 749735
(B) 736749
(C) 367497
(D) none of the mentioned
Conditional Operator
Syntax:
exp1 ? exp2 : exp3
Working of the ? Operator:
 exp1 is evaluated first
• if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the expression
• If exp1 is false(zero) then
- exp3 is evaluated and its value becomes the value of the expression
Ex: Ex:
m=2; m=2;
n=3; n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Value of r will be 3 Value of r will be 2
Bitwise Operator
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
Bitwise Operator Examples
8 = 1000 (In Binary)
6 = 0110 (In Binary)
Bitwise & (AND) Bitwise | (OR)
int a=8,b=6,c; int a=8,b=6,c;
c = a & b; c = a | b;
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 0 Output = 14
Bitwise << (Shift Left) Bitwise >> (Shift Right)
int a=8,b=6,c; int a=8,b=6,c;
c = a << 1; c = a >> 1;
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 16 Output = 4
left shifting is the equivalent of right shifting is the equivalent
multiplying a by a power of two of dividing a by a power of two
New Operators in C++
It allows to access to the global
version of variable
:: Scope Resolution Declares a pointer to a member of
a class
::* Pointer-to-member declarator
->* Pointer-to-member operator To access pointer to class members

.* Pointer-to-member operator To access pointer to data members


of class
new Memory allocation operator
Allocates memory at run time
delete Memory release operator
endl Line feed operator Deallocates memory at run time

setw Field width operator It is a manipulator causes a linefeed


to be inserted
It is a manipulator specifies a field
width for printing value
Scope Resolution
Operator
Scope Resolution Operator(::)
....
....
Declaration of x in inner block hides
{ declaration of same variable declared in an
int x=10; outer block.
....
.... Therefore, in this code both variable x
{ refers to different data.
int x=1; Block-1
.... Block-2
....  In C language, value of x declared in Block-1
} is not accessible in Block-2.
....
 In C++, using scope resolution operator (::),
}
value of x declared in Block-1 can be
accessed in Block-2.
#include <iostream> Scope resolution example
using namespace std;
int m=10; Global declaration of variable m
int main()
{
int m=20; variable m declared , local to main
{
int k=m;
int m=3;
cout<<"we are in inner block\n";
cout<<"k="<<k<<endl; variable m
cout<<"m="<<m<<endl; declared again local to inner block
cout<<"::m="<<::m<<endl;
} Output:
cout<<"we are in outer block\n"; we are in inner block
cout<<"m="<<m<<endl; k=20
cout<<"::m="<<::m<<endl; m=3
return 0; ::m=10
} we are in outer block
m=20
::m=10
C++ Data Types
Basic Data types
C++ datatypes

User-defined Built-in Derived


structure array
union function
class pointer
enumeration reference

Integral Void Floating

int char float double


Built in Data types
Data Type Size (bytes) Range
char 1 -128 to 127
unsigned char 1 0 to 255
short or int 2 -32,768 to 32,767
unsigned int 2 0 to 65535
long 4 -2147483648 to 2147483647
unsigned long 4 0 to 4294967295
float 4 3.4e-38 to 3.4e+308
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932
Type Conversion
Type Conversion
 Type Conversion is the process of converting one predefined data
type into another data type.

Type Conversion

Implicit Explicit
(Automatically converts (Forcefully converts one
one datatype to another datatype to another
datatype) datatype)

 Explicit type conversion is also known as type casting.


Type Conversion(Cont…)
int a;
double b=2.55;
a = b; // implicit type conversion
cout << a << endl; // this will print 2
a = int(b); //explicit type conversion
cout << a << endl; // this will print 2
Implicit type conversion hierarchy

long
double double
float
long int
unsigned
int int
char
Implicit Type Conversion
#include <iostream>
using namespace std;
ans = count * avg
int main()
{ 5 10.01
int count = 5;
float avg = 10.01; double int float
double ans;
5.0 *
ans = count * avg;
float
50.05
cout<<"Answer=:"<<ans; 50.05
return 0; float
double
}
Output:
Answer = 50.05
Type Casting
 In C++ explicit type conversion is called type casting
 Syntax
type-name (expression) //C++ notation
 Example
average = sum/(float) i; //C notation
average = sum/float (i); //C++ notation
#include <iostream>
using namespace std;
int main()
Type Casting Example
{
int a, b, c;
a = 19.99 + 11.99; //adds the values as float
// then converts the result to int
b = (int) 19.99 + (int) 11.99; // old C syntax
c = int (19.99) + int (11.99); // new C++ syntax

cout << "a = " << a << ", b = " << b;


cout << ", c = " << c << endl;

char ch = 'Z';
cout << "The code for " << ch << " is "; //print as char
cout << int(ch) << endl; //print as int
return 0;
}
Output:
a = 31, b = 30, c = 30
The code for Z is 90
Reference Variable
Reference Variable
 A reference provides an alias or a different name for a variable.
 One of the most important uses for references is in passing
arguments to functions.
declares variable a
int a=5;
int &ans = a; declares ans as reference to a
OUTPUT Its necessary to
cout<<"a="<<a<<endl; a=5 initialize the
cout<<"&a="<<&a<<endl; &a=0x6ffe34 Reference at the
time of declaration
cout<<"ans="<<ans<<endl; ans=5
cout<<"&ans="<<&ans<<endl; &ans=0x6ffe34
ans++;
cout<<"a="<<a<<endl; a=6
cout<<"ans="<<ans<<endl; ans=6
Reference Variable(Cont…)
 C++ references allow you to create a second name for the a
variable.
 Reference variable for the purpose of accessing and modifying the
value of the original variable even if the second name (the
reference) is located within a different scope.
Reference Vs Pointer
References Pointers
int i; int *p = &i;
int &r = i;

p
addr

r i
addr
A reference is a A pointer is a variable
variable which refers which stores the address
to another variable. of another variable.
Enumeration
Enumeration (A user defined Data Type)
 An enumeration is set of named integer constants.
 Enumerations are defined much like structures.

enum days{Sun,Mon,Tues,Wed,Thur,Fri,Sat};
0 1 2 3 4 5 6
Keyword
Tag
name Integer Values for symbolic constants

 Above statement creates days the name of datatype.


 By default, enumerators are assigned integer values starting with 0.
 It establishes Sun, Mon… and so on as symbolic constants for
the integer values 0-6.
Enumeration Behaviour(Cont…)
enum coin { penny, nickel, dime, quarter=100,
half_dollar, dollar};

The values of these symbols are


penny 0
nickel 1
dime 2
quarter 100
half_dollar 101
dollar 102
Enumeration Behaviour
enum days{ sun, mon, tue, wed, thu, fri, sat };
days today; variable today declared of type days

today = tue; Valid, because tue is an enumerator. Value 2 will


be assigned in today
today = 6; Invalid, because 6 is not an enumerator

today++; Invalid, today is of type days. We can not apply


++ to structure variable also
today = mon + fri; Invalid
Valid, days data type converted to int,
int num = sat;
value 6 will be assigned to num
num = 5 + mon; Valid, mon converted to int with value 1
Control Structures
Control Structures
 The if statement:
• Simple if statement
• if…else statement
• else…if ladder
• if…else nested
 The switch statement :
 The do-while statement: An exit controlled loop
 The while Statement: An entry controlled loop
 The for statement: An entry controlled loop
FUNCTIONS IN C++
Introduction
•Dividing a program into functions.
•a major principle of top-down, structured
programming.
•To reduce the size of the program.
•Code re-use.
•C++ function can be overloaded to make it
perform different tasks depending on the
arguments passed to it.
Introduction
continue…

Two types of Function:


Library Function : getch(),clrscr()
User Defined Function
void show( ); /* Function declaration OR Function Prototype*/
void main( )
{
----
show( ); /* Function call */
----
}
void show( ) /* Function definition */
{
----
---- /* Function body */
}
The main( ) Function

•The main( ) returns a value of type int to the


operating system by default.

•The functions that have a return value should use


the return statement for termination.

•Use void main( ), if the function is not returning any


value.
Function Prototyping

• The prototype describes the function interface to the


compiler by giving details such as:

• The number and type of arguments


• The type of return values.

• It is a template

• When the function is called, the compiler uses the template


to ensure that proper arguments are passed, and the return value
is treated correctly.
Function Prototyping continue…

•Function prototype is a declaration statement in the


calling program.

type function-name ( argument-list ) ;

•The argument-list contains the types and names of


arguments that must be passed to the function.
Function Prototyping
continue…

•Each argument variable must be declared


independently inside the parentheses.

float avg ( int x, int y) ; // correct


float avg ( int x, y) ; // illegal

•In a function declaration, the names of the


arguments are dummy variables and therefore they
are optional.
Function Prototyping continue…

float avg ( int , int ) ;

The variable names in the prototype just act as


placeholders and therefore if names are used, they
do not have to match the names used in the
function call or function definition.

void display( ); // function with an


void display(void); // empty argument list.
Functions - Example
• Function prototype #include <stdio.h>
• Like a variable declaration /* function prototype */
• Tells compiler that the function will
be defined later double product(double x, double y);
• Helps detect program errors
• Note semicolon!! int main()
• Function definition {
• Note, semicolon double var1 = 3.0, var2 = 5.0;
• Function return double ans;
• return statement terminates execution of ans = product(var1, var2);
the current function
• Control returns to the calling function
printf("var1 = %.2f\n"
• if return expression; "var2 = %.2f\n",var1,var2);
• then value of expression is returned printf("var1*var2 = %g\n", ans);
as the value of the function call }
• Only one value can be returned this way
/* function definition */
• Function call
• main() is the 'calling function' double product(double x, double y)
• product() is the 'called function' {
• Control transferred to the function code double result;
• Code in function definition is executed
result = x * y;
return result;
}
Types of User-defined Functions
in C Programming

• For better understanding of arguments and return in functions, user-defined


functions can be categorised as:
• Function with no arguments and no return value
• Function with no arguments and return value
• Function with arguments but no return value
• Function with arguments and return value.
Sr. No C function Syntax

int function ( int ); // function declaration


function ( a ); // function call
with arguments and with
1 int function( int a ) // function definition
return values
{statements;
return a;}

void function ( int ); // function declaration


with arguments and without function( a ); // function call
2
return values void function( int a ) // function definition
{statements;}

void function(); // function declaration


without arguments and
function(); // function call
3 without
void function() // function definition
return values
{statements;}

int function ( ); // function declaration


function ( ); // function call
without arguments and with
4 int function( ) // function definition
return values
{statements;
return a;}
Function with no arguments
and no return value
• #include<stdio.h>
• #include<conio.h>
• void area();
• void main()
• {
• area();
• getch();
• } Function with no arguments and no return
• void area() value
• {
float r, ar;
• printf("enter radius of circle");
• scanf("%f",&r);
• ar=3.14*r*r;
• printf("the area of circle is %f",ar);
• }
Function with Arguments but not Return
Value

• #include<stdio.h>
• #include<conio.h>
• void area(float r);
• void main()
• {
• float x;
• printf("enter radius of circle");
• scanf("%f",&x);
Function with arguments but no return
• area(x);
• getch();
value

• }
• void area(float r)
• {
• float ar;

• ar=3.14*r*r;
• printf("the area of circle is %f",ar);
• }
Function with Arguments and Return
Value

• #include<stdio.h>
• #include<conio.h>
• float area(float r);
• int main()
• {
• float x,ans;
Function with arguments and return
• printf("enter radius of circle");
• scanf("%f",&x);
value.
• ans=area(x);
• printf("%f the area of a circle is",ans);
• return 0; }
• }
• float area(float r)
• {
• float ar;
• ar=3.14*r*r;
• return(ar);
• }
Function with no arguments and
return value

• #include<stdio.h>
• #include<conio.h>
• float area();
• int main()
• { float ans;

• ans=area();
• printf("%f the area of a circle is",ans);
• return 0; Function with no arguments and
• }
• float area()
return value
• {
• float x,ar;
• printf("enter radius of circle");
• scanf("%f",&x);

• ar=3.14*x*x;
• return(ar);
• }
C++ Programming Recursion

• A function that calls itself is known as recursive function and the process of
calling function itself is known as recursion in C++ programming.
• Example of recursion in C++ programming
• Write a C++ program to find sum of first n natural numbers using recursion.
Note: Positive integers are known as natural number i.e. 1, 2, 3....n
• #include <iostream>
• using namespace std;
• int sum(int n);
• int main()
• {
• int num,add;
• cout<<"Enter a positive integer:\n";
• cin>>num;
• add=sum(num);
• cout<<add;
• }
• int sum(int n){
• if(n==0)
• return n;
• else
• return n+sum(n-1); /*self call to function sum() */
• }
• sum(5)
• =5+sum(4)
• =5+4+sum(3)
• =5+4+3+sum(2)
• =5+4+3+2+sum(1)
• =5+4+3+2+1+sum(0)
• =5+4+3+2+1+0
• =5+4+3+2+1
• =5+4+3+3
• =5+4+6
• =5+10
• =15
• Every recursive function must be provided with a way to end the recursion. In this
example when, n is equal to 0, there is no recursive call and recursion ends.
Recursion of Factorial Number
Call by Value

A function call passes arguments by value.


• The called function creates a new set of variables and copies the values of
arguments into them.

• The function does not have access to the actual variables in the calling
program and can only work on the copies of values.
#include<iostream>
//#include<conio.h>
uisng namespace std;
int swap(int ,int );
int main()
{ int a,b;
cout<<“enter a,b”;
cin>>a>>b;
swap(a,b);
return 0;
}
• int swap(int a,int b)
•{
• int t=a;
• a=b;
• b=t;
• cout<<a<<“ “<<b;
•}
Call by Reference

When we pass arguments by reference, the formal arguments in the called


function become aliases to the actual arguments in the calling function.

This means that when the function is working with its own arguments, it is
actually working on the original data.
#include<iostream>
using namespace std;
int swap(int &,int &);
int main()
{
int a,b;
cout<<“enter a,b”;
cin>>a>>b;
swap(a,b);
cout<<a<<b;
return 0;
}
• int swap(int &a,int &b)
•{
• int t=a;
• a=b;
• b=t;
•}
Inline Function

• We mentioned that functions save memory space because all the calls to the
function cause the same code to be executed
• The function body need not be duplicated in memory
• When compiler sees the function call, it normally generates a jump to the
function.
• At end of the function it jumps back to the instruction following the call.
• While this sequence of events may save memory space, it takes some extra
time.
• Syntax:- inline function-header
• {
• function body
• }

• Eg: inline double cube(double a)


•{
• return (a*a*a);
•}
Max. from 3 no. using Inline
Function

• #include<iostream.h>
• #include<conio.h>
• inline int max(int a,int b,int c)
• { return (a>b ?((a>c)?a:c) : ((b>c? b: c))); }
• int main()
• { int x,y,z;
• cout<<“Enter x,y,z”; Enter x,y,z
• cin>>x>>y>>z; 1 2 3
• cout<< “Max no is”<<max(x,y,z); getch(); }
Max no is3
Function Overloading

• Same thing for different purposes.


#include<iostream.h>
#include<conio.h>
void add(int ,int );
void add(float ,int );
void add(float ,float );
void main()
{
int a,b;
float c,d;
cout<<“Enter a,b,c,d”;
cin>>a>>b>>c>>d;
add(a,b);
add(c,a);
add(c,d);
getch();
}
void add(int a,int b)
{
cout<<a+b; }
void add(float c,int a)
{ cout<<c*a; }
void add(float c,float d)
{cout<<c/d; }
Storage Class Specifier
• It provides information about variable’s visibility and lifetime.
• It can be declared as……

• Auto
• Register
• Static
• External
Auto Storage Class

• Local variables which are declared inside a function.

• Memory space for local variable is automatically allocated


when function is executing and released as soon as it ends.

• Section of program where variable can be used is called


scope of variable. Local variables are given the storage class
auto by default.
• Example: int main() { auto int a,b; return 0;}
• OR
• int main() { int a,b; return 0;}
Example

#include<iostream.h>
#include<conio.h>
void test();
int main()
{ int a=5;
cout << a<<endl;
{ int a=10; //print 10
cout<<a<<endl; }
test();
return 0;
}
• void test()
•{
• int b=6; // local variable to test()
• cout<<b<<endl;
• getch();
•}

Output:

5 10 6
Register Storage Class

•Local variables stored in register instead of memory


as register is much faster than memory.

•Variable can be declared by register.

•register int a;

•It is just a request.


•It depends on compiler to store variable in register
or not.
Static Storage Class
• he static variable is initialized only once and exists till the
end of a program. It retains its value between multiple
functions call.

• The static variable has the default value 0 which is provided


by compiler.

• For defining static variable use static as keyword.


#include <iostream>
using namespace std;
void func() {
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{
func();
func();
func();
}
Extern Storage Class

•The extern storage class specifier allows you to


declare variables and functions that several source
file can use.

•It gives reference of global variable that is visible to


all the program files.

•Extern specifier is mostly used when there are two


or more files sharing same global variables or
functions.
• extern int globalvar; // declare that variable is defined in another file (Extern
variable)

• int globalvar=28; //Definition


//OR
• extern int globalvar=28; //Extern” specifier is optional.
Manipulators
Manipulators
• endl Manipulator
• setw Manipulator
• setfill Manipulator
• setprecision
Manipulaton
Previous Exam Questions

• What is function? Demonstrate types of function with their syntax.


• What is inline function? Explain with suitable example.
• Difference between call by value and call by reference.
• Explain call by value and call by reference with suitable example (swap program)
• Explain default argument with suitable example
• Difference between macro and inline function.
[email protected]
Thank You

You might also like