Relation between FOR-TO and max. count of function parameters

Today I have hit one “C/Side-effect” (C/Side side-effect). It took me some time to begin understand what is the problem. And I want to share it with you.

How it begin

Imagine these two code parts:

Example 1:

MyFunction(Param1,Param2,Param3,Param4,Param5,Param6,Param7,Param8,Param9,

                    Param10,Param11,Param12,Param13,Param14,Param14,Param15,Param16,Param17);

Example 2:

 

for j :=1 to 1 do begin
    MyFunction(Param1,Param2,Param3,Param4,Param5,Param6,Param7,Param8,Param9,

                       Param10,Param11,Param12,Param13,Param14,Param15,Param16,Param17);
end;

Question is, what is the main difference?

 

Answer is: the Example 2 cannot be compiled… are you shocked? I was too… :-)

The error which you will get is:

—————————
Microsoft Dynamics NAV
—————————
Reduce the expression so it is less complex.

—————————
OK  
—————————

 

Why? In the example 1 the expression is same and it is not too complex. What’s the problem?

First I tried to nest the function call into IF-THEN-ELSE or REPEAT-Until blocks => no problem.

Problem is the for-to loop. I did more research on this and conclusion was: each for-to loop decrease the maximum number of parameters of called function inside the loop by 3 when the loops are nested. The number of parameters is not related to data type of the parameters. You could have same count of parameters regardless they are text1000 or text1 type.

Implications:

1) C/Side have limited stack for local variables – max is 20

2) Each for-to loop is taking 3 local variables in the stack (may be “start value”, “control value”, “end value”?)

3) You can have only 6 nested for-to loops in C/AL (20 div 3 = 6) – after that you will get same error

4) If you need more, use repeat-until or while loops or move the nested loops into some new function

5) If you nest 6 for loops, you can call only functions with only one parameter within the most nested loop… :-)

Result

If you will see this kind of error, just check number of parameters of the function and look at nested for-to loops. If the parameters count is <20, replace the for-to loop with while-do or if-repeat-until loops.

It seems that this limitation is because magic number 20 is used in the language syntax analyzer when creating stack of local “variables”.

20 is magic number everywhere in C/Side and C/Al. You can have only 20 SumIndexFields for each key, you can have only 20 fields in primary key etc…

 

Tested on NAV5.00SP1 Update 2.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>