1

Basically I'm wondering what the rules are for passing in pointers vs references to functions in C++. I couldn't find them stated anywhere. Can you pass a primitive type integer, for example, into a function expecting a pointer? Can't you only pass in pointers to methods expecting pointers?

walnut
  • 21,629
  • 4
  • 23
  • 59
  • 1
    Have you tried writing the code corresponding to the cases you are interested in, and compiling with full warnings/running to test? – nanofarad Feb 06 '20 at 00:24
  • 1
    Please do not post text in images. Copy-paste or (re-)type the text directly into the question instead. See [ask]. – walnut Feb 06 '20 at 00:25
  • Where in your example do you think a non-pointer is passed to a function expecting a pointer? I don't see any. – walnut Feb 06 '20 at 00:27
  • 1
    I don't see the connection between your question and the code supplied. If you have a specific question about what the code does, please state it. (BTW, the indicated answer of `3` is wrong) – Ken Y-N Feb 06 '20 at 00:27
  • 1
    Your image (which, as @walnut mentioned, shouldn't be here) has nothing to do with the question. BTW the answer is 2. – IMil Feb 06 '20 at 00:28
  • But `increment2` won't work. because the body should be `++*x;` – lakeweb Feb 06 '20 at 00:30
  • @lakeweb Incrementing the pointer one-past-the-object is allowed. – walnut Feb 06 '20 at 00:33
  • @walnut Yes, but it does nothing and looks goofy in context. I guess that is the point here. Thanks. – lakeweb Feb 06 '20 at 00:37
  • Only `increment2` expects a pointer. And the code passes one in. – jxh Feb 06 '20 at 00:37
  • 1
    @lakeweb Yes, both `increment1` and `increment2` are obviously *wrong* in the sense that they are never useful for anything, but as you said, this seems to me to be the point of the exercise. – walnut Feb 06 '20 at 00:39
  • Fairly certain this question actually wants to ask *What is the difference between a pointer and a reference function parameter*, and [this](https://stackoverflow.com/q/57483/315052) is close, but not quite a dup. – jxh Feb 06 '20 at 00:42
  • When in doubt, try running it. If the output doesn't make sense, try debugging it and look closely at what's going on. If that still doesn't make sense, then that's a good time to ask about the specifics. – TheUndeadFish Feb 06 '20 at 00:56

1 Answers1

0

A pointer is just a memory address and in c++ you can get the address of a variable by using the &. Here is an example

#include <iostream>

void increment(int& x)
{
    ++x;
}

void increment2(int* x)
{
    ++(*x);
}

int main()
{
    int i = 1;
    int * p = new int(1);

    increment2(&i);
    increment2(p);
    std::cout << i << std::endl;
    std::cout << *p << std::endl;

    increment(i);
    increment(*p);
    std::cout << i << std::endl;
    std::cout << *p << std::endl;
}

output

2
2
3
3

try it: https://godbolt.org/z/br9APq

Philip Nelson
  • 1,027
  • 12
  • 28