C ++ Simple shorthand with pointers (puzzled)
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.
source to share
You expect (* x) - and you get * (x--). Cause Priority of operations . Look for this. pre and post increment bind before the "dereference address".
source to share
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.
source to share