Thread: Static global variable acting as global variable?

  1. #1
    New User
    Join Date
    Jul 2004
    Posts
    1

    Question Static global variable acting as global variable?

    "Applying the specifier static to a global variable instructs the compiler to create a global variable known only to the file in which it is declared. This means that even though the variable is global, routines in other files have no knowledge of it and cannot alter its contents directly, keeping it from side effects." - C: The Complete Reference, by Herbert Schildt.

    Contents of "staticgl.c"

    #include <stdio.h>
    #include "static.h"
    int main()
    {
    int i;
    startat(10);
    for (i=0; i<5; i++)
    printf("%d %d\n", counter++, nextnumber()); /*How could it possible.*/
    return 0;
    }

    Contents of "static.h", Header file used in "staticgl.c".

    static int counter;

    void startat(int);
    int nextnumber(void);

    void startat(int x)
    {
    counter=x;
    }

    int nextnumber(void)
    {
    counter++;
    return counter;
    }

    Output:

    11 11
    13 13
    15 15
    17 17
    19 19
    19 19


    How the main() function in another file can access the 'counter' variable? I am using Turbo C 2.0 compiler.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I'd sure like to know exactly what the hell is wrong with all the new posters, who never read the board Announcements!

    The Complete Reference, by Herbert Schildt.
    *bursts out laughing* Not my first choice as a reference.

    Anyway...

    The answer to your question is very very simple, and can be summed up in one line:
    Code:
    #include "static.h"
    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    .
    Join Date
    Nov 2003
    Posts
    307
    The older version of Schildt seems to have a lot of, um, problems. I got a freebie on the newest version with C99 stuff, but haven't really looked. So, based on your comments I assume it has some issues as well and is destined for recycling....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  2. LNK2001 ERROR!!! need help
    By lifeafterdeath in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2008, 05:05 PM
  3. global variable turns zero
    By Roaring_Tiger in forum C Programming
    Replies: 5
    Last Post: 04-07-2003, 12:52 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM