Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variables defined and declared in one function in another function?

Tags:

c++

scope

Can anyone tell me how to access variables declared and defined in a function in another function. E.g

void function1()
{
   string abc;
}

void function2()
{
   I want to access abc here.
}

How to do that? I know using parameters we can do that but is there any other way ?

like image 246
Varun Chitre Avatar asked Aug 02 '12 18:08

Varun Chitre


2 Answers

The C++ way is to pass abc by reference to your function:

void function1()
{
    std::string abc;
    function2(abc);
}
void function2(std::string &passed)
{
    passed = "new string";
}

You may also pass your string as a pointer and dereference it in function2. This is more the C-style way of doing things and is not as safe (e.g. a NULL pointer could be passed in, and without good error checking it will cause undefined behavior or crashes.

void function1()
{
    std::string abc;
    function2(&abc);
}
void function2(std::string *passed)
{
    *passed = "new string";
}
like image 77
JoeFish Avatar answered Oct 09 '22 13:10

JoeFish


Make it global then both can manipulate it.

string abc;

void function1(){
    abc = "blah";
} 

void function2(){
    abc = "hello";
} 
like image 27
BenN Avatar answered Oct 09 '22 12:10

BenN