Implicit return value from a proc

Viewed 197

The nim lang tutorial here says -

A procedure that does not have any return statement and does not use the special result variable returns the value of its last expression.

Why does my echo res print 0 ? Shouldn't I expect the last statement a mod b (= 3) to be returned?

proc divmod(a, b: int; res, remainder: var int): int =
  res = a div b        
  remainder = a mod b  
  

var
  x, y: int

let res: int = divmod(8, 5, x, y) # modifies x and y

echo res
1 Answers

In your divmod proc remainder = a mod b is a statement, not an expression, so divmod returns the default value for int which is 0.

I'm not sure why'd you want to both return remainder by a mutable argument and the result, but this is how you can do it:

proc divmod(a, b: int; res, remainder: var int): int =
  res = a div b        
  remainder = a mod b
  remainder # or result = remainder
  

var
  x, y: int

let res: int = divmod(8, 5, x, y) # modifies x and y

echo res

This is how your proc can be remade if you don't really need to modify existing values:

proc divmod(a, b: int): (int, int) =
  (a div b, a mod b)

let (x, y) = divmod(8, 5)

echo x, " ", y
Related