options(*CONVERT) in RPGfree '
The *CONVERT option in RPG is specified to tell the compiler to automatically convert a value passed as a parameter to the correct type if it differs from the type defined in the procedure.
How OPTIONS(*CONVERT) Works
OPTIONS(*CONVERT) allows for automatic data
conversion between compatible types when a procedure or function is called with
a parameter of a different type than expected. For example, if a procedure is
defined with a numeric parameter and a different type, such as a decimal, is
passed to it, the compiler will automatically handle the conversion so that the
value matches the declared type.
**free // ******************************************************* // * convert to char * // ******************************************************* ctl-opt main(main) dftactgrp(*no); // * PGM start * // ******************************************************* dcl-proc main; dcl-s UTF8uni char(25) ccsid(*utf8) inz('IBM i (AS400) fans only'); dcl-s vFloat Float(8) inz(123) ; dsply (cvtToChar(UTF8uni)) ; dsply (cvtToChar(vFloat)) ; dsply (cvtToChar(%timestamp())) ; dsply (cvtToChar(%date())) ; dsply (cvtToChar(1.2345678901)) ; end-proc; dcl-pi *n varchar(40); ConvertedtoChar varchar(40) const options(*convert); end-pi; return ConvertedtoChar; end-proc; |
Here’s a breakdown of how each call works:
- String
with UTF-8 (UTF8uni): cvtToChar receives a UTF-8 character string and
uses OPTIONS(*CONVERT) to ensure it's interpreted as VARCHAR(40). Since
it’s already a character type, minimal conversion is required.
- Float
Value (vFloat): OPTIONS(*CONVERT) converts vFloat, a floating-point
number, into a character string.
- Timestamp
and Date (%timestamp() and %date()): Both are non-character types, but
OPTIONS(*CONVERT) allows them to be passed as parameters, and the compiler
automatically converts them to a string representation.
- Constant Decimal (1.2345678901): This decimal constant is automatically converted to a VARCHAR type, demonstrating compatibility with numeric literals.
When to Use It
Some tips to use it effectively?
What do you think? Have you used OPTION(*CONVERT) in your RPG projects?
Triggers for log-programs. We can now drop MOVEL and use this instead.
ReplyDelete