Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Local and Global Variables

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 122
    Comment on it

    Local Variables: Variables that are defined within a function or a block are called local variables. They can only be used within a function or a block. These can't be accessed outside their scope or we can say outside their function.

    #include <stdio.h>
     
    int main () {
    
      /* local variable declaration */
      int x, y;
      int z;
     
      x = 20;
      y = 30;
      z = x + y;
     
      print ("value of x = %d, y = %d and z = %d\n", x, y, z);
     
      return 0;
    }

    The above example shows how the local variables are declared and how they are used. In this example, we have declared the local variables inside the main function which means that these variables are local to the main function and can only be accessed within the main function and not outside the main function.

    Global Variables: Global Variables are defined outside of any function.Global Variables can be accessed inside as well as outside of any function of the program and hold the values assigned to them throughout the lifetime of the program. It can be accessed by any function.

    #include <stdio.h>
     
    /* global variable declaration */
    int g;
     
    int main () {
    
      /* local variable declaration */
      int x, y;
      x = 40;
      y = 30;
      g = x + y;
     
      print ("value of x = %d, y = %d and g = %d\n", x, y, g);
     
      return 0;
    }

    Program can have same name for local and global variable but inside a function local variable will be give preference.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: