In: Computer Science
write a simple program to demonstrate the use of
static type of variables in c++...
use comments to explain plz
Static Variables in Functions:-
#include <iostream>
#include <string>
using
namespace
std;
void
sample()
{
// static
variable
static
int
count = 0;
cout << count
<<
" "
;
// value is updated
and
// will be carried to
next
// function
calls
count++;
}
int
main()
{
for
(
int
j=0; j<5;
j++)
sample
();
return
0;
}
OUTPUT:-
0 1 2 3 4
Static Variables in Class:-
#include<iostream>
using
namespace
std;
class
Sample
{
public
:
static
int
i;
Sample()
{
//
Do nothing
};
};
int
Sample::i = 1;
int
main()
{
Sample
obj;
// prints value of
i
cout <<
obj.i;
}
OUTPUT:-
1
Class objects as static:
#include<iostream>
using
namespace
std;
class
Sample
{
int
r;
public
:
Sample()
{
r
= 0;
cout
<<
"Inside
Constructor\n"
;
}
~Sample()
{
cout
<<
"Inside
Destructor\n"
;
}
};
int
main()
{
int
y =
0;
if
(y==0)
{
Sample
obj;
}
cout <<
"End of main\n"
;
}
OUTPUT:-
Inside Constructor Inside Destructor End of main
Static functions in a class
#include<iostream>
using
namespace
std;
class
Sample
{
public
:
// static member
function
static
void
printMsg()
{
cout<<"Welcome
to
Sample!";
}
};
// main function
int
main()
{
// invoking a static
member function
Sample::printMsg();
}
OUTPUT:-
Welcome to Sample!