Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Pointer allows you to dereference a memory address. A reference is the physical memory address variable.

If you have a variable and you want to pass-by-reference, making any changes to the original variable effect the originally allocated value.

You use a pointer for instance if you want to dereference a physical memory address as part of an array of allocated memory addresses.

  // reference example
  int value = 0;
  int value1 = &value;
  value1 = 2;
  // value should equal 2

  // pointer example
  int value[5] = {1,2,3,4,5};
  *value += 1;value++;
  *value += 1;value++;
  *value += 1;value++;
  *value += 1;value++;
  *value += 1;
  // should now be {2,3,4,5,6}


I'm not c++ programmer, so please correct me if I'm wrong, but I think that the reference example is not correct. Shouldn't it be as bellow?

    // reference example
    int value = 0;
    int& value1 = value;
    value1 = 2;
    // value should equal 2


Yes. And this subthread nicely proves the parent: At least half of people who claim to program in C++ can't.


That is more correct, yes.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: