Local Vs Global variabls

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vidyagouri
    New Member
    • Sep 2009
    • 1

    Local Vs Global variabls

    Suppose that we have declared a global variable say int x in C language. A variable with the same name i.e., int x is also declared in a function so that it is a local variable to that function. Now, the question is how to access global value of x in that function?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Have a look at this recent thread.

    kind regards,

    Jos

    Comment

    • OraMaster
      New Member
      • Aug 2009
      • 135

      #3
      Originally posted by vidyagouri
      Suppose that we have declared a global variable say int x in C language. A variable with the same name i.e., int x is also declared in a function so that it is a local variable to that function. Now, the question is how to access global value of x in that function?
      Hello Vidya
      In C, the local variable takes precedance over the global, unless the global is declared static, in which case the local one cannot even be declared.

      Regds,
      Bhushan

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by OraMaster
        Hello Vidya
        In C, the local variable takes precedance over the global, unless the global is declared static, in which case the local one cannot even be declared.
        Who told you that nonsense?

        kind regards,

        Jos

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          No declaring a global static does not prevent you declaring a local variable with the same name, for example this is valid

          Code:
          #include <stdio.h>
          
          static void PrintGlobal(void);
          
          static int V1 = 5;
          
          int main()
          {
              int V1 = 10;
          	
          	printf("V1: %d\n", V1);
          	
          	PrintGlobal();
          	
          	return 0;
          }
          
          static void PrintGlobal(void)
          {
          	puts("Global Data");
          	printf("V1: %d\n", V1);
          }
          Output:
          V1: 10
          Global Data
          V1: 5

          Comment

          Working...