doubt in storage class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jeyshree
    New Member
    • Jul 2010
    • 75

    doubt in storage class

    Hai,
    I am jeyshree.W ill anyone please explain me when is the memory allocated for gloabal variable in the following snippets?
    #include<stdio. h>
    #include<conio. h>
    extern int a;
    main()
    {
    printf("%d",a) ;
    getch();
    }
    int a=10;
    OUTPUT:
    10
    and another one:
    #include<stdio. h>
    #include<conio. h>
    extern int a=10;
    main()
    {
    printf("%d",a) ;
    getch();
    }
    OUTPUT:
    10
    Please explain .Thanks in advance
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    "when is memory allocated"

    Are you looking for an answer that is true for typical compiler implementations or are you interested in only what is guaranteed by the C Standard?

    It would help me understand what you're asking for if you listed some of the possible options you can think of for when memory might be allocated.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Memory for global variables is allocated before main() starts.

      This is a global variable:

      Code:
      extern int val = 10;
      This is not:

      Code:
      extern int val;
      The first case creates a global variable with an intial value of 10 and the variable has external linkage.

      The second case tells the compiler that there is a variable named val that has external linkage but it's not in this file.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        In the following example, the extern statement serves only one purpose -- it allows a to be accessed from the main function. Without the extern statement, references to a from main would be forward references to line 5, which are not permitted in C. Line 1 could be deleted without altering the operation of the program if line 5 were moved to that position.
        Code:
        extern int a;
        int main() {
           ...
           }
        int a = 10;
        In the following example, the extern keyword is superfluous. There would be no change to the operation of the program if it were removed.
        Code:
        extern int a = 10;

        Comment

        Working...