#include <iostream>
using namespace std;

void someFunction(bool& a);

int main()
{
 bool a = true;
 
 someFunction(a);

 if( a )
 cout <<"a = true";

 else
 cout <<"a = false";
}

void someFunction(bool& a)
{
 a = false;
}

This will print out "a = false".

bool& a in the someFunction contains a memory address, no?
So how can you take a memory address = value?
Wouldn't that try to change the memory address into false in this case?

Recommended Answers

All 2 Replies

Please re-read the section in your textbook about references. Yes, the bool& is a reference and yes, it has a pointer in it at the machine code level, but it is always automatically deferenced.

If you're still wondering, a variable on the stack has an address, which points to a reserved section of memory. The process is veery similar to using dynamically allocated objects with pointers.

Hopefully this small example can clear up some of it:

#include <iostream>
using namespace std;
int main()
{
	int someInt = 0; //<-- memory allocated and initialized to 0.
	cout << &someInt << endl;//<-- print the address of someInt
	//^^ It really prints the address of the base of the allocated section of memory.
	int *dynamicInt = new int(0);//<-- memory allocated (on the heap) and initalized to 0.
	cout << dynamicInt << endl;//<-- print the address of dynamicInt

	//Assign both sections of memory the value of 1.
	someInt = 1;
	*dynamicInt = 1;//<-- here the pointer is "de-referenced"
	cout << "someInt = " << someInt << endl;
	cout << "dynamicInt = " << *dynamicInt << endl;

	//Create a reference to both.
	int &someRef = someInt;//<-- disregard the syntax with regard to the address
	int &otherRef = *dynamicInt;//

	//Modify both with the reference.
	someRef = 2;
	otherRef = 2;
	cout << "someRef = " << someRef << endl;
	cout << "otherRef = " << otherRef << endl;

	delete dynamicInt;//<-- free dynamically allocated memory.

	cout << "Press RETURN to continue." << endl;
	cin.get();
	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.