Question from the course:
Watch the parentheses around the argument of the ++ operator. Are they really needed? What will happen when you remove them?
Initially there was only one cout
expression. I added another one to see the difference, like so:
#include <iostream>
using namespace std;
class Class {
public:
Class(void) {
cout << "Object constructed!" << endl;
}
~Class(void) {
cout << "Object destructed!" << endl;
}
int value;
};
int main(void) {
Class *ptr;
ptr = new Class;
ptr -> value = 0;
cout << ++(ptr -> value) << endl;
cout << ++(ptr -> value) << endl;
delete ptr;
return 0;
}
My idea was to test it again without parentheses and see what is different:
...
cout << ++ptr -> value << endl;
cout << ++ptr -> value << endl;
...
The result is the same in both cases. Thus I conclude: No difference.
Can someone explain and correct please? Why would they ask that question if there is no difference? My feeling is there is a subtlety I am missing.
Result:
Object constructed!
1
2
Object destructed!
There is no difference because ->
has a higher precedence than ++
. This means that ++ptr -> value
is always parsed as ++(ptr->value)
.
Regardless of how the compiler will see your code, you shouldn't write it like that, because someone who doesn't know C++ operator precedence rules might think the code does something different from what it actually does. ++(ptr->value)
is far clearer.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments