0

1)what different between int &p= n and int *q = &n in this code they do same thing. 2)what do & exactly(maybe return addres variable or something different?)

    void foo(int &p){
        p++;
    }
    int main(){
    
        int n = 5;
    
    
        foo(n);
    
        int &p= n;
        int *q = &n;
    
        cout << *q;
        cout << p;
}
Dqqqos
  • 3
  • 2
  • `p` is a reference, `q` is a pointer. What `&` does exactly would take a very long time to explain. If you want to learn C++ properly you need a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – john Nov 12 '20 at 08:35

2 Answers2

1

int &p= n;

p here is a (non-const) int reference, that refer to the object of type int with an associated named n. See Reference declaration for details.

int *q = &n;

q here is an (non-const) pointer to an (non-const) int object, where the address of variable n is used to initialize the pointer; specifically by using the address-of operator & (&expr). The Pointer declaration for details.

dfrib
  • 70,367
  • 12
  • 127
  • 192
0

1)what different between int &p= n and int *q = &n

p is an lvalue reference to an object and q is a pointer to an object.

Some of the differences between references and pointers:

  • References cannot be made to refer to other objects; Pointers can be re-assigned to point to another object.
  • Pointers can point to null. A reference cannot refer to null.
  • Indirection through a reference is implicit, while indirection through a pointer requires the use of the indirection operator.

2)what do & exactly(maybe return addres variable?)

In a compound type name, & means that the type is a reference. In an expression, the unary operator & is the addressof operator.

eerorika
  • 232,697
  • 12
  • 197
  • 326