1

For my compiler class, we are gradually creating a pseudo-PASCAL compiler. It does, however, follow the same precedence as C. That being said, in the section where we create prefix and postfix operators, I get 0 for

int a = 1;
int b = 2;
++a - b++ - --b + a--

when C returns a 1. What I don't understand is how you can even get a 1. By doing straight prefix first, the answer should be 2. And by doing postfix first, the answer should be -2. By doing everything left to right, I get zero.

My question is, what should my precedence of my operators be to return a 1?

marcinx27
  • 243
  • 1
  • 3
  • 15
  • 1
    @marcinx27 Please, implement in your compiler such feature: when compiler sees code like this it automatically opens browser on a SO page linked above and also asks programmer if he want to re-read a C programming book. – Ivan Aksamentov - Drop Mar 10 '14 at 03:48

3 Answers3

1

Operator precedence tells you for example whether ++a - b means (++a) - b or ++(a - b). Clearly it should be the former since the latter isn't even valid. In your implementation it's clearly the former (or you wouldn't be getting a result at all), so you implemeneted operator precedence correctly.

Operator precedence has nothing to do with the order in which subexpressions are evaluated. In fact the order in which the operator operands to + and - are evaluated is unspecified in C and any code that modifies the same variable twice without a sequence point in between invokes undefined behavior. So whichever order you choose is fine and 0 is as valid a result as any other value.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

It is illegal to change variables several times in a row like that (roughly between asignments, the standard talks about sequence points). Technically, this is what the C standard calls undefined behaviour. The compiler has no obligation to detect you are writing nonsense, and can assume you will never do. Anything whatsoever can happen when you run the program (or even while compiling). Also check nasal demons in the Jargon File.

vonbrand
  • 11,412
  • 8
  • 32
  • 52
0

The ++ increment and -- decrement operators can be placed before or after a value, different affect. If placed before the operand (prefix), its value is immediately changed, if placed after the operand (postfix) its value is noted first, then the value is changed.

McGrath, Mike. (2006). C programming in easy steps, 2nd Edition. United Kingdom : Computer Step.

Joe DF
  • 5,438
  • 6
  • 41
  • 63