13
#!/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?

Rob Wells
  • 36,220
  • 13
  • 81
  • 146
Instantsoup
  • 14,825
  • 5
  • 34
  • 41

3 Answers3

33

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
alanc
  • 4,102
  • 21
  • 24
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
  • 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 Jun 18 '09 at 00:24
21

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

Brandon E Taylor
  • 24,881
  • 6
  • 47
  • 71
3

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

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117