top of page
Search

Using arrays of variable length as FC/FB arguments

  • Writer: Ivaylo Fiziev
    Ivaylo Fiziev
  • 5 hours ago
  • 2 min read

Suppose you have an array of integers that has to be sorted. How would you implement a function that sorts it? The function should be able to take arrays of any length right? How do you express this in SCL? Typically arguments are type checked before calling the function. In SCL the array length is part of the type. This means that Array[1..10] of BYTE and Array[1..15] of BYTE are actually two different types. In other words - the lengths of the argument / actual argument array should match!

Not any more!

Starting with version 2606 SCL supports arrays of variable lengths as FC/FB arguments. So instead of providing the exact length you simply use a placeholder (*) for it. The actual length is determined at runtime using a set of standard functions.


Here is a version of the bubble sort function working on BYTE arrays:

FUNCTION "BUBBLE_SORT_BYTE" : VOID
VERSION:1.0
VAR_IN_OUT
	buff:Array[*] of BYTE;
END_VAR
VAR_TEMP
	i,n: UINT;
	tmp:REAL;
	swap:bool;
	lbound:dint;
	ubound:dint;
END_VAR
BEGIN
	#lbound := LOWER_BOUND(ARR:=#buff, DIM:= 1); // array start index
	#ubound := UPPER_BOUND(ARR:=#buff, DIM:= 1); // array end index
	for #n := #ubound - 1 to #lbound do
		#swap:= false;			
		for #i := #lbound to #n do
			if #buff[#i] > #buff[#i+1] then
				#tmp := #buff[#i+1];			// swap elements
				#buff[#i+1] := #buff[#i];		//
				#buff[#i] := #tmp;			//
				#swap := true;
			end_if;
		end_for;
		if not #swap then
			exit;							// break the loop
		end_if;								
	end_for;
END_FUNCTION

How does this work?

The only difference compared to before is that the array length is ignored during type checks. However you still need to use a single dimensional array.

What will happen if you pass a two dimensional array? - The array will still be sent to the function but when you try to index it, you'll gen an error since the function only indexes the first dimension.

What will happen if you pass an array of INT instead of an array of BYTE? - You'll get a type compatibility error.

What will happen If you miss the actual argument for the array? - You'll get an error since the SCL interpreter does not know how to allocate a variable of this type.

How about the new functions? - LOWER_BOUND / UPPER_BOUND are quite straight forward. You give them the array and the dimension index (1 based) and they return the index of the first / last element of the array.


On the level of the API, ISCLArrayInfo.Rank = 0 indicates this situation. Since the rank is not specified the function will accept arrays of any length.



 
 
 

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Subscribe Form

Thanks for submitting!

bottom of page