0

Found a weird behaviur on my code.

Code:

char foo[] = {64, 1};
int i = 0;

char c = ((foo[i]) | (foo[(++i)]));

cout << "Text: " << c << " " << (int)c << endl;

Results:

Text: ☺ 1

I was specting "Text: A 1" instead of "Text: ☺ 1". For some reason the compiler is ignoring the "| foo[++i]" part.

Well the solution for this is quite simple, it would just take another line, but what I'm interested in is to know if this is a compiler bug or just c++ being weird.

Tested in VC10 and VC11.

edit: Added () to the code, still the same behaviou.

TheVTM
  • 1,510
  • 13
  • 14
  • 2
    The order of the evaluations in `foo[i] | foo[++i]` is not specified. There are many questions about similar problems, e.g. [Undefined behavior and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). In your particular case, I guess `i` is first incremented (`++i`), and then you get `c = foo[1] | foo[1]`, which is `c = 1 | 1`, i.e. `c = 1`. Note that relying on unsequenced operations does not only make results hard to predict, but can cause undefined behaviour. – jogojapan Jun 19 '13 at 02:37
  • @jogojapan @jprofitt its not an eveluation ordening problem, because the result is the same when I do something like this `char c = ((foo[i]) | (foo[(++i)]));` – TheVTM Jun 19 '13 at 02:50
  • 2
    @TheVTM Brackets don't change the situation. You still have two arguments to the `|`-operator, and the order of evaluation for operator arguments (as well as function arguments) isn't specified by the Standard. – jogojapan Jun 19 '13 at 02:51

1 Answers1

0

The order of expression(not well-formed formula) is not documented in C++ standard. It depend on compiler behaviour. For example:

push(pop() * pop());

C++ doesn't document the order of calling pop(). So results are different in MSVC and GCC. You should call foo[i] and foo[++i] step-by-step.

mattn
  • 7,571
  • 30
  • 54