# Returning a value from a Module

In the following simple example

MyMod := Module[{i},
Do[
Return[1],
{i, 3}
];
Print["test"]
]


I expected the module to exit on Return and never reach the Print, instead I have

In[1]:= a = MyMod
test


I am sure I always used the former expected logic in the past.
I lost my memory or is it changed something in the way Return works?

-

You need to use Module option on return

myMod := Module[{i},
Do[
Return[1, Module],
{i, 3}
];
Print["test"]
]


and now

 myMod
(* 1 *)


This is because Return only returns from nearest enclosure, which was Do in your case and not from the whole Module unless you use the Module second option to Return. This is different from other languages that you might be familiar with.

update

To answer the question in comment below if Return has always worked this way?

Using V 2.2 of Mathematica, the Module option was not supported since I get an error. So this option was added sometime after version 2.2. May be someone else knows when it was added.

ps. looking at bottom of the Return help page, it says it was updated in 1996 (version 3.0), so I would assume this is when the option Module was added.

-
Thank you, can I ask if you know if Return has always worked this way? – enzotib Mar 23 '14 at 17:02
@enzotib Let me reboot my version 2.2 of Mathematica and see. I can't answer this question right now. I would think it always worked this way in Mathematica, but I do not know. May be someone else would. But I will check 2.2 to see. – Nasser Mar 23 '14 at 17:04
Also, I cannot find any reference to a possible second parameter to Return in that document. – enzotib Mar 23 '14 at 17:05
@enzotib it a secret option :) I am sure it is there somewhere, but need more time to find it now. – Nasser Mar 23 '14 at 17:06
@enzotib The documentation is well hidden. Also see the discussion here. – WReach Mar 23 '14 at 17:37