Swa1n Suen
Swa1n Suen

Reputation: 133

What is the return type of address-of (&) operator?

int main(){
    int i = 0;
    int *p = 123;
    return 0;
}

The error message is: invalid conversion from 'int' to 'int*' [-fpermissive] int *p = 123;

I know int *p = &i; could make this work, but how the complier convert the &i type to int * type (what return type of & is)?

Thanks for anyone explaining this to me!

Upvotes: 1

Views: 908

Answers (1)

cigien
cigien

Reputation: 60268

From the reference:

For an expression of the form

& expr

If the operand is an lvalue expression of some object or function type T, operator& creates and returns a prvalue of type T*, with the same cv qualification, that is pointing to the object or function designated by the operand.

So, the type of the expression &i is an int*, where i is of type int.


Note that for expressions of this form where expr is of class type, the address-of operator may be overloaded, and there are no constraints on the type that can be returned from this overloaded operator.

Upvotes: 3

Related Questions