Thread: Static Variables VS Pointers

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    19

    Static Variables VS Pointers

    Below is the sample code that I am working with. In the tutorial that relates to this example the author is explaining the usage of static variables as it relates to variable scope.

    Code:
    #include <stdio.h>
    
    void func1(void);
    main()
    {
       int count;
       for (count = 0; count < 20; count++)
       {
          printf("At iteration %d: ", count);
          func1();
       }
    
       return 0;
    }
    void func1(void)
    {
       static int x = 0;
       int y = 0;
    
       printf("x = %d, y = %d\n", x++, y++);
    }
    What the code does is understood, my question is: should I rather send a pointer variable to the function or use a static variable? Is this just a rudimentary example, different methods to accomplish the same task, or something different altogether?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Well, a "static" variable within a function is "a global variable with limited scope".

    This means that the variable has a permanent storage, which makes it different from normal local variables, whic only have a storage space when inside that function.

    But they are also not global variables in the normal sense, because the variable is only available in the function.

    Yes, you can solve the same problem by passing a pointer to a variable into the function.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    19
    Thanks Mats, I appreciate the clarification.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Free.
    By chakra in forum C Programming
    Replies: 9
    Last Post: 12-15-2008, 11:20 AM
  2. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  3. Linking errors with static var
    By Elysia in forum C++ Programming
    Replies: 8
    Last Post: 10-27-2007, 05:24 PM
  4. Static variables
    By ashughs in forum C++ Programming
    Replies: 3
    Last Post: 10-26-2006, 09:21 AM
  5. Replies: 5
    Last Post: 11-19-2002, 07:49 PM