0

I have read on some stackoverflow questions that post or pre-incrementing a variable in a function call can result in undefined behavior.

Since in a vector, the array element access operator, operator[]() is a function call, is the same true for the following code example?

double p_step = 1.0 / (double)_progress_bar_chars.size();
int ixx = 0;
for(double p = 0.0; p < 1.0; p += p_step)
    _progress_bar_chars[ixx ++] = (p <= progress ? '=' : ' ');

Does the above code produce undefined behavior?

For reference:

std::vector<char> _progress_bar_chars;
_progress_bar_chars.resize(50);
double progress = 0.5;

Finally, does it matter that I use a std::vector here rather than a pure array or heap-allocated array?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • use it like this will not result in undefined behavior, maybe [this page](http://en.cppreference.com/w/cpp/language/eval_order) can help you more – apple apple Nov 25 '16 at 14:54
  • As `_progress_bar_chars[ixx ++]` is the same as `_progress_bar_chars.operator[](ixx ++)` I would say that this is question is a possible duplicate of http://stackoverflow.com/questions/598148/is-it-legal-to-use-the-increment-operator-in-a-c-function-call – Simon Kraemer Nov 25 '16 at 15:01

2 Answers2

4

The problem occurs when you increment the same variable twice, for example:

foo(i++, i++);

In this case, the second one is undefined

When using operator[] there is no undefined behaviour.

For more information: Is it legal to use the increment operator in a C++ function call?

Community
  • 1
  • 1
Emi Höss
  • 86
  • 4
  • 1
    More specifically, it is undefined in which order function arguments will be evaluated, so any argument having "side effects" is potentially dangerous. – Sven Nilsson Nov 25 '16 at 15:01
  • 1
    @SvenNilsson: Given `foo((*f1())++, ((*f2())++)` operations within f1() could not be interleaved with any other operations, and likewise operations within f2(), but the reads-modify-write sequences on the addresses returned by those functions could be interleaved in problematic fashion. If two things in the argument list for the same function call are both incremented, behavior will only be defined if they are disjoint. Otherwise the code may invoke nasal demons. – supercat Nov 25 '16 at 22:11
1

Using a pre or post increment doesn't affect the validity of the code.

The only important thing is that the resulting index is in-range for the vector or array

Bo Persson
  • 90,663
  • 31
  • 146
  • 203