Search code examples
c++castingoperator-overloadingc-stringsvoid-pointers

Why does `(void *)&` get the address of the variable?


Could someone explain the logic behind this? Why void? For example

#include <iostream>
using namespace std;
int main()
{
    char c;
    cout << (void *)&c;
    return 0;
}

Solution

  • cout << (void *)&c;
    

    takes the address of c, then casts it to void*, then prints pointer.

    The intent here is to print the address of variable c. But when passing a char * to std::cout << it will attempt to print a null-terminated string. To avoid this (and print the actual address) you have to cast to void* first.


    More explanation:

    std::ostream::operator<< has overload (2) that handles char * and const char*. It assumes that a const char* will point to some string that is eventually terminated by a null-character '\0'. That's simply a convention used in C and C++.

    You want to avoid this and instead use overload (7) to print the address.