# Functions and Variables (C++)

This topic is 2402 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

void mysociety(){ cout << "Here is the current state of your society: \n\n"; //display current statistics cout << "The current population of your society is " << initpop << " humanoids." << endl; //user action cout << "\nEnter '1' if you would like to skip a number of years, '2' if you would like \nfurther information about your society or any other number if you would like to make changes to your society: "; int skiporchange; cin >> skiporchange; if(skiporchange == 1)timestepforward(); else if(skiporchange == 2)aboutyoursociety(); else changes();}

When I press '1' the timestepforward function is called. Its code is as follows:

void timestepfoward(){ otherfactors(); cout << "\n\nIt is currently year " << currentyear << " and the population is " << initpop << ".\n"; cout << "How many years would you like to skip? "; cin >> t; population(); currentyear = t+currentyear; cout << "\nIt is now year " << currentyear << " and the population is now " << newpopulation << ".\n"; newpopulation=initpop; mysociety(); } void population(){ popgrowth=(births-deaths)/initpop+1; newpopulation = initpop*exp( (births-deaths)/initpop * t ); }

My problem is that when I call the first function after doing a time step forward, (mysociety()), the global variable for initpop has not updated! Why is this?

##### Share on other sites
Show me the line that assigns a value to initpop. I don't see one.

##### Share on other sites
Hello,
 void timestepfoward(){ otherfactors(); cout << "\n\nIt is currently year " << currentyear << " and the population is " << initpop << ".\n"; cout << "How many years would you like to skip? "; cin >> t; population(); currentyear = t+currentyear; cout << "\nIt is now year " << currentyear << " and the population is now " << newpopulation << ".\n"; newpopulation=initpop; // shouldn't this line be: initpop = newpopulation; ? mysociety(); } 

##### Share on other sites
Ok so first of all I assign initpop to 1000 (otherwise the formula wouldn't work (if it were 0)) then after population() has run the newpopulation should be assigned to the initpop (initial population) so that the formula will work every time it is called.

unsigned int initpop=1000; //holds the population at the start of each period. unsigned int newpopulation;

##### Share on other sites
Why don't you post your complete code? That way we don't have to try and guess what you're doing with all these variables.

##### Share on other sites
One option is to package all your data into a "Society" type. This can be passed from and to functions. In this manner, you can make a stateless functions that describe and mutate the society.

Something like this
 struct Society { int population; int births; int deaths; int year; // ... }; Society timestepfoward(const Society &current) { otherfactors(/* may need to pass current here */); cout << "\n\nIt is currently year " << current.year << " and the population is " << current.population << ".\n"; cout << "How many years would you like to skip? "; int years; if(cin >> years) { Society next = timestepforward(current, years); cout << "\nIt is now year " << next.year << " and the population is now " << next.population << ".\n"; return next; } else { // Error handling } } Society timestepfoward(const Society &previous, int years) { Society next = previous; int growth = (next.births - next.deaths) / next.population + 1; next.population = next.population * exp( (next.births - next.deaths) / next.population * years ); next.year += years; return next; } void mysociety() { Society current = buildInitialSociety(); cout << "Here is the current state of your society: \n\n"; //display current statistics cout << "The current population of your society is " << current.population << " humanoids." << endl; //user action cout << "\nEnter '1' if you would like to skip a number of years, '2' if you would like \nfurther information about your society or any other number if you would like to make changes to your society: "; int skiporchange; cin >> skiporchange; if(skiporchange == 1) { current = timestepforward(current); } else if(skiporchange == 2) { aboutyoursociety(current); } else { // changes } } 

##### Share on other sites
This is my complete code.#include <iostream> #include <cmath> #include <math.h> #include <stdio.h> using namespace std; //MAIN FUNCTIONS: void intro(); // the introduction story sequence function void namefunc(); // adds HOIC to beginning of name, couts complete name void mysociety(); // sets the initial values for each factor/variable. void otherfactors(); //temporary function to effect births and deaths. void population(); // natural logarithm for population growth. void birthdeathrate(); //yearly birth and death rate void timestepfoward(); //performs all neccasary proceedures to fast foward time void changes();//main changes menu. void aboutyoursociety();//tells user about society. void initsetup(); //FACTOR FUNCTIONS: void politicalsystem();//executes poltical system algorithm. //CHANGE FUNCTIONS: void inputpoliticalsystemchanges();//allows user to implement political changes. //PRESENTING INFO FUNCTIONS: void politicsinfo();//states political info. //MAIN VARIABLES: double births;//births over a year double deaths;//deaths over a year double popgrowth; // population growth over a year (percentage) double t=0; //time in years int currentyear=0; //current year unsigned int initpop=1000; //holds the population at the start of each period. unsigned int newpopulation; char name[21]; // holds user input name int publicapproval; int economicrating; //CHANGE VARIABLES: int democracy=0; int dictatorship=0; int communist=0; int Politicsystemtype; //EXP VARIABLES: int politicalsystemexp; int main() { intro(); mysociety(); return 0; } void intro(){ cout << "The year is 2332...\n" << "The human population of earth has surpassed 15 billion.\n"; cout << "The world is on the brink of revolution and the Eurasian Alliance have decided\n"; cout << "that in order to secure the future of the human race, the Utopia Protocol must be initiated."; cout << "\n\n" << "The Utopia Protocol originated under president Elysia, the 60th president of theUnited States,"; cout << " as a reformation article and safeguard against the threat of \nmutually assured destruction during the 2073 energy crisis. "; cout << "\n\n" << "The protocol has recently been redesigned by the Alliance to make use of modern tecnology and engineering advances."; cout << "\n\n" << "It states that 'in order to ensure Humanity's prosperity and longevity, a \nUtopian society must be created'."; cout << " It continues, 'A large scale Utopian society \nmust be built, not simply initialised in order for it to be stable and \ncomplete'."; cout << " Recent advances in technology have allowed scientists to create \nhumanoids which replicate human behaviour with 99.9% accuracy."; cout << " These humanoids \nare capable of reproduction and decomposition."; cout << "\n\n" << "This is where you come in." << "\n\n" << "You are a H.I.N.C (Hive Intelligence Network Command),"; cout << " a highly advanced AI thatforms the subconcious of all humaniods. This gives you an indirect control over the entire humanoid population."; cout << "\n\n" << "You are based on one of around 200 habitable planets in the Milky Way where a \nH.I.N.C has been established."; cout << " You are tasked with creating a Utopian society in which humanity can eventually migrate to, replacing the humanoid population."; cout << "\n\n" << "Now, what would you like to be called? "; cin >> name; cout << "\nOkay "; namefunc(); cout << ", you have the power to create a paradise or a hell. \nAll the desions you make will have ramifications, be they positive or negative."; cout << " The decisions start here.\n\n\n\n"; initsetup(); } void namefunc(){ char hinc[]= "H.I.N.C: "; cout << hinc << name; } //****USER CHANGES**** //initial setup: void initsetup(){ } //loop options: void mysociety(){ cout << "Here is the current state of your society: \n\n"; //display current statistics cout << "The current population of your society is " << initpop << " humanoids." << endl; //user action cout << "\nEnter '1' if you would like to skip a number of years, '2' if you would like \nfurther information about your society or any other number if you would like to make changes to your society: "; int skiporchange; cin >> skiporchange; if(skiporchange == 1)timestepfoward(); else if(skiporchange == 2)aboutyoursociety(); else changes(); } //****CHANGES MENU**** void changes(){ cout << "\nWhich factor would you like to change?\n\n"; cout << "1. The political system" << endl; cout << "2. Investment in industries/resources" << endl; cout << "3. Religion" << endl; cout << "4. Education" << endl; cout << "\nEnter the number of the factor you would like to change: "; int factornum; cin >> factornum; switch(factornum){ case 1: inputpoliticalsystemchanges(); break; case 2: break; } //switch statement that allows access to changing each factor and ends by reverting to changes() or my } //****CHANGES FUNCTIONS**** void inputpoliticalsystemchanges(){ restart: cout << "\nYou have ten points to distribute amongst three systems: Democracy, Dictatorship and Communism."; cout << "\nHow many would you like to assign to Democracy? "; cin >> democracy; cout << "\nHow many would you like to assign to Dictatorship?" << " You have " << 10-democracy << " points left. "; cin >> dictatorship; cout << "\nHow many would you like to assign to Communism?" << " You have " << (10-democracy)-dictatorship << " points left. "; cin >> communist; if((democracy+dictatorship+communist)!=10) { cout << "\nYou failed to assign all the points correctly. "; goto restart;} else cout << "\n\nEnter '9' to return to the changes section. Or any other number to change these values again."; //change to switch. int back; cin >> back; switch(back){ case 9: changes(); break; default: goto restart; } } //****SOCIETY INFORMATION**** void aboutyoursociety(){ cout << "\nWhich element of your society would you like to know about? \n\n"; cout << "1. Illness" << endl; // etc. } //****SOCIETY INFO FUNCTIONS**** void politicsinfo(){ } //****TIME/EXPONENTIAL POPULATION GROWTH**** void timestepfoward(){ otherfactors(); cout << "\n\nIt is currently year " << currentyear << " and the population is " << initpop << ".\n"; cout << "How many years would you like to skip? "; cin >> t; population(); currentyear = t+currentyear; cout << "\nIt is now year " << currentyear << " and the population is now " << newpopulation << ".\n"; newpopulation=initpop; mysociety(); } void population(){ popgrowth=(births-deaths)/initpop+1; newpopulation = initpop*exp( (births-deaths)/initpop * t ); } void otherfactors(){ births = 24; deaths = 19; // will be more complex when taking other variables into account. } //****AUTOMATIC (changing according to user-inputed variables) FACTOR FUNCTIONS**** void politicalsystem(){ Politicsystemtype=((11*democracy)+dictatorship); //if pol syst > x and < y it is a Z - implement in an if else loop for all sytems. //Exp double politicalsystemexp1; double politicalsystemexp2; if(publicapproval >= 0.5) politicalsystemexp1 = publicapproval*10; if(economicrating >= 50) politicalsystemexp2 = economicrating/10; politicalsystemexp = politicalsystemexp1 + politicalsystemexp2; } //****EVENTS**** 
@rip-off I will give that a try later, thanks +1!

##### Share on other sites
initpop never changes because you don't assign it a value anywhere other than the initial value.

I don't see a "initpop = 1234" anywhere?

##### Share on other sites

Hello,
 void timestepfoward(){ otherfactors(); cout << "\n\nIt is currently year " << currentyear << " and the population is " << initpop << ".\n"; cout << "How many years would you like to skip? "; cin >> t; population(); currentyear = t+currentyear; cout << "\nIt is now year " << currentyear << " and the population is now " << newpopulation << ".\n"; newpopulation=initpop; // shouldn't this line be: initpop = newpopulation; ? mysociety(); } 

Actually that did fix it xD

##### Share on other sites
Removing all the global variables will help immensely.

Do not use GOTO, almost every usage of GOTO can be replaced with a normal loop instead. This usually makes the code easier to reason about.
 #include <cassert> int requestPoints(std::string prompt, int remaining) { if(remaining <= 0) { return 0; } int points; do { cout << "You have " << remaining << " points left.\nHow many would you like to assign to " << prompt << "? "; if(!cin >> points) { // Handle I/O errir } } while(points < 0 || points > MAX_POINTS); return points; } void inputpoliticalsystemchanges() { const int MAX_POINTS = 10; int back; do { cout << "\nYou have " << MAX_POINTS << " points to distribute amongst three systems: Democracy, Dictatorship and Communism."; democracy = requestPoints("Democracy", MAX_POINTS); int remaining = MAX_POINTS - democracy; dictatorship = requestPoints("Dictatorship", remaining); remaining -= dictatorship; communist = requestPoints("Communism", remaining); remaining -= communist; assert((democracy + dictatorship + communist) == 10); std::cout << "You chose:\n"; std::cout << "\tDemocracy: " << democracy << '\n'; std::cout << "\Dictatorship: " << dictatorship << '\n'; std::cout << "\Communism: " << communist << '\n'; cout << "\n\nEnter '9' to return to the changes section. Or any other number to change these values again."; if(!(cin >> back)) { // Handle I/O Error } } while(back != 9); changes(); } 

##### Share on other sites
the problem is this line of code
newpopulation=initpop;
initpop=newpopulation;
in the timestepfoward() function