22 Jan C – Variable Scope
The existence of a variable in a region is called its scope, or the accessibility of a variable defines its scope. The scope of Variables is of utmost importance while accessing variables. We will discuss global and local variables below.
Local Variables
Whenever a variable is defined in a function or a block, it can be used only in that function or block. The value of that variable cannot be accessed from outside the function. Let us see an example wherein we will create and initialize local variables. We will also see how to access and use local variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <stdio.h> int main () { // Declaring four local variables int p, q, r; int s; // Initializing the variables p = 2; q = 5; r = 7; s = p * q * r; // Display the variables printf ("p = %d",p); printf ("\nq = %d",q); printf ("\nr = %d",r); printf ("\ns (Multiplication Result) = %d",s); return 0; } |
Output
1 2 3 4 5 6 |
p = 2 q = 5 r = 7 s (Multiplication Result) = 70 |
Global Variables
A variable has Global Scope, if it is defined outside a function i.e., the code body, and is accessible from anywhere. Let us see an example wherein we will learn how to create and work with global variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <stdio.h> // Declaring a global variable int s; int main () { // Declaring three local variables int p, q, r; /* Initializing the variables p, q, r are local variables s is a global variable */ p = 2; q = 5; r = 7; s = p * q * r; // Display the variables printf ("p = %d",p); printf ("\nq = %d",q); printf ("\nr = %d",r); printf ("\ns (Multiplication Result) = %d",s); return 0; } |
Output
1 2 3 4 5 6 |
p = 2 q = 5 r = 7 s (Multiplication Result) = 70 |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments