Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ arrow operator with pre-increment: With or without parentheses is the same?

Tags:

c++

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!
like image 962
Ely Avatar asked Jun 05 '15 08:06

Ely


People also ask

What is arrow operator explain with example in C++?

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.

Which of the following operator has the highest precedence in C Plus Plus?

In C, the ternary conditional operator has higher precedence than assignment operators.

What is the arrow operator in C++ called?

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.


1 Answers

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.

like image 117
TartanLlama Avatar answered Nov 07 '22 16:11

TartanLlama