Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to compile recursive formula when it relies on more than a few global variables (global to the topmost compiled function)? It is unreasonable to pass on all such variables to each recursive subroutine (there are more than one), as:

  • that would require a lot of tensor copying which would cause a slowdown;
  • even if passing globals would be possible, returning all affected globals from each subroutine would be tedious as each function must return a regular tensor of uniform data type.

Consider the following toy problem to calculate the factorial:

fact[x_] := Module[{sub, global = 1},
   sub[y_] := If[y > 0, global = global*y; sub[y - 1]];

How to compile it without passing global to sub? While this code works nicely in the general Mathematica interface, the following compiled version will call MainEvaluate as there is a SetDelayed expression which the compiler cannot handle:

factC = Compile[{{x, _Integer}}, Module[{global = 1, sub},
    sub[y_] := If[y > 0, global = global*y; sub[y - 1]];

Is there any way to overcome this problem?

share|improve this question
Related mathgroup post: Pass by reference for compiled functions No solution general enough though. – ssch Aug 26 '13 at 21:37
@ssch This pretty much tells me that what I want is impossible at the moment. I might be more successful writing code directly in C and than calling from under Mathematica... – István Zachar Aug 26 '13 at 21:52
Yea :( Perhaps passing the globals in the Compiled functions and then replace them with pointers in the CCodeStringGenerate can save some (writing) time. – ssch Aug 26 '13 at 22:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.