Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

operators

csh

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

like image 348
Instantsoup Avatar asked Jun 17 '09 23:06

Instantsoup


2 Answers

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
like image 87
Paul Dixon Avatar answered Sep 30 '22 20:09

Paul Dixon


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

like image 34
Brandon E Taylor Avatar answered Sep 30 '22 20:09

Brandon E Taylor