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!
The -> is called the arrow operator. It is formed by using the minus sign followed by a greater than sign. Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.
In C, the ternary conditional operator has higher precedence than assignment operators.
The -> (arrow) operator is used to access class, structure or union members using a pointer. A postfix expression, followed by an -> (arrow) operator, followed by a possibly qualified identifier or a pseudo-destructor name, designates a member of the object to which the pointer points.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With