5

I'd like a little clarification on the precedence of the return statement, which appears to go against the general precedence rules.

For example the expression

^ 2 + 3. 

returns 5(which is what I want) but shouldn't it return just 2 since Unary operators of which ^ is one has higher precedence over + which is Binary?.

Jatajuuf
  • 301
  • 3
  • 11

3 Answers3

10

There are no "unary operators" in Smalltalk. There are only 3 precedence levels: unary messages ("receiver message"), binary operators ("receiver + argument"), and n-ary keyword messages ("receiver message: argument1"). In all cases the receiver comes first.

So "^" is not an operator, but indicates a return statement. Similarly, in "-4" the "-" is not an operator but part of the number literal.

codefrau
  • 4,583
  • 17
  • 17
  • So I had it backwards, I kept thinking ^ was a message to be sent to 2. Thanks, that cleared it up. – Jatajuuf Jun 19 '11 at 11:51
  • `^` is a message send to thisContext, if you think of it (or thisContext parent) ^^ – mathk Jun 21 '11 at 15:28
  • Note that up to squeak 3.9, a space was accepted in negative literal numbers, like - 3. This was removed because non documented and a source of confusion as it could have been seen as a unary operator. – aka.nice Jun 14 '12 at 17:39
3

The return symbol, ^, is one of the few language built-ins constructs. Smalltalk will return the value of the expression following the ^ symbol.

SHODAN
  • 1,249
  • 10
  • 8
1

Is Smalltalk's ^ really an operator at all ? I guess it is rather a reserved symbol. And what should happen to the "dangling" + 3 then, when the surrounding method has returned? I think the behavior is correct as the return statement is the last statement to happen in a "normal" Smalltalk method.

Regards

Nico
  • 1,554
  • 1
  • 23
  • 35
  • I meant to imply operators/methods interchangeably. The behavior is correct but i'd like to know how the precedence rules for ^ is defined, and whether it's treated special or not. – Jatajuuf Jun 19 '11 at 11:06