C++ modifying variables from outside main()

Posts 1–3 of 3 · Page 1 of 1
C++ modifying variables from outside main()
i was wondering how to modify the following to make the loop end without using "return".
in otherwords im asking how to use "meow()" to directly edit "main()"s int1
Code:
void meow(int int1)
{
	int1 += 10;
	cout << int1 << endl;
}


int main()
{
	int int1 = 5;
	while(int1 < 100)
	{
	meow(int1);
	}

   system("pause");
    return 0;
}
Quote Originally Posted by utherson601 View Post
i was wondering how to modify the following to make the loop end without using "return".
in otherwords im asking how to use "meow()" to directly edit "main()"s int1
Code:
void meow(int int1)
{
	int1 += 10;
	cout << int1 << endl;
}


int main()
{
	int int1 = 5;
	while(int1 < 100)
	{
	meow(int1);
	}

   system("pause");
    return 0;
}
Use a reference.

Code:
void meow(int& int1)
{
	int1 += 10;
	cout << int1 << endl;
}


int main()
{
	int int1 = 5;
	while(int1 < 100)
	{
	meow(int1);
	}

   system("pause");
    return 0;
}
You can also use a pointer (less desired method in C++, but only method in C):


Code:
void meow(int* int1)
{
	*int1 += 10;
	cout << *int1 << endl;
}


int main()
{
	int int1 = 5;
	while(int1 < 100)
	{
	meow(&int1);
	}

   system("pause");
    return 0;
}
However, this deafeat the purpose of a function, which is to be more or less self-contained. Rarely should you use references in this sort of context.
thanks, i almost gave up on trying to do it..... i really need to remember this ....
Posts 1–3 of 3 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us