2
#include <stdio>
int main(){      

       int x = 4;  
       int y = 3;  
       int z;

       z = x---y;
       printf("%d" , z);
       return 0;
}

The gcc compiler in Linux Mandriva evaluates it as (x--)-y. I am confused as to why is it so. It could have been x - (--y).

I know some of the answers would tell me to look at precedence tables. Ihave gone through all of them, still the doubt persists.

Please anybody clarify this.

Frank
  • 10,461
  • 2
  • 31
  • 46
Pritpal
  • 571
  • 1
  • 6
  • 11

3 Answers3

9

The C lexical tokeniser is greedy, so your expression is tokenised as

x -- - y

before precedence rules are applied.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Out of curiosity, is this a implementation defined behaviour or does the standard mandate it to be greedy? Can i rely on this behaviour on different platforms/compilers? – RedX Jul 14 '11 at 09:15
  • @RedX: I'm fairly certain you can rely on this. I can't find a specific reference, but the behaviour is implied by this lexer for C: http://www.lysator.liu.se/c/ANSI-C-grammar-l.html – Greg Hewgill Jul 14 '11 at 09:21
4

The rule is "when getting the next token, use the longest sequence of characters possible that constitute a valid token". So --- is -- followed by a - and not the other way around. Precedence has actually nothing to do with this.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
-1

x-- is stronger than --x , so it is compiled this way. Postfix is stronger than prefix.

See C Operator Precedence Table.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
powerMicha
  • 2,753
  • 1
  • 24
  • 31