Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass by reference with increment operator

Hello all I have a very basic question while learning to code in c++.

I am reading about the difference between pass by reference and pass by value. I wrote a simplistic code to test it but it does something I didn't expect.

    #include <iostream>
    using namespace std;

    void MyIncr (float *x);
    int main() {
        float score = 10.0;
        cout << "Orignal Value = " << score << endl;
        MyIncr(&score);
        cout << "New Value = " << score << endl;
     }

     void MyIncr (float *x) {
        *++x;
     }

How come I get 10 for both couts? However if I change the function to be something like:

     void MyIncr (float *x) {
        *x += 1;
     }

I get 10 for the old value and 11 for the new, which is what I would have expected in the previous case as well.

like image 749
vkaushal Avatar asked Jan 27 '23 19:01

vkaushal


1 Answers

 void MyIncr (float *x) {
    *++x;
 }

Is undefined behavior in this context. You are incrementing the pointer first, then dereferencing it. When the pointer is incremented, it no longer points to a valid float object. Hence, dereferencing it is undefined behavior.

On the calling side, nothing happens to the pointer or the value of object the pointer points to. To increment the value of the object that the pointer points to, use ++(*x).

 void MyIncr (float *x) {
    ++(*x);
 }

It will be better to pass the object by reference. There will be less confusion.

 void MyIncr (float& x) {
    ++x;
 }
like image 145
R Sahu Avatar answered Feb 06 '23 15:02

R Sahu