Syntax to define variables

 

  • Syntax to define a variable in C (same as in Java):

       data-type  variableName  [= initialValue] ;   

    Examples:

       int   x, y;
       float z = 4.0;        

     

     

Where can you place variable definitions ?   (1) inside a function

  • A variable can be defined inside a function:

      int  main(int argc, char *argv[] )               
      {
         int x;            // Local variables are defined      
         float y = 4.0;    // inside a function
    
         x = 0;   // OK to access inside the same function
      } 

  • Local variables: (a concept !)

    • Variables defined inside a function are local variables

  • Property of Local variables:

      • Local variables can only be accessed (= used) by statements inside the same function (a.k.a.: local scope)

Where can you place variable definitions ?   (2) outside a function

  • A variable can be defined outside a function:

      int x;            // Global variables are defined      
      float y = 4.0;    // outside a function
    
      int  main(int argc, char *argv[] )               
      {
         x = 0;  // OK
      }
    
      void func( )
      {
         y = 1;  // OK
      } 

  • Variables defined outside a function are global variables

    • There is only 1 copy of a global variable with the same name in each C program

  • Global variables can be accessed (= used) by statements in any function

DEMO: demo/C/set1/variables1.c

A global variable is similar to a class (static) variable in Java

  • A global variable in a C program has the same properties as a class/static variable in a Java program

  • The variable x in these programs behave exactly the same way:

      C program Java program
       int x = 1;      // Global variable 
          
       int main(int argc, char *argv[] )
       {
           x = 777;    // Update
                       // global variable
       }
      
      
      
      
      
       public class myClass
       {
           static int x = 1;
      
           static void main(String argv[] )
           {
               myClass.x = 777; 
                         // Update the class 
                         // (~= global) variable
           }
       }
      

  • Note:

    • There is only 1 copy of a class variable with the same name in a Java class

DEMO: demo/C/set1/variables1.java

Concept:   when are the local and global variables created

  • When are local variables created:

      • Each invocation of a function will create a new copy of all local variables defined in the function/method

      • I.e.:

        • Multiple invocations of a function/method (such as recursion) will create multiple copies of the local variables

  • When are global variables created:

      • Global variables are created at the start of execution of a computer program

      • There is one copy of each global variable throughout the entire execution of a computer program