Thursday, January 10, 2013

5.6. Conflicts in the names of the variables


What happens if we give the same name to two local variables? Let's see an example:

/*---------------------------*/
/*  C# Example #51:          */
/*  example51.cs             */
/*                           */
/*  Two local variables      */
/*  with the same name       */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example51
{

  public static void changeN() {
    int n = 7;
    n ++;
  }


  public static void Main()
  {
    int n = 5;
    Console.WriteLine("n is {0}", n);
    changeN();
    Console.WriteLine("Now n is {0}", n);
  }
 
}

The result of this program is:

n is 5
Now n is 5

Why? It is simple: we have a local variable within "changeN" and another in "main". The fact that both variables have the same name does not affect the behavior of the program, they are still different variables.

If the variable is "global", declared out of these functions, it will be accessible by all of them:

/*---------------------------*/
/*  C# Example #52:          */
/*  example52.cs             */
/*                           */
/*  A global variable        */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example52
{

  static int n = 7;

  public static void changeN() {
    n ++;
  }


  public static void Main()
  {
    Console.WriteLine("n is {0}", n);
    changeN();
    Console.WriteLine("Now n is {0}", n);
  }
 
}

We'll soon will discuss why each of the blocks of our program, and even the "global variables" are preceded by the word "static". It will be when we start talking about the "Object-Oriented Programming" in the next chapter.

No comments:

Post a Comment