C ++ Simple shorthand with pointers (puzzled)

I am a little puzzled by this behavior. Can anyone explain

  void Decrement(int* x){
        *x--; //using this line, the output is 5 

        //*x=*x-1; //using this l ine, the output is 4

    }

    int main(){
        int myInt=5;
        Decrement(&myInt);
        cout<<myInt<<endl;
        return 0;
    }

    Output: 5

      

+3


source to share


6 answers


*x--

means *(x--)

. That is, your program is modifying x

, not what it points to. Since it passed by value, this modification does not affect main()

. To match your commented line you need to use (*x)--

.



+8


source


Try it (*x)--;

.



Your code decrements the pointer, then plays it out and discards the value.

+3


source


This is an operator priority issue.

The operator --

takes precedence over the dereference operator ( *

). So what you are actually doing is just access the value in one memory location below the x location (and do nothing with it).

What I feel you probably want to do is pass x "by reference". It will look like this:

void Decrement(int& x){
    x--;
}

int main(){
    int myInt = 5;
    Decrement(myInt);
    cout << myInt << endl;
    return 0;
}

      

When you pass a value by reference, C ++ will automatically play out the pointer for you, so it's *

no longer required in the Decrement function.

+2


source


You expect (* x) - and you get * (x--). Cause Priority of operations . Look for this. pre and post increment bind before the "dereference address".

+2


source


Basically you are passing a pointer x

by value. As a result, the change in x

(and not in what it points to) in the function is void Decrement(int*)

not reflected in main()

. This code will achieve what you intended to do:

void Decrement(int& x)
    {
        x--;

    }

int main()
    {
        int myInt=5;
        Decrement(myInt);
        cout<<myInt<<endl;
        return 0;
    }

    Output: 4

      

This is a call by reference, through which a link (or address) to a variable is passed.

+2


source


The expression is *x--

equivalent *(x--)

.

+1


source







All Articles