2

Is iter++->empty() a legal expression?

iter is an iterator of a vector of strings.

I am asking because considering the precedence of the operators both -> and () should precede the postfix increment but I really don't know how the operands should be grouped.

On my compiler it works (the expression yields the empty() result for the first string and iter points to the second string) but I'm still wondering if it is Undefined Behaviour.

Edit

I just found the solution (I think):

iter++->empty() should be the same as (*iter++).empty()

therefore considering associativity and precedence rules the grouping should be:

(((*(iter++)).empty) ())

Is that correct?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138

3 Answers3

6

It's legal, but don't do it.

Asking yourself this question is reason enough to break it into two statements:

iter->empty();
iter++;
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • thank you. I am a newcomer to C++. This is a question in my primer and considering precedence, associativity and order of evaluation rules I was really confused. –  Nov 04 '13 at 10:52
0

Assuming the iterator it is valid, the expression it++->empty() is well-defined

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

Assuming that iter->empty() is a valid statement, the answer is yes. The post-increment operator doesn't change the type of iter, is simply increments it after the empty() method has been performed.

However, I'd recommend splitting it up into two statements, as (especially post-) increment statements often make your code less clear. So why not go for:

iter->empty();
iter++;
Yellow
  • 3,955
  • 6
  • 45
  • 74