Thread: Static variables + Initialisation

  1. #1
    Eager young mind
    Join Date
    Jun 2006

    Static variables + Initialisation

    I felt I was a bit grey in this aspect and I found this :

    He says,
    "static' can also be defined within a function. If this is done, the variable is initalised at compilation time and retains its value between calls. Because it is initialsed at compilation time, the initalistation value must be a constant. "

    I just tried out a simple code where I didnt initialise the static variable. I was expecting some warning to be displayed when I compiled it with the -Wall option. Instead the static variable was initialised to 0.
    Can anyone shed some light on this.

    Here's the code :

     # include<stdio.h>
    int func()
            static int i;
            return (i);
    int main()
            int count=0;
            while(count < 5) {
                    printf(" count :%d, func = %u\n",count,func());
            return 0;
    And the output :

     count :0, func = 1
     count :1, func = 2
     count :2, func = 3
     count :3, func = 4
     count :4, func = 5
    In the middle of difficulty, lies opportunity

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    In the absence of an initialiser, zero will be used instead.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Eager young mind
    Join Date
    Jun 2006
    OK! Thanks for the clarification.
    In the middle of difficulty, lies opportunity

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. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Replies: 23
    Last Post: 07-09-2007, 04:49 AM
  4. static variables
    By swgh in forum C++ Programming
    Replies: 2
    Last Post: 08-28-2006, 06:35 AM
  5. Replies: 5
    Last Post: 11-19-2002, 07:49 PM