问题
#!/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?
回答1:
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
回答2:
The + and - operators are right-associative in csh. This means that '4 - 3 + 1' is evaluated as '4 - (3 + 1)'.
回答3:
Operator grouping. It's reading the operation as 4 - (3 + 1), as opposed to (4 - 3) + 1.
来源:https://stackoverflow.com/questions/1010049/in-csh-why-does-4-3-1-0