Pritpal
Pritpal

Reputation: 591

Expression evaluation in C

#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.

Upvotes: 2

Views: 145

Answers (3)

powerMicha
powerMicha

Reputation: 2773

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

See C Operator Precedence Table.

Upvotes: -1

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

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.

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 993105

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

x -- - y

before precedence rules are applied.

Upvotes: 9

Related Questions