-4

The address of a variable can be directly accessed by Ampersand.Then why do we use pointers. Isn't that useless?

I have used ampersand and pointer and obtained the same output.

#include <iostream>
using namespace std;

int main()
{
    int score = 5;
    int *scorePtr;
    scorePtr = &score;
    cout << scorePtr << endl;
    cout << &score << endl;
   //output 
   //0x23fe44
   //0x23fe44
    return 0;
}
uv_
  • 746
  • 2
  • 13
  • 25
HMS
  • 96
  • 1
  • 2
  • 4
    Possible duplicate of [Pointers in C: when to use the ampersand and the asterisk?](https://stackoverflow.com/questions/2094666/pointers-in-c-when-to-use-the-ampersand-and-the-asterisk) – uv_ Dec 15 '18 at 12:38
  • _"Then why do we use pointers.Isn't useless?"_ There are rare edge cases in c++ where you really want to use raw pointers. – πάντα ῥεῖ Dec 15 '18 at 12:41

2 Answers2

3

Using the ampersand allows you to get the address of the variable, and a pointer allows you to keep it and pass it along in your application.

uv_
  • 746
  • 2
  • 13
  • 25
2

In simple code like your example there's no benefit to using pointers. In more complicated cases they're useful:

void increment_value(int *ptr) {
    if (ptr)
        (*ptr)++;
}

int main() {
    int i = 3;
    increment_value(&i);
    std::cout << i << '\n'; // i is 4
    int j = 5;
    increment_value(&j);
    std::cout << j << '\n'; // j is 5
    increment_value(nullptr); // harmless
    return 0;
}

The benefit here is that you can call the same function and apply it to different variables by passing a pointer.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Technically, even the example written in the question does the same, on line `cout << &score << endl;`, due to it invoking overload of `operator<<` that accepts a pointer. :) – Algirdas Preidžius Dec 15 '18 at 14:18
  • @AlgirdasPreidžius — no, you’ve missed the point. The stream inserter takes its argument by **value**. It does not display the content of the pointee. Please don’t muddle this issue further. – Pete Becker Dec 15 '18 at 18:32
  • 1) "_The stream inserter takes its argument by value._" In the same way, as it does (since the overload, that gets invoked is `basic_ostream& operator<<( const void* value );`), take the pointer by value, your does the same. 2) "_It does not display the content of the pointee_" I fail to see how doing a specific thing to a pointee, is related to a question. It is about a pointer, as a type, in general. – Algirdas Preidžius Dec 15 '18 at 19:52