Question:
How can I use the same variables in two different functions? C++?
2014-04-15 23:04:14 UTC
Here is an example:

int register_account()
{
string sUsername;
string sPassword;
string question;

cout << "Please enter your new user-name: ";
cin >> sUsername;

cout << "Please enter your new password: ";
cin >> sPassword;

cout << "Creating your account..." << endl;
cout << "Returning to home screen..." << endl;

cout << "Do you want to 'login'?" << endl;
cin >> question;

if(question == "login")
{
login();
}
}

int login()
{
string slUsername;
string slPassword;

cout << "Please enter your user-name: " << endl;
cin >> slUsername;

cout << "Please enter your password: " << endl;
cin slPassword;

if(slUsername == sUsername && slPassword == sPassword)
{
special_message();
}
}
Four answers:
Tommy
2014-04-16 04:40:33 UTC
you could just make them global variables but lots of people will tell you thats bad practice also its not really necessary in this case just pass them as arguments to the other function like this



if(question == "login")

{

login(sUsername, sPassword);

}



and then youll have to change your login function definition to allow arguments to be passed in like this



int login(string sUsername, string sPassword)

{

...all the login and password checking stuff you already have...

}



for more info on this type of thing see here

http://www.tutorialspoint.com/cplusplus/cpp_functions.htm



also unrelated to this but instead of only checking to see if they answer the login question with "login" you might also want to check if they answer with "yes" since thats how most people would answer that question for example



do you want to login

yes
2014-04-16 00:17:02 UTC
Define the variable in one file like: data_type variable_name;

And declare it global in the other file like: extern data_type variable_name;



eg

in demo1.cpp

int dummyVar;



in demo2.cpp

extern int dummyVar;



but this is a very poor practice I Do NOT recommend this
?
2014-04-16 08:57:23 UTC
put both functions in one file

declare your shared variables static at file scope (outside either function)



compile the two functions.

link them into the rest of your programme.



the static keyword will keep the local "globals" from being seen outside the file that it was in.



static int shared_int;

int my_funct1(...){



shared_int=2;

return x;

}

void my_funct2(...){



shared_int =3;

return;

}
2014-04-15 23:06:56 UTC
In the process of changing some code, I have spilt some functions into multiple files. I have the files controls.cpp and display.cpp and I would like to be able to have access to the same set of variables in both files.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...