## CCM Optional arguments

Consider the following function

 `````` function find_y(x,a,b,cin) real :: find_y,x real :: a,b,c real :: cin c=cin find_y=a*x**2 + b*x +c end function ``````

The a "normal" call to this might be:

 `````` z=find_y(1.0,10.0,20.0,0.0) ``````

Assume that for most calls to find_y we can assume some default value for cin, say zero. It might be useful to call find_y without specifing cin. For example:

 `````` z=find_y(1.0,10.0,20.0) ``````

With optional arguments in Fortran 90, this is legal.

The function shown above would need to be modified slightly.

 `````` function find_y(x,a,b,cin) real :: find_y,x real :: a,b,c real,optional :: cin if(present(cin))then c=cin else c=0.0 endif find_y=a*x**2 + b*x +c end function ``````

Note we have declared cin as optional. The intrinsic function "present" allows the procedure to determine the presence of an optional argument in the invocation argument list. If cin is present then c is assigned the value of cin, else c gets assigned a default value.

We can declare other parameters as optional.

 `````` function find_y(x,ain,bin,cin) real :: find_y,x real :: a,b,c real,optional :: ain,bin,cin a=0 b=0 c=0 if(present(ain))a=ain if(present(bin))b=bin if(present(cin))c=cin find_y=a*x**2 + b*x +c end function ``````

One other feature available is that we can specify the names of the parameters in the function call.

 `````` z=find_y(x=1.0,ain=10.0,bin=20.0,cin=0.0) ``````

When this is done, the order is not significant. We could say

 `````` z=find_y(x=1.0, ain=10.0, bin=20.0, cin=0.0) ! or z=find_y(x=1.0, bin=20.0, ain=10.0, cin=0.0) ! or z=find_y(bin=20.0, x=1.0, ain=10.0, cin=0.0) ! or z=find_y(bin=20.0, x=1.0, ,cin=0.0, ain=10.0) ``````

One place where specifing the names of the parameters is required is if you leave out parameters in the middle of the argument list.

 `````` z=find_y(x=1.0,ain=10.0,cin=0.0) ``````

Where bin was not specified.

Back to Basic API and user's guide