SlideShare ist ein Scribd-Unternehmen logo
1 von 6
What is Storage Class?
Storage class defined for a variable determines the accessibility and longevity of the
variable. The accessibility of the variable relates to the portion of the program that
has access to the variable. The longevity of the variable refers to the length of time
the variable exists within the program.

Types of Storage Class Variables in C++:
•
Automatic
•
External
•
Static
•
Register
Automatic:
Variables defined within the function body are called automatic variables. Auto is the
keyword used to declare automatic variables. By default and without the use of a
keyword, the variables defined inside a function are automatic variables.
For instance:

void exforsys( )
{
auto int x;
auto float y;
………
…………
}

is same as

void exforsys( )
{
int x;
float y;
………
…………
}

//Automatic Variables

In the above function, the variable x and y are created only when the function
exforsys( ) is called. An automatic variable is created only when the function is
called. When the function exforsys( ) is called, the variable x and y is allocated
memory automatically. When the function exforsys( ) is finished and exits the control
transfers to the calling program, the memory allocated for x and y is automatically
destroyed. The term automatic variable is used to define the process of memory
being allocated and automatically destroyed when a function is called and returned.
The scope of the automatic variables is only within the function block within which it
is defined. Automatic variable are also called local variables.

External:
External variables are also called global variables. External variables are defined
outside any function, memory is set aside once it has been declared and remains
until the end of the program. These variables are accessible by any function. This is
mainly utilized when a programmer wants to make use of a variable and access the
variable among different function calls.
Static:
The static automatic variables, as with local variables, are accessible only within the
function in which it is defined. Static automatic variables exist until the program ends
in the same manner as external variables. In order to maintain value between
function calls, the static variable takes its presence.
For example:

#include <iostream.h>
int exforsys(int);
void main( )
{
int in,out;
while(in!=0)
{
cout<<”Enter input value:”;
cin>>in;
out=exforsys(in);
cout<”nResult:”<<out;
}
cout<”n End of Program”<<out;
}
int exforsys(int x)
{
static int a=0;
static int b=0;
a++;
b=b+x;
return(b/a);
}
In the above program, the static variables a and b are initialized only once in the
beginning of the program. Then the value of the variables is maintained between
function calls.

When the program begins, the value of static variable a and b is initialized to zero.
The value of the input in is 5 (which is not equal to zero) and is then passed to the
function in variable x. The variable a is incremented thus making a as equal to 1.
Variable b becomes equal to 5 and thus, the return of value from function exforsys( )
for the first time is 5, which is printed in the called function.

The second time the value of the input in is 7 (which is not equal to zero) and is
passed to the function in variable x. The variable a (which is declared as static) has
the previous value of 1. This is incremented and the value of a is equal to 2. The
value of b is maintained from the previous statement as 5 and new value of b now is
b=5+7 = 12 and thus, the return value from the function is 12/2=6 which is printed
in the called function.

Storage Classes.
C has a concept of 'Storage classes' which are used to define the scope (visibility) and life
time of variables and/or functions.
So what Storage Classes are available?
auto register static extern typedef

Auto - storage class
Auto is the default storage class for local variables.
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only be
used within functions, i.e. local variables.
Register - Storage Class
Register is used to define local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the register size (usually
one word) and cant have the unary '&' operator applied to it (as it does not have a
memory location).
{
register int Miles;
}
Register should only be used for variables that require quick access - such as counters. It
should also be noted that defining 'register' goes not mean that the variable will be stored
in a register. It means that it MIGHT be stored in a register - depending on hardware and
implementation restrictions.
Static - Storage Class
Static is the default storage class for global variables. The two variables below (count and
road) both have a static storage class.
static int Count;
int Road;
main()
{
printf("%dn", Count);
printf("%dn", Road);
}
'Static' can also be defined within a function. If this is done, the variable is initialized at
compilation time and retains its value between calls. Because it is initialsed at
compilation time, the initialization value must be a constant. This is serious stuff - tread
with care.
void Func(void)
{
static Count=1;
}
Here is an example
There is one very important use for 'static'. Consider this bit of code.
char *Func(void);
main()
{
char *Text1;
Text1 = Func();
}
char *Func(void)
{
char Text2[10]="martin";
return(Text2);
}
'Func' returns a pointer to the memory location where 'Text2' starts BUT Text2 has a
storage class of auto and will disappear when we exit the function and could be
overwritten by something else. The answer is to specify:
static char Text[10]="martin";
The storage assigned to 'Text2' will remain reserved for the duration if the program.

Extern - storage Class
extern defines a global variable that is visable to ALL object modules. When you use
'extern' the variable cannot be initalized as all it does is point the variable name at a
storage location that has been previously defined.
Source 1
-------extern int count;
write()
{
printf("count is %dn", count);
}

Source 2
-------int count=5;
main()
{
write();
}

Count in 'source 1' will have a value of 5. If source 1 changes the value of count - source
2 will see the new value.
'Func' returns a pointer to the memory location where 'Text2' starts BUT Text2 has a
storage class of auto and will disappear when we exit the function and could be
overwritten by something else. The answer is to specify:
static char Text[10]="martin";
The storage assigned to 'Text2' will remain reserved for the duration if the program.

Extern - storage Class
extern defines a global variable that is visable to ALL object modules. When you use
'extern' the variable cannot be initalized as all it does is point the variable name at a
storage location that has been previously defined.
Source 1
-------extern int count;
write()
{
printf("count is %dn", count);
}

Source 2
-------int count=5;
main()
{
write();
}

Count in 'source 1' will have a value of 5. If source 1 changes the value of count - source
2 will see the new value.

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Storage class in c
Storage class in cStorage class in c
Storage class in c
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Storage classes
Storage classesStorage classes
Storage classes
 
Functions in c
Functions in cFunctions in c
Functions in c
 
storage class
storage classstorage class
storage class
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
 
Storage class
Storage classStorage class
Storage class
 
Storage classes
Storage classesStorage classes
Storage classes
 
Function in C++
Function in C++Function in C++
Function in C++
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Storage classes
Storage classesStorage classes
Storage classes
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
 
Linq & lambda overview C#.net
Linq & lambda overview C#.netLinq & lambda overview C#.net
Linq & lambda overview C#.net
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Storage classes
Storage classesStorage classes
Storage classes
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programming
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Storage classes
Storage classesStorage classes
Storage classes
 
Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)
 

Andere mochten auch

Andere mochten auch (9)

Data type
Data typeData type
Data type
 
Loop and storage class
Loop and storage classLoop and storage class
Loop and storage class
 
Oops
OopsOops
Oops
 
Control structures
Control structuresControl structures
Control structures
 
Cursors
CursorsCursors
Cursors
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting Personal
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Ähnlich wie What is storage class

Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageJenish Bhavsar
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and AnswersDaisyWatson5
 
C language presentation
C language presentationC language presentation
C language presentationbainspreet
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdfKUNALHARCHANDANI1
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
Advanced C Programming Notes
Advanced C Programming NotesAdvanced C Programming Notes
Advanced C Programming NotesLeslie Schulte
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semKavita Dagar
 
Presentation on function
Presentation on functionPresentation on function
Presentation on functionAbu Zaman
 

Ähnlich wie What is storage class (20)

Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C Language
 
5.program structure
5.program structure5.program structure
5.program structure
 
C functions list
C functions listC functions list
C functions list
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
 
C language presentation
C language presentationC language presentation
C language presentation
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Function C++
Function C++ Function C++
Function C++
 
Advanced C Programming Notes
Advanced C Programming NotesAdvanced C Programming Notes
Advanced C Programming Notes
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-sem
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Functions
FunctionsFunctions
Functions
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 

Kürzlich hochgeladen

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Kürzlich hochgeladen (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

What is storage class

  • 1. What is Storage Class? Storage class defined for a variable determines the accessibility and longevity of the variable. The accessibility of the variable relates to the portion of the program that has access to the variable. The longevity of the variable refers to the length of time the variable exists within the program. Types of Storage Class Variables in C++: • Automatic • External • Static • Register Automatic: Variables defined within the function body are called automatic variables. Auto is the keyword used to declare automatic variables. By default and without the use of a keyword, the variables defined inside a function are automatic variables. For instance: void exforsys( ) { auto int x; auto float y; ……… ………… } is same as void exforsys( ) { int x; float y; ……… ………… } //Automatic Variables In the above function, the variable x and y are created only when the function exforsys( ) is called. An automatic variable is created only when the function is called. When the function exforsys( ) is called, the variable x and y is allocated memory automatically. When the function exforsys( ) is finished and exits the control transfers to the calling program, the memory allocated for x and y is automatically
  • 2. destroyed. The term automatic variable is used to define the process of memory being allocated and automatically destroyed when a function is called and returned. The scope of the automatic variables is only within the function block within which it is defined. Automatic variable are also called local variables. External: External variables are also called global variables. External variables are defined outside any function, memory is set aside once it has been declared and remains until the end of the program. These variables are accessible by any function. This is mainly utilized when a programmer wants to make use of a variable and access the variable among different function calls. Static: The static automatic variables, as with local variables, are accessible only within the function in which it is defined. Static automatic variables exist until the program ends in the same manner as external variables. In order to maintain value between function calls, the static variable takes its presence. For example: #include <iostream.h> int exforsys(int); void main( ) { int in,out; while(in!=0) { cout<<”Enter input value:”; cin>>in; out=exforsys(in); cout<”nResult:”<<out; } cout<”n End of Program”<<out; } int exforsys(int x) { static int a=0; static int b=0; a++; b=b+x; return(b/a); }
  • 3. In the above program, the static variables a and b are initialized only once in the beginning of the program. Then the value of the variables is maintained between function calls. When the program begins, the value of static variable a and b is initialized to zero. The value of the input in is 5 (which is not equal to zero) and is then passed to the function in variable x. The variable a is incremented thus making a as equal to 1. Variable b becomes equal to 5 and thus, the return of value from function exforsys( ) for the first time is 5, which is printed in the called function. The second time the value of the input in is 7 (which is not equal to zero) and is passed to the function in variable x. The variable a (which is declared as static) has the previous value of 1. This is incremented and the value of a is equal to 2. The value of b is maintained from the previous statement as 5 and new value of b now is b=5+7 = 12 and thus, the return value from the function is 12/2=6 which is printed in the called function. Storage Classes. C has a concept of 'Storage classes' which are used to define the scope (visibility) and life time of variables and/or functions. So what Storage Classes are available? auto register static extern typedef Auto - storage class Auto is the default storage class for local variables. { int Count; auto int Month; } The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables. Register - Storage Class Register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location). { register int Miles; }
  • 4. Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implementation restrictions. Static - Storage Class Static is the default storage class for global variables. The two variables below (count and road) both have a static storage class. static int Count; int Road; main() { printf("%dn", Count); printf("%dn", Road); } 'Static' can also be defined within a function. If this is done, the variable is initialized at compilation time and retains its value between calls. Because it is initialsed at compilation time, the initialization value must be a constant. This is serious stuff - tread with care. void Func(void) { static Count=1; } Here is an example There is one very important use for 'static'. Consider this bit of code. char *Func(void); main() { char *Text1; Text1 = Func(); } char *Func(void) { char Text2[10]="martin"; return(Text2); }
  • 5. 'Func' returns a pointer to the memory location where 'Text2' starts BUT Text2 has a storage class of auto and will disappear when we exit the function and could be overwritten by something else. The answer is to specify: static char Text[10]="martin"; The storage assigned to 'Text2' will remain reserved for the duration if the program. Extern - storage Class extern defines a global variable that is visable to ALL object modules. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined. Source 1 -------extern int count; write() { printf("count is %dn", count); } Source 2 -------int count=5; main() { write(); } Count in 'source 1' will have a value of 5. If source 1 changes the value of count - source 2 will see the new value.
  • 6. 'Func' returns a pointer to the memory location where 'Text2' starts BUT Text2 has a storage class of auto and will disappear when we exit the function and could be overwritten by something else. The answer is to specify: static char Text[10]="martin"; The storage assigned to 'Text2' will remain reserved for the duration if the program. Extern - storage Class extern defines a global variable that is visable to ALL object modules. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined. Source 1 -------extern int count; write() { printf("count is %dn", count); } Source 2 -------int count=5; main() { write(); } Count in 'source 1' will have a value of 5. If source 1 changes the value of count - source 2 will see the new value.