tags:

views:

283

answers:

3
#!/bin/csh

@ cows = 4 - 3 + 1
echo $cows

This simple csh script when run produces "0" for output when I'd expect "2".

~root: csh simple.1
0

I did a bunch of looking and the only thing I could think of was that the "-" was being read as a unary negation rather than subtraction, therefore changing operator precedence and ending up with 4 - 4 rather than 2 + 1. Is this correct? If so, any reason why? If not...help!

Edit: So they're right associative! These operators are NOT right associative in C, are they? Is C-Shell that different from C?

+2  A: 

Operator grouping. It's reading the operation as 4 - (3 + 1), as opposed to (4 - 3) + 1.

McWafflestix
+15  A: 

The + and - operators are right-associative in csh. This means that '4 - 3 + 1' is evaluated as '4 - (3 + 1)'.

Brandon E Taylor
Gave both +1 but Paul's answer has the pretty picture and the nice link.
Instantsoup
I gave a Paul a +1 as well. Looks like I need to brush up on my ASCII art.
Brandon E Taylor
+28  A: 

While you are expecting the operators to be left associative, they are right associative in csh, so it's evaluated as 4-(3+1)

   -
  / \
 /   \
4     +
     / \
    3   1
Paul Dixon
damn! spent too long finding a link!
Paul Dixon
and making ascii art parse trees
Paul Dixon
I have been 'scooped' several times for the very same reason.
Brandon E Taylor
I gave you +1 anyway, you're about to hit 1000 rep, a nice milestone!
Paul Dixon
+1 for the ASCII art and the reference.
Eddie
Just answer quickly and spend less than 5 minutes making it pretty and linky :P
Ólafur Waage
Look at that, it all came good in the end :)
Paul Dixon
Among many right answers, the best should be accepted!
Instantsoup
+1 for the AST.
Andrew Coleson
That is not a parse tree. It is not an AST. Look at the BNF again and see how both operands and operators are child nodes of an expression node. Compilers have to do extra work to convert parse trees to expression trees.
Windows programmer

related questions