Optional function arguments

Hello,

I have created a function with some input parameters. The last input parameter is optional and should be initialized to -1 by default. When I try to call the function without this optional input parameter, the compiler shows an error that I have too few input parameters for the function.

Is it generally not possible to have optional input parameters in a function or do I have to declare the input parameters as optional. If so, how do I do this?

Unfortunately, I can’t find anything about this in the help.

Hi there,

there is no such thing as an optional parameter to a function, which is why you don’t find anything about it in the help.
You could make the function a function block instead - then you can skip passing any args.

Best regards

Hello,

i may just add some ideas about how to work around this:
You can Add an Second Input Parameter Named like “OptionxxxUsed” to pass the Information to the Function if a parameter is used or not. With this information you can Initialise the ParameterValue internaly to a Default value.

It adds a little bit of complexity to the Function Interface but you then have the possibility to have optional Parameters.

Using a Functionblock interface Definition like descriped by Michael adds some more comfort.

IF Parameter3Used = 0 THEN 
  InternalParameter3 := DefaultValue; 
ELSE
  InternalParameter3 := Parameter3;
END_IF

Greetings
Michael

Thank you Michael and Michael,

thanks for the reply, your suggestions are definitely good if I want to create a new function.

My problem is that I want to extend an existing function. And then the problem is that the function is already called >1000 times in my project. For this, an optional input that is initialized to a specific value by default would be very helpful so that I don’t have to change the existing function calls.

For that usecase you could make the existing function a wrapper for a new function.
I am using C-syntax here just to demonstrate what I mean:

void existingFunction(int arg1, int arg2)
{
    // Here used to be the old code - remove it and replace it with  this call
    newFunction(arg1, arg2, DEFAULT_VALUE_FOR_ARG3);
}

void newFunction(int arg1, int arg2, int arg3)
{
    // insert the source code of your existing function here and
    // add handling for arg3
}

That way you can keep existing calls and call the new function wherever you need the optional argument.