Home > Net >  Is *&var redundant?
Is *&var redundant?

Time:05-26

New to C and trying to understand use of * and &.

I think I understand that &*var is useful if I want to have a reference variable to a pointer as a function argument, or just as a reference variable to a pointer in general. What about if the & and * are flipped?

Is *& redundant in C ?

Here's some code:

#include <iostream>

using namespace std;

int main(){

    // example 1
    int num = 10;
    cout << *&num; // exact same as num?

    // example 2
    struct person
    {
        string name;
        int age;
    };

    person me[3];

    me[0].name = "my name";
    me[0].age = 321;

    cout << (*&me[0]).name << endl; // exact same as me[0].name?

    return 0;
}
  1. Is the use of *&var in the two cout's redundant because &var is an address and the * that comes before &var means to look at the variable the address is pointing to?

  2. If it is not redundant, what is the use of *&var in C ?

CodePudding user response:

In most cases, *&var (take the address of var, then dereference that address to access var) and &*var (dereference var to access the thing it points at, then take the address of that thing) are the same as just using var by itself.

However, a class type can overload operator& to return whatever address it wants, and overload operator* to return whatever reference it wants. These are the only cases where *&var and &*var may not be the same as var. This is common in smart pointers and iterators, for instance.

To account for the former case, C 11 introduced std::addressof() to take the address of an object regardless of whether or not it overloads operator&, eg:

*&var -> *std::addressof(var)
&*var -> std::addressof(*var)

  • Related