Search code examples
c++operator-precedence

How does the operator precendence of ++ vs -> work when incrementing incrementing a member int through a pointer?


A question for C++ language lawyers out there. It looks simple but I'm trying to figure out exactly what is going on in my simple program.

struct A
{
    int data1;
    int data2;
};

int main()
{
    A myA;
    A* ptr = &myA;
    ptr->data1 = 100;
    ++ptr->data1;                                                                                                                 

    std::cout << "A: " << myA.data1 << std::endl;
    return 1;
}

The above correctly works and outputs 101 on my gcc 4.8.2.

According to things I've read online the ++ and -> operator have the same level of precedence (https://msdn.microsoft.com/en-us/library/126fe14k.aspx), thus I would expect precedence to be followed left to right.

If I interpreted left-to-right precedence, then I'd expect ++ptr to execute first rather than ptr->data1. This would lead to markedly different (and incorrect) results.

What am I missing here?


Solution

  • http://en.cppreference.com/w/cpp/language/operator_precedence As u can see, the ++ operator what u used, a prefix operator and this have lower lever precedence than ->.

    Suffix operator are same level than ->.