Thread: I want my functions to "remember" their integers

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    33

    Question I want my functions to "remember" their integers

    Hi! A beginner here. I've been dabbling in C programming for 1/2 a year now. I've been making a text adventure/IF game in C and it's going pretty well. But I have a a question about how to get a function to "remember" a integer value/s after the function has run all the way through?
    The way I've maneuvered around this problem is to loop infinitly and have the exit from the loop be a function call and another function call to get back to the calling function and have intergers still intact. How can I do this in a better way?

    Help would be much appreciated
    Last edited by sampleandhold; 02-29-2012 at 11:29 AM.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Make your function's variables static perhaps.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    33
    Quote Originally Posted by hk_mp5kpdw View Post
    Make your function's variables static perhaps.
    I don't know what that means? Is that a good solution?

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Declare it like this in your function:
    Code:
    static int x = 42;
    That means the first time your function is called, x starts with a value of 42. Whatever you change it to, that new value will be remembered, and next time you start the function, it will start with the new value. It wont be 42 every time.

    The technical way to describe such a variable is one having static duration, and local scope. Think of it like a hybrid local/global. It exists throughout the entire duration of the program (static duration). It's stored with any global variables, and follows the same rules of initialization, i.e. if uninitialized, it's zero, if initialized, it's initialized once at program start up, not every time the function starts. The difference between a static local and a global is that only the function with the static local declaration can see the variable (local scope).

    Note that this means there is only one copy of the variable for the entire program. That means this solution can cause problems if you're using recursive functions (functions that call themselves, or that call other functions that then call it), but can also help in recursive functions, depending on what you want to do with it. It can also be a problem with multi-threaded apps (probably not an issue for you).

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by sampleandhold View Post
    I don't know what that means? Is that a good solution?
    Yes, that is probably the ideal solution.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Registered User
    Join Date
    Feb 2012
    Posts
    33
    Quote Originally Posted by anduril462 View Post
    Declare it like this in your function:
    Code:
    static int x = 42;
    That means the first time your function is called, x starts with a value of 42. Whatever you change it to, that new value will be remembered, and next time you start the function, it will start with the new value. It wont be 42 every time.

    The technical way to describe such a variable is one having static duration, and local scope. Think of it like a hybrid local/global. It exists throughout the entire duration of the program (static duration). It's stored with any global variables, and follows the same rules of initialization, i.e. if uninitialized, it's zero, if initialized, it's initialized once at program start up, not every time the function starts. The difference between a static local and a global is that only the function with the static local declaration can see the variable (local scope).

    Note that this means there is only one copy of the variable for the entire program. That means this solution can cause problems if you're using recursive functions (functions that call themselves, or that call other functions that then call it), but can also help in recursive functions, depending on what you want to do with it. It can also be a problem with multi-threaded apps (probably not an issue for you).
    Thanks for the good explanation! (:

    Now I'm very curious if static variables will work with my program. When I started my program I wanted to use lots of global variables but the book I'm reading doesn't recommend
    using them. It also doesn't give any explanation why so I avoided them.

    From what I understood from your post there's only one copy of a static variable, does that mean I can't pass a static variable to another function?
    Can I make a pointer that points to a static variable? And then pass the pointer to a function that changes the static variable?

    Sorry that there's about forty questions here but I'm very excited about starting on the next level of my game and I want to program it better than the first part. I also have a desire to make a much better parser for the game but I havn't found any solutions to that yet. In the book I'm reading it says C is not so good when it comes to receiving input from the keyboard/user and that alot of C programmers get their user input routines from somewhere else. I'm wondering how to do that. But that's an entirely different thread.
    Last edited by sampleandhold; 02-29-2012 at 01:12 PM.

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    You can pass the value to another function but you aren't passing the actual variable. A pointer to a static variable passed into another function would allow the 2nd function to change the value of the variable in the 1st function.
    Code:
    #include <iostream>
    
    void foo2(int * bar)
    {
        *bar = *bar * 2;
    }
    
    void foo1()
    {
        static int var = 42;
    
        std::cout << "Before foo2 call, var is: " << var << std::endl;
        foo2(&var);
        std::cout << "After foo2 call, var is: " << var << std::endl;
    
        ++var;
    }
    
    int main()
    {
        foo1();
        foo1();
        return 0;
    }
    Attached Images Attached Images I want my functions to &quot;remember&quot; their integers-untitled1-jpg 
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by sampleandhold View Post
    Thanks for the good explanation! (:
    You're welcome.

    Now I'm very curious if static variables will work with my program. When I started my program I wanted to use lots of global variables but the book I'm reading doesn't recommend
    using them. It also doesn't give any explanation why so I avoided them.
    Read this: Global Variables Are Bad.

    From what I understood from your post there's only one copy of a static variable, does that mean I can't pass a static variable to another function?
    Can I make a static variable pointer?
    You can pass it to another function, because C passesby value, meaning that it passes a copy of the of the variable. Whatever you do in the function you passed it to, those changes only exist in that function, the original variable, static or not, is left alone. You can make any local variable static in this sense*, whether it be an int, double, array, pointer, struct or union. static is a type qualifier, meaning it just gives extra info/instructions about that variable, it is not a special type of variable on it's own. You can also make a pointer point to a static variable and change the static variables value through the pointer.

    * The 'static' keyword has a totally different meaning when applied to file-scope symbols (functions and global variables). IMO, it's was a poor design choice and is very confusing, but we must live with it. You probably don't need to worry about this too much.

  9. #9
    Registered User
    Join Date
    Feb 2012
    Posts
    33
    Quote Originally Posted by anduril462 View Post
    You're welcome.


    Read this: Global Variables Are Bad.


    You can pass it to another function, because C passesby value, meaning that it passes a copy of the of the variable. Whatever you do in the function you passed it to, those changes only exist in that function, the original variable, static or not, is left alone. You can make any local variable static in this sense*, whether it be an int, double, array, pointer, struct or union. static is a type qualifier, meaning it just gives extra info/instructions about that variable, it is not a special type of variable on it's own. You can also make a pointer point to a static variable and change the static variables value through the pointer.

    * The 'static' keyword has a totally different meaning when applied to file-scope symbols (functions and global variables). IMO, it's was a poor design choice and is very confusing, but we must live with it. You probably don't need to worry about this too much.
    All right! Thanks for the information. It really helped alot with a problem I had. I have one more question though. Does a static variable stay static when it's passed to another function?

  10. #10
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    The variable stays static for the entire time the program is running. But remember, when you pass that variable to another function, you don't pass the actual variable, you just copy the value. Think of the parameter in the other function as a local variable that gets initialized with whatever value you pass in. Retry hk_mp5kpdw's example from post #7 and observe the output. Then try it again, changing foo2() to the following, and observing the difference:
    Code:
    void foo2(int bar)
    {
        bar = bar * 2;
        printf("In foo2(), bar = %d\n", bar);
    }

  11. #11
    Registered User
    Join Date
    Feb 2012
    Posts
    33
    Quote Originally Posted by anduril462 View Post
    The variable stays static for the entire time the program is running. But remember, when you pass that variable to another function, you don't pass the actual variable, you just copy the value. Think of the parameter in the other function as a local variable that gets initialized with whatever value you pass in.
    I think I've found a good solution to make the value of the variable stays static after it's passed. It's simple but it's going to work!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    main()
    {
        int static var;
        var = 23;
    
    
        printf("The value of var is %d", var);
        fun2(var);
    }
    
    
    fun2(int var)
    {
        int static newVar;
        newVar = var;
    
    
        printf("\nnewVar is %d and it's static!", newVar);
    
    
        return 0;
    }

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by sampleandhold View Post
    I think I've found a good solution to make the value of the variable stays static after it's passed. It's simple but it's going to work!
    No it isn't, because you pass a value, then you assign it to another variable. That is not the original static variable. Look:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int fun2(int);
     
    int main()
    {
        int static var;
        var = 23;
     
     
        printf("The value of var is %d", var);
        fun2(var);
    
    	// let's see if they still have the same value
    	printf("in main, var is still %d\n", var);
    
    	return 0;
    }
     
     
    int fun2(int var)
    {
        int static newVar;
        newVar = var;
    
    	// make changes to the value of newVar
    	newVar += 10;
     
        printf("\nnewVar is %d and it's static!\n", newVar);
     
     
        return 0;
    }
    The value of var is 23
    newVar is 33 and it's static!
    in main, var is still 23

    If you want to keep the reference to the same variable, you need to use a pointer with the address where it is stored:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int fun2(int*);
     
    int main() 
    {
        int static var;
        var = 23;
     
     
        printf("The value of var is %d", var);
        fun2(&var);
    	// check var now
    	printf("The value of var is now %d\n", var);
    	return 0;  // return an int!
    }
     
     
    int fun2(int *var)
    {
    	// add to var
    	*var += 10;
        printf("\nvar is %d and it's static!\n", *var);
     
     
        return 0;
    }
    The value of var is 23
    var is 33 and it's static!
    The value of var is now 33
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Registered User
    Join Date
    Feb 2012
    Posts
    33
    Quote Originally Posted by MK27 View Post
    No it isn't, because you pass a value, then you assign it to another variable. That is not the original static variable. Look:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int fun2(int);
     
    int main()
    {
        int static var;
        var = 23;
     
     
        printf("The value of var is %d", var);
        fun2(var);
    
        // let's see if they still have the same value
        printf("in main, var is still %d\n", var);
    
        return 0;
    }
     
     
    int fun2(int var)
    {
        int static newVar;
        newVar = var;
    
        // make changes to the value of newVar
        newVar += 10;
     
        printf("\nnewVar is %d and it's static!\n", newVar);
     
     
        return 0;
    }
    The value of var is 23
    newVar is 33 and it's static!
    in main, var is still 23
    I didn't mean the original variable is static as parameter. But I can assign the value of the original static variable to a new static variable in the receiving function! This works for me!

    If you want to keep the reference to the same variable, you need to use a pointer with the address where it is stored:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int fun2(int*);
     
    int main() 
    {
        int static var;
        var = 23;
     
     
        printf("The value of var is %d", var);
        fun2(&var);
        // check var now
        printf("The value of var is now %d\n", var);
        return 0;  // return an int!
    }
     
     
    int fun2(int *var)
    {
        // add to var
        *var += 10;
        printf("\nvar is %d and it's static!\n", *var);
     
     
        return 0;
    }
    The value of var is 23
    var is 33 and it's static!
    The value of var is now 33
    If I wanted to change the original static variable I would do this!
    But what I want is to have a static variable value to work with in several functions. Different name, same purpose. Check out the code again.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    main()
    {
        int static var;
        var = 23;
    
    
        printf("The value of var is %d", var);
        fun2(var);
    }
    
    
    fun2(int var)
    {
        int static newVar;
        newVar = var;
    
    
        printf("\nnewVar is %d and it's static!", newVar);
    
    
        return 0;
    }
    Last edited by sampleandhold; 03-05-2012 at 04:27 PM.

  14. #14
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Setting the value of two static variables the same doesn't link them in any way whatsoever, they're still two totally separate values. But if I understand you, there is a better way. If you declare a variable in main and simply pass it around to the functions that need it, you get the same effect. The variable is created at the beginning of main, effectively when your program starts, and lives until the end of main, effectively when your program ends. Any function you call from main, and any functions that those functions call, directly or indirectly, can have access to that variable if you simply pass it to functions as needed. One variable, visible and changeable by any functions you want.

  15. #15
    Registered User
    Join Date
    Feb 2012
    Posts
    33
    Quote Originally Posted by anduril462 View Post
    Setting the value of two static variables the same doesn't link them in any way whatsoever, they're still two totally separate values. But if I understand you, there is a better way. If you declare a variable in main and simply pass it around to the functions that need it, you get the same effect. The variable is created at the beginning of main, effectively when your program starts, and lives until the end of main, effectively when your program ends. Any function you call from main, and any functions that those functions call, directly or indirectly, can have access to that variable if you simply pass it to functions as needed. One variable, visible and changeable by any functions you want.
    I know the variables aren't linked in anyway. But they will have the same value until I change one of them. And I don't want to change them. I want them to be static. They'll have different names but I'll use them for the same purpose in seperate functions.
    I want to use static variables because with a regular int variable, when I change it's value within the function and the function finishes. And when it gets called again it starts from the top and the variable is no longer what it was until it reaches the part where it's changed!

    For example if I change a variable called var1 to 3 in the middle of function1. And I call function2 and then I call function1 again. In function1 var1 won't be 3 anymore. I need to var1 to be 3 as soon as the function begins. So the function can execute in different ways depending on a variable value.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Shared "Integers"
    By RoshanX in forum C Programming
    Replies: 6
    Last Post: 10-21-2003, 08:38 AM
  2. Replies: 2
    Last Post: 05-23-2003, 02:46 PM
  3. "itoa"-"_itoa" , "inp"-"_inp", Why some functions have "
    By L.O.K. in forum Windows Programming
    Replies: 5
    Last Post: 12-08-2002, 08:25 AM
  4. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 07:59 AM