Question

Currently learning c++ and nowhere else better to ask something than to the experts of S.O. I Couldn't find more complete and better answers than here. So there it goes.

DWORD dw = 5;
cout << &dw;

Displays the address where the value of dw is stored.

But then why:

void Display(  DWORD &dwUserId )
{
    cout << dwUserId;
}

int _tmain( int argc, _TCHAR* argv[] )
{
    DWORD dw = 5;
    Display( dw );
} 

Why on this example it is displayed the value of dw and not dw address?

Was it helpful?

Solution

& has two different meanings in this context:

  • placed in a declaration, it means the variable is a reference. In your case, you pass the parameter by reference.

  • outside a declaration, before a variable, it takes its address.

Besides these, it can also mean the bitwise AND operator

int x;
int& y = x;  //y is a reference to x
int* z = &x; //& takes the address of x and assigns it to z
y & x;       //bitwise AND

OTHER TIPS

DWORD &dwUserId as a parameter to a function is a reference to DWORD.

In C++, the & operator does two things, depending on context:

  • When used in an r-value expression, it returns the address-of a value. e.g. void* ptr = &myObject;
  • When used in a type specifier it modifies the type to be a "reference-of" type. This is similar to how references work in Java and .NET. e.g. int& ref = myInt;

In your case, your dwUserId parameter is actually of type "reference to DWORD".

If you want to change it to get the address then do this:

void Display(DWORD* userId) {
    cout << userId;
}

Display( &dw );

Also, please void TCHAR types. MBCS is deprecated. Win32 Unicode and wchar_t is the future :) Also avoid Hungarian notation. This isn't the 1980s. We have IDEs now.

Because when you use the & sign before a parameter name on a function definition you are telling the compiler to pass that parameter as a reference, i.e., don't make a copy of it.

When you use it before a variable name somewhere in the code you are telling the compiler to use the variable address instead of his value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top