Thread: static varibales simple qns

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    17

    static varibales simple qns

    Hi all,

    I have a doubt that id like to clear on

    say in a program ur given something like this
    Code:
      
        int x=1;
      int main() {
    
     ....
    
     then in a function :
    
        funct() {
    
         static int x =10;
    
         x++;
    
          printf("The value of x is %d", x);
    
        }
    does the value of the x change after incrementing it?

    I mean isnt it static so it wouldnt change?

    thanks for ur reply

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    596
    Static doesn't mean that it can't change. This use of static means that the variable is initialized only once, and retains its value in between calls to the function. So if it is incremented during one function call the incremented value is remembered, so on the next call to the function, it starts off with the incremented value. In your example, the static variable x in the function is completely different from the global variable x.

    Fix it by giving funct() a return type of void. Then try running it, calling funct several times in main & you will see:
    The value of x is 11The value of x is 12...

  3. #3
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    For the 1000-millionth time: You don't have a doubt, but a question. You can BE IN DOUBT. Doubt is just not something you can "have".
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  4. #4
    Registered User
    Join Date
    Feb 2003
    Posts
    596
    Quote Originally Posted by claudiu View Post
    For the 1000-millionth time: You don't have a doubt, but a question. You can BE IN DOUBT. Doubt is just not something you can "have".
    I have my doubts about that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  2. Linking errors with static var
    By Elysia in forum C++ Programming
    Replies: 8
    Last Post: 10-27-2007, 05:24 PM
  3. Replies: 23
    Last Post: 07-09-2007, 04:49 AM
  4. Static functions.... why?
    By patricio2626 in forum C++ Programming
    Replies: 4
    Last Post: 04-02-2007, 08:06 PM
  5. Linker errors with simple static library
    By Dang in forum Windows Programming
    Replies: 5
    Last Post: 09-08-2001, 09:38 AM