SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
Data Structure
               Scope of Variables



                      Prepared By..
       Kumar
Saurav Kumar                     Shaambhavi Pathak
        CS-
B. tech CS-Oil &Gas Info                 CS-
                                 B. tech CS-Oil &Gas Info

500016630                         500016891
R970211046                        R970211047
2011-
2011-2015                         2011-
                                  2011-2015
In very simple words, scope of a variable can be defined as a
validity of a variable or other identifier within which its
declaration has an effect.
A C program consists of multiple functions classes code
structures (like while, for, do-while loops).A Normal program
makes use of variables or other identifier under any functions for
manipulation or storage purposes.
Now, once the code is written it may or may not be accessible for
the other section of the code. This accessibility depends upon the
declaration of the variables that how it was declared and where it
was declared. This comes under variable scope
                                           scope.
There are different types of variable scope.
•Block Scope
 Block
•Function Scope
 Function
•Global Scope
•File Scope


Now, let us Get down To each of them One by One.
Block Scope


C program is divided into many blocks of codes. They are mostly embraced ({}).For
example, for loop has a statement block.

It is Also Said to have a local scope.

Look these codes:

#include<stdio.h> //header file

main()

{

    int i;                //local variable

    for(i=0;i<5;i++)

      {

             int j=i*i;

           printf(“nValue of j is %d”,j);

       }

      //printf(“nValue of j is %d”,j);

}
As seen from the output screen that if the comment statement is
not executed the program runs well in code blocks IDE.
Now,The Difference lies here…
#include<stdio.h>

main()

{

    int i;

    for(i=0;i<5;i++)

      {

             int j=i*i;

           printf(“nValue of j is %d”,j);

       }

      printf(“nValue of j is %d”,j);

}
Follows by an error..!!

The explanation behind this is that the variable j is only valid inside the for loop but
not outside.

This Concludes the Block Scope.



Function Scope
C program typically are structured with classes and codes called
function. Each function is capable of performing its own
prescribed task and takes in arguments and return a values and
further depends on which type is it.
Concept to know: Variable declared within a function is
accessible only under that function and those variables are called
local variables.
Look to this piece of code:
#include<stdio.h>

int fact(void);   //function declaration
main()

{

     int n,res;

     printf(“nEnter a no “);

     scanf(“%d”,&n);

     res=fact(n);

    printf(“nValue is %d”,res);

}

int fact (void)

{

int res;          //local variable in fact function

    if(n!=1)

      {

    res=n*fact(n-1);

     return(res);

      }

else

      {

return(1);

      }

}
Any Guess What the error would be..??

Its due to that we are neglecting the the function scope.

Lets try Improving our code..
#include<stdio.h>

int fact(int);

main()

{

     int n,res;

     printf(“nEnter a no “);

     scanf(“%d”,&n);

     res=fact(n);       //function call

    printf(“nValue is %d”,res);

}

int fact (int n)

{

int res;

    if(n!=1)

      {

    res=n*fact(n-1);
return(res);

   }

else

   {

return(1);

       }}




Now when we Corrected/declared local variable in fact function
the program runs well…!!
Thus we see that here in the function scope the local variable
once declared in one function is not accessible in any other
function.
This concludes the basic of Function scope.


Global Scope
A global scoped variable can be accessed through any Where in
the code irrespective of the function or file. It is usually placed
just below the source file.
It is also said to have a Program Scope.
Let us examine this code:
#include<stdio.h>

int array[5];        //global array declaration

void next(void); //function declaration

main()

{

    int a;

    for(a=0;a<=2;a++)

     {

            array[a]=a+1;     //inserting values in globally created array

        }

next();         //function call

printf(“n”);

for(a=0;a<5;a++)                           //loop for printing the stroed values in the array

     {

    printf(“t%d”,array[a]);

    }

}

void next(void)

{

    int b;

    for(b=3;b<=4;b++)

            {

                  array[b]=b+1;

            }
}




Hence From the above output it clearly shows that the global variable can be accessed throught any
piece of code.

However, if a variable name is declared same in two different scopes(i.e global and block),then any
change made inside the block code for that variable will change the value of the variable for that
variable inside the block. Same if any change is made outside the global variable’s value will be
altered..!!

Let us Examine this concept through the following code:

#include<stdio.h>

int out=50;                     //global variable

main()

{

    {

        int out=50;    //local variable

        out=out+50;

        printf("nTha value of variable out inside the block is %d",out);

    }

    printf("nThe value of out variable outside the block is %d",out);

}
The 1st output is 100 while the second output is 50.This example shows that block scope is valid
inside block (Note SAME NAME OF GLOBAL VARIABLE IS THERE
              Note:                                                THERE).

This Basically concludes the Global variables.



Now, before we begin with our next variable scope (file scope) we
must learn about variable storage classes
                                  classes.


Sometimes we need to mention or declare the variables according
to our programming needs.
 Variable storage class specifiers are used when declaring a variable
to give the compiler information about how a variable is likely to be
used and accessed within the program being compiled.
•Static
•Extern
•auto
•const
•volatile


Here we shall discuss only about static.


Static as a Variable storage Class
 It specifies that a variable is to be accessible only within the scope
of current source file when it is declared globally. when it is declared
under any function then it its value don’t die even after the
execution.
This was just to introduce Static as a variable storage class.
Now when static is either used with global variables or local
variables.
Let us see an example of static used with Global variable.
#include<stdio.h>
static int marks=100;    //static global variable
    main()
{
    //statements
}
Initially global variables could be used anywhere in the programme
or even in another file.
When we use static, this variable aquires file scope meaning that
this variable is valid only in the current file and not in any other file.
Now let us see an example of static used with local variable..
#include<stdio.h>

void fun();

main()

{

    int i;

    for(i=0;i<5;i++)

    {

        fun();

    }

}

void fun()

{

    static m=0;

    m++;

    printf("t%d",m);

}



If you got output as
1 1 1 1 1
Then, you need to look at your work again..!!
Due to the storage class static the value of m remains
conserved..!!
So here is the output :




This concludes the lesson.




Sources: http://www.learncpp.com/cpp-tutorial/43-file-scope-and-the-static-keyword/
             http://www.techotopia.com/index.php/Objective-C_Variable_Scope_and_Storage_Class

             http://icecube.wisc.edu/~dglo/c_class/scope.html

Contenu connexe

Tendances

Tendances (20)

07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
C function
C functionC function
C function
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in c
Function in cFunction in c
Function in c
 
Virtual function
Virtual functionVirtual function
Virtual function
 
lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
 
Function in c
Function in cFunction in c
Function in c
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and Functions
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Function lecture
Function lectureFunction lecture
Function lecture
 
Algorithm and Programming (Branching Structure)
Algorithm and Programming (Branching Structure)Algorithm and Programming (Branching Structure)
Algorithm and Programming (Branching Structure)
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Function in c program
Function in c programFunction in c program
Function in c program
 
What is storage class
What is storage classWhat is storage class
What is storage class
 

En vedette (15)

Proyecto apoyo
Proyecto apoyoProyecto apoyo
Proyecto apoyo
 
An Introduction to PEX Piping
An Introduction to PEX PipingAn Introduction to PEX Piping
An Introduction to PEX Piping
 
What is a Slab Leak?
What is a Slab Leak?What is a Slab Leak?
What is a Slab Leak?
 
Trabajo Valores
Trabajo ValoresTrabajo Valores
Trabajo Valores
 
มอก.18001
มอก.18001มอก.18001
มอก.18001
 
Mi red de comunicación
Mi red de comunicaciónMi red de comunicación
Mi red de comunicación
 
Presentation 26000
Presentation 26000Presentation 26000
Presentation 26000
 
Els dinosaures. Presentació per a fillets.
Els dinosaures. Presentació per a fillets.Els dinosaures. Presentació per a fillets.
Els dinosaures. Presentació per a fillets.
 
Software Entrenador
Software EntrenadorSoftware Entrenador
Software Entrenador
 
ISO14000
ISO14000ISO14000
ISO14000
 
Presentation ts 16949
Presentation ts 16949Presentation ts 16949
Presentation ts 16949
 
Presentation 18001
Presentation 18001Presentation 18001
Presentation 18001
 
Presentation haccp
Presentation haccpPresentation haccp
Presentation haccp
 
Trabajar el ataque organizado
Trabajar el ataque organizadoTrabajar el ataque organizado
Trabajar el ataque organizado
 
Presentation gmp
Presentation gmpPresentation gmp
Presentation gmp
 

Similaire à Data structure scope of variables

Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semKavita Dagar
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 
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
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxrajkumar490591
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variableimtiazalijoono
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and AnswersDaisyWatson5
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of ckinish kumar
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSivakumar R D .
 
Storage_classes_and_Scope_rules.pptx
Storage_classes_and_Scope_rules.pptxStorage_classes_and_Scope_rules.pptx
Storage_classes_and_Scope_rules.pptxCheriviralaNikhil
 
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptxSRKCREATIONS
 

Similaire à Data structure scope of variables (20)

Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-sem
 
5.program structure
5.program structure5.program structure
5.program structure
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
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 in C++
Function in C++Function in C++
Function in C++
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variable
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
functions
functionsfunctions
functions
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Storage class
Storage classStorage class
Storage class
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
 
Storage_classes_and_Scope_rules.pptx
Storage_classes_and_Scope_rules.pptxStorage_classes_and_Scope_rules.pptx
Storage_classes_and_Scope_rules.pptx
 
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptx
 

Dernier

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Dernier (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Data structure scope of variables

  • 1. Data Structure Scope of Variables Prepared By.. Kumar Saurav Kumar Shaambhavi Pathak CS- B. tech CS-Oil &Gas Info CS- B. tech CS-Oil &Gas Info 500016630 500016891 R970211046 R970211047 2011- 2011-2015 2011- 2011-2015
  • 2. In very simple words, scope of a variable can be defined as a validity of a variable or other identifier within which its declaration has an effect. A C program consists of multiple functions classes code structures (like while, for, do-while loops).A Normal program makes use of variables or other identifier under any functions for manipulation or storage purposes. Now, once the code is written it may or may not be accessible for the other section of the code. This accessibility depends upon the declaration of the variables that how it was declared and where it was declared. This comes under variable scope scope. There are different types of variable scope. •Block Scope Block •Function Scope Function •Global Scope •File Scope Now, let us Get down To each of them One by One.
  • 3. Block Scope C program is divided into many blocks of codes. They are mostly embraced ({}).For example, for loop has a statement block. It is Also Said to have a local scope. Look these codes: #include<stdio.h> //header file main() { int i; //local variable for(i=0;i<5;i++) { int j=i*i; printf(“nValue of j is %d”,j); } //printf(“nValue of j is %d”,j); }
  • 4. As seen from the output screen that if the comment statement is not executed the program runs well in code blocks IDE. Now,The Difference lies here… #include<stdio.h> main() { int i; for(i=0;i<5;i++) { int j=i*i; printf(“nValue of j is %d”,j); } printf(“nValue of j is %d”,j); }
  • 5. Follows by an error..!! The explanation behind this is that the variable j is only valid inside the for loop but not outside. This Concludes the Block Scope. Function Scope C program typically are structured with classes and codes called function. Each function is capable of performing its own prescribed task and takes in arguments and return a values and further depends on which type is it. Concept to know: Variable declared within a function is accessible only under that function and those variables are called local variables. Look to this piece of code: #include<stdio.h> int fact(void); //function declaration
  • 6. main() { int n,res; printf(“nEnter a no “); scanf(“%d”,&n); res=fact(n); printf(“nValue is %d”,res); } int fact (void) { int res; //local variable in fact function if(n!=1) { res=n*fact(n-1); return(res); } else { return(1); } }
  • 7. Any Guess What the error would be..?? Its due to that we are neglecting the the function scope. Lets try Improving our code.. #include<stdio.h> int fact(int); main() { int n,res; printf(“nEnter a no “); scanf(“%d”,&n); res=fact(n); //function call printf(“nValue is %d”,res); } int fact (int n) { int res; if(n!=1) { res=n*fact(n-1);
  • 8. return(res); } else { return(1); }} Now when we Corrected/declared local variable in fact function the program runs well…!! Thus we see that here in the function scope the local variable once declared in one function is not accessible in any other function. This concludes the basic of Function scope. Global Scope A global scoped variable can be accessed through any Where in the code irrespective of the function or file. It is usually placed just below the source file. It is also said to have a Program Scope.
  • 9. Let us examine this code: #include<stdio.h> int array[5]; //global array declaration void next(void); //function declaration main() { int a; for(a=0;a<=2;a++) { array[a]=a+1; //inserting values in globally created array } next(); //function call printf(“n”); for(a=0;a<5;a++) //loop for printing the stroed values in the array { printf(“t%d”,array[a]); } } void next(void) { int b; for(b=3;b<=4;b++) { array[b]=b+1; }
  • 10. } Hence From the above output it clearly shows that the global variable can be accessed throught any piece of code. However, if a variable name is declared same in two different scopes(i.e global and block),then any change made inside the block code for that variable will change the value of the variable for that variable inside the block. Same if any change is made outside the global variable’s value will be altered..!! Let us Examine this concept through the following code: #include<stdio.h> int out=50; //global variable main() { { int out=50; //local variable out=out+50; printf("nTha value of variable out inside the block is %d",out); } printf("nThe value of out variable outside the block is %d",out); }
  • 11. The 1st output is 100 while the second output is 50.This example shows that block scope is valid inside block (Note SAME NAME OF GLOBAL VARIABLE IS THERE Note: THERE). This Basically concludes the Global variables. Now, before we begin with our next variable scope (file scope) we must learn about variable storage classes classes. Sometimes we need to mention or declare the variables according to our programming needs. Variable storage class specifiers are used when declaring a variable to give the compiler information about how a variable is likely to be used and accessed within the program being compiled. •Static •Extern •auto •const
  • 12. •volatile Here we shall discuss only about static. Static as a Variable storage Class It specifies that a variable is to be accessible only within the scope of current source file when it is declared globally. when it is declared under any function then it its value don’t die even after the execution. This was just to introduce Static as a variable storage class. Now when static is either used with global variables or local variables. Let us see an example of static used with Global variable. #include<stdio.h> static int marks=100; //static global variable main() { //statements } Initially global variables could be used anywhere in the programme or even in another file.
  • 13. When we use static, this variable aquires file scope meaning that this variable is valid only in the current file and not in any other file. Now let us see an example of static used with local variable.. #include<stdio.h> void fun(); main() { int i; for(i=0;i<5;i++) { fun(); } } void fun() { static m=0; m++; printf("t%d",m); } If you got output as 1 1 1 1 1 Then, you need to look at your work again..!!
  • 14. Due to the storage class static the value of m remains conserved..!! So here is the output : This concludes the lesson. Sources: http://www.learncpp.com/cpp-tutorial/43-file-scope-and-the-static-keyword/ http://www.techotopia.com/index.php/Objective-C_Variable_Scope_and_Storage_Class http://icecube.wisc.edu/~dglo/c_class/scope.html