0
#include<iostream>
#define LOG(x) std::cout<<x<<std::endl
void increment(int value)
{
    ++value;
    
}
int main()
{
    int a = 6;
    increment(a);
    LOG(a);
    std::cin.get();
}

I press F11 and debug into the function of "increment".The parameter of function equal to 6.But why the "value++"doesn't work .I know it is called "pass by value",but I think local value should change in the function of body.

#include<iostream>
    #define LOG(x) std::cout<<x<<std::endl
    void increment(int& value)
    {
        ++value;
        
    }
    int main()
    {
        int a = 6;
        increment(a);
        LOG(a);
        std::cin.get();
    }

here I pass by reference and the value plus one. Is that the reason the compiler can not get the address of "++value",so it will be discarded,sorry for the fist submit.

herring
  • 21
  • 6
  • 2
    Because it is passed by value and not by reference. A copy is sent, modified to 7 and destroyed upon return. Not the actual object in main was modified. – Tony Tannous Aug 18 '20 at 10:42
  • I only see one example. – molbdnilo Aug 18 '20 at 10:51
  • Tony ,I agree with you ,no better explanation – herring Aug 18 '20 at 11:04
  • Tannous,if I pass by reference,you can see it in the next example . In the second situation ,Does the "++value" mean the address or value change? – herring Aug 18 '20 at 11:12
  • @herring Value change, references are not pointers so there is no address to change. I'm afraid I not sure what you mean by `the compiler can not get the address of "++value"` You are misunderstanding something there but I'm not sure what it is. – john Aug 18 '20 at 11:15
  • @john Beacause it is passed by reference,so we can find the address of "++value" in the second example. And we can only find the value in the first example. So, I want to express that. – herring Aug 18 '20 at 11:23
  • In the first example, `increment` has its own `value` distinct from `a` in the caller `main`. In the second example, `increment` has `value` which is an *alias* to `a` -- they are one-and-the-same. (I'm trying to use vernacular terminology, not C++ language standard terminology.) – Eljay Aug 18 '20 at 11:40
  • `because it is passed by reference, so we can find the address of "++value"` If you want to find the address of something you need to use the address-of operator `&`, so `&value` or `&++value` but the latter only works because prefix `++` returns a reference, not because `value` was passed by reference. – john Aug 18 '20 at 14:51

0 Answers0