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?

4

2 回答 2

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

尽管 z 可能看起来是 0,但实际上不是,它实际上可以是任何值,并且完全取决于您使用的编译器。这是因为 z 的赋值具有未定义的行为。

未定义的行为来自序列点之间多次更改 x 的值。在 C++ 中,|| 运算符是一个序列点,这就是为什么 y 的分配按预期工作的原因,但是 + 运算符不是一个序列点。

C++ 中当然还有其他各种序列点, ; 是一个更突出的例子。

我还应该指出 ++ 运算符返回变量的先前值,即在此示例中

#include <iostream>

using namespace std;

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

为 y 打印的值为 0。

于 2012-12-01T12:57:48.497 回答
0

用另一种方式说同样的话。AC编译器可以自由实现

int z = x++ + x++;

作为

 z = x + x
 incr x
 incr x

或作为

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

您的编译器似乎正在使用第一个计划。

于 2012-12-02T20:15:50.437 回答