Home > Back-end >  How can I pass the variables from int function 1 to another int function and add every time?
How can I pass the variables from int function 1 to another int function and add every time?

Time:11-23

I want to program a game where the user has 10 days. I have an int main and a LOT of int functions. The user can visit a lot of functions everytime easily and the functions represent the locations in the game. What I want to do is for the day to increase by 1 everytime I leave a location. lets say that my first location is function1, in here it will state that it is day 1, once i leave the location, it will bring me to another function and it will state day 2.

I havent tried to actually code it as I am a bit lost on how the other functions will know the values of the other. I think that the code I want will need to make use of pointers and paramenters but I'm not very sure on how to get that work. This is what I have for now.

int function1()
{
    
    int day = 1;
  
    
    printf ("today is day %d", day);
   
}


CodePudding user response:

The static keyword is one way to do it.

int function1()
{
    static int day = 0;  
    //this will only happen once, no matter how many times you call the function

    if(day <= 10)
    {
        day  ;
    }

    printf ("today is day %d", day);

    return day;
}

But since you're probably going to need that variable elsewhere in your program, it's likely best to make it global like so:

#include <stdio.h>
int day;  //it's global since it's declared outside of main.

int function1()
{
    if(day <= 10)
    {
        day  ;
    }

    printf ("today is day %d", day);

    return day;
}
int main()
{
   //your code goes here.
}

Be careful with this, since if you say int day in main thinking it refers to your gloabl variable day, you will be sorely mistaken.

#include <stdio.h>
int day; // global variable

int main()
{
    int day = 0;  
//this is a local variable that has nothing to do with the global variable "day".
}

CodePudding user response:

#include <stdio.h>
int sum (int a);
int main(){
 int day = 1;
 sum(day);
}
int sum (int a){
 a  = 1;
 printf("\n value of 'a' in the called function is = %d", a);
 return 0;
}

CodePudding user response:

In general it is nice to have all of your game's state collected into one global structure, that you initialize at startup, for example

struct GameState {
    int day;
    int health;
    int shield;
    int points;
} gs;

int main()
{
    gs.day = 1;
    gs.health = 100;
    gs.health = 0;
    gs.points = 0;
}

And all your functions can call a day incrementer when they're done:

int function1()
{
    while (doing_stuff)
    {
        // do stuff
        if (unexpected())
            return next_day();
    }

    return next_day();
}

And the helper function to increment the day count

int next_day()
{
    return gs.day  ;
}
  • Related