Advertisement
BlackHawk74

Difference between pointers and references in C++ v2

Nov 5th, 2012
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. // Pointers and references syntax
  2. int x = 5;
  3. int& y = x; // y == x
  4. y++; // y == 6 && x == 6
  5. int * z = &x; // z is address of x
  6. int * zz = &y; // z == zz && *z == *zz && *z == 6 && *z == x && *z == y
  7. (*zz)++; //  x == 7 && *z == 7 etc.
  8.  
  9.  
  10. // References
  11. int x = 5, y = 10;
  12. int& z = x;
  13. z = y;
  14. ++y;
  15. // z == 10 && x == 10 && y == 11
  16.  
  17. // Pointers are nullable
  18. int * x = NULL; // OK
  19. int& x = NULL; // does not compile
  20.  
  21. // Const modifiers
  22. int * x0; // pointer to int
  23. ++x0; // OK
  24. ++(*x0); // OK
  25.  
  26. const int * x1; // pointer to constant int
  27. int const * x2; // same thing
  28. ++x1; // OK
  29. ++(*x1) // FAIL
  30.  
  31. int * const x3; // constant pointer to int
  32. ++x3; // FAIL
  33. ++(*x3); // OK
  34.  
  35. const int * const x4; // constant pointer to constant int
  36. int const * const x5; // same thing
  37. ++x4; // FAIL
  38. ++(*x4); // FAIL
  39.  
  40. const int const * xx; // should not compile
  41.  
  42. int & x6; // reference to int
  43. const int & x7; // reference to constant int
  44. int & const x8; // this doesn't make sense, I'm not sure that it compiles
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement