# Indexed variables in compile

In this contribution Leonid Shifrin says that

You can not really use indexed variables in Compile, although it may appear that you can.

This sounds ambiguous to me. Is it possible or is it not possible? And if the former is true, how to implement indexed variables in compile? This would simplify one of my programs a lot.

• I'm afraid this is a bit too board, can you add a specific example? – xzczd Oct 15 '18 at 14:41
• It's just the idea to generate something like Table[var[i],{i,1,10}] within Compile and then assign values to the different var[i]. That's what I mean about indexed variables. Sorry for the confusion. – Display Name Oct 15 '18 at 14:44
• I don't remember exactly, but I think what I meant was that while you can compile this: Compile[{{x[1], _Integer}, {y[1], _Integer}}, x[1] + y[1]] down to MVM byte code or C just fine, the following, for example: Compile[{{a, _Integer}, {b, _Integer}}, Module[{x}, x[1] = a; x[2] = b; x[1] + x[2]]], will use the calls to main evaluator. You can see that by loading Get["CompiledFunctionTools"] and calling CompilePrint on resulting CompiledFunctions. – Leonid Shifrin Oct 15 '18 at 14:57
• If I understand your question correctly, I think we can achieve something similar with the help of code-generation technique e.g. here. But it's hard to help without a complete example, so once again, please be more specific. BTW, another related post is this. – xzczd Oct 15 '18 at 14:59
• @LeonidShifrin: Yes, this is exactly the problem I was referring to. Would have been great to use these kind of indexed variables without explicitely specifying them which doesn't seem to be possible then. But I like Henrik Schumacher's workaround. Thank you for the links xzczd! – Display Name Oct 15 '18 at 19:13

Well, one can use arrays to emulate indexed variables. As an example I do something which is usually verboten: I use Subscript (but in a controlled environment):

cf = With[{Subscript = Part},
Compile[{{a, _Integer}, {b, _Integer}},
Block[{x},
x = Table[0, 2];
Subscript[x, 1] = a;
Subscript[x, 2] = b;
Subscript[x, 1] + Subscript[x, 2]
]
]
];


Now,

CompiledFunctionToolsCompilePrint[cf]


shows that this compiles nicely without calls to MainEvaluate...