static and auto variable declaration in C++ language
auto variable declaration in C++:
In auto type of data declaration, values of the variables declared in a function are not retained their value even after the execution of the function.
The program illustrates auto storage type, in which sum function will initialize with zero after every function call.
Program Code:
#include <iostream>
using namespace std;
void auto_fun();
int main()
{
int i;
for(i = 1 ; i<=4; i++)
{
auto_fun();
cout<<endl;
}
return 0;
}
void auto_fun()
{
auto int sum = 0;
int a;
cout<<"Input the value of a : ";
cin>>a;
sum=sum+a;
cout<<"The value of sum is : ";
cout<<sum;
}
The program output is tested on www.jdoodle.com
Output:
Input the value of a : 4
The value of sum is : 4
Input the value of a : 3
The value of sum is : 3
Input the value of a : 5
The value of sum is : 5
Input the value of a : 6
The value of sum is : 6
Static variable declaration in C++:
In static type of data declaration, values of the variables declared in a function are retained even after the execution of the function.
The program illustrates static storage type, in which sum function will retain after every function call.
Program Code:
#include <iostream>
using namespace std;
void static_fun();
int main()
{
int i;
for(i = 1 ; i<=4; i++)
{
static_fun();
cout<<endl;
}
return 0;
}
void static_fun()
{
static int sum = 0;
int a;
cout<<"Input the value of a : ";
cin>>a;
sum=sum+a;
cout<<endl;
cout<<"The value of sum is : ";
cout<<sum;
}
The program output is tested on www.jdoodle.com
Output:
Input the value of a : 4
The value of sum is : 4
Input the value of a : 3
The value of sum is : 7
Input the value of a : 5
The value of sum is : 12
Input the value of a : 6
The value of sum is : 18
Thanks
Mukesh Rajput
Post A Comment:
0 comments: