Assign Value to Local Variable via Function


void setValue () {
theVariable = 10;
}

int main () {
int theVariable = 0;
setValue();
cout << theVariable; //Should display 10


I am trying to achieve the previous, how would I attempt it the best way?
I don't know why you are doin this but try the following:

#include<iostream>
using namespace std;

int theVariable;

void setValue () {
theVariable = 10;
}

int main () {
theVariable = 0;
setValue();
cout << theVariable; //Should display 10
return 0;
}
As you said, theVariable is "local" to main() function and the setValue() does not recognize/reset the value.
You either change the scope of the variable to global as suggested above,
or change the value by reference, meaning, either a pointer or reference type.
Pass the value by reference to function and let it change the passed-in value, then the main() would see the changed value.

Good luck :)
For example, create a function like:

1
2
3
4
void chval(int & the_changed, int the_new)
{
    the_changed = the_new;
}
And would I use the function as so:

1
2
3
4
5
6
int main()
{
int mainVar = 10;

chval(&mainVar,15);
}
Yes.
Topic archived. No new replies allowed.