3

I am trying to implement a simple compiler using flex & bison, and got stuck in the postfix notation. (The compiler should behave like the C++ compiler)

Here is the problem: Given the following code:

    int x = 0;
    int y = x++ || x++  ; //y=1 , x = 2 this is understandable

    int z = x++ + x++ ;  // z = 0 , x=2

the first line is fine because of the following grammar:

    expression = expression || expression; //  x=0
    expression = 0 || expression   // x= 1
    expression = 0 || 1  //x=2
    expression = 1 // x=2 
    y = 1

However, I don't understand why z=0.

When my bison grammar sees 'variable' ++ it first returns the variables value, and only then increments it by 1. I used to think thats how C++ works, but it won't work for the 'z' variable.

Any advice on how to solve this case?

Joe
  • 41,484
  • 20
  • 104
  • 125

2 Answers2

2
int z = x++ + x++;

Although z may appear to be 0, it is not, it could in fact be any value and will depend entirely upon the compiler you are using. This is because the assignment of z has undefined behaviour.

The undefined behaviour comes from the value of x being changed more than once between sequence points. In C++, the || operator is a sequence point which is why the assignment of y is working as expected, however the + operator is not a sequence point.

There are of course various other sequence points in C++, the ; being a more prominent example.

I should also point out that the ++ operator returns the previous value of the variable, that is in this example

#include <iostream>

using namespace std;

int main() {
    int x = 0;
    int y = x++;
    cout << y << endl;
    return 0;
}

The value printed out for y is 0.

ctor
  • 5,938
  • 2
  • 26
  • 37
  • Thank you for the fast reply. I am aware that y=0 in your example. The only thing that has me confused is the undefined behaviour of the C compiler. So essentially I have no way of knowing how the C compiler will act on similar occasions? – CrazyDiamond Dec 01 '12 at 13:15
  • Ahh sorry, I miss-read the statement you made at the bottom. There are many forms of undefined behaviour in C and C++. A list of some of the more common ones can be found on StackOverflow here http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-a-c-programmer-should-know-ab – ctor Dec 01 '12 at 13:17
0

Saying the same thing another way. A C compiler is free to implement

int z = x++ + x++;

as either

 z = x + x
 incr x
 incr x

or as

 int r1 = x;
 incr x
 z = r1 + x
 incr x

Your compiler appears to be using the first plan.

brian beuning
  • 2,836
  • 18
  • 22