In csh, why does 4 - 3 + 1 == 0?

社会主义新天地 提交于 2019-12-01 14:53:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!