fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. int x = 10;
  6. int* x_ptr = &x; //take the address of x, assign it to a pointer to an int (int *)
  7. int& x_ref = x; //create a reference to an integer (int&) and point it to x
  8.  
  9. x_ref = 12; //you can use refs just like the original variable, no need to dereference
  10. cout << x_ref << endl;
  11. *x_ptr = 14; //you have to dereference a pointer before you can assign a value to the object
  12. cout << *x_ptr << endl;
  13.  
  14. int y = 40;
  15. x_ptr = &y; //you can set a pointer to point to a different address
  16. cout << *x_ptr << endl;
  17. //&x_ref = y; //there's no way to point x_ref anywhere else, the compiler will actually use this fact to make various optimizations
  18.  
  19. return 0;
  20. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
12
14
40