Supplying Values for Missing Keywords

N_ELEMENTS is frequently used to check for omitted plain and keyword arguments. N_PARAMS cannot be used to check for the number of keyword arguments because it returns only the number of plain arguments. (See Supplying Values for Missing Arguments.) An example of using N_ELEMENTS to check for a keyword parameter is as follows:

; Display an image with a given zoom factor.  
; If factor is omitted, use 4. 
PRO ZOOM, image, FACTOR = factor 
 
; Supply default for missing keyword parameter. 
IF N_ELEMENTS(factor) EQ 0 THEN factor = 4 

Note
If you use this method, the variable factor is defined has having the value 4, even though no value was supplied by the user. If the ZOOM procedure were called within another routine, the variable factor would be defined for that routine and for any other routines also called by the routine that called ZOOM. This can lead to unexpected behavior if you pass arguments from one routine to another.

You can avoid this problem by using different variable names inside the routine than are used in calling the routine. For example, if you wanted to supply a default zoom factor in the example above, but did not want to change the value of factor, you could use an approach similar to the following:

IF N_ELEMENTS(factor) EQ 0 THEN zoomfactor = 4 $
    ELSE zoomfactor = factor

You would then set the zoom factor internally using the zoomfactor variable, leaving factor itself unchanged.