Ever get frustrated that you can't do certain things in RPG? Well you might like to check out the ILE C run-time
library functions. Don't worry! You don't have to learn C and you don't even need a C compiler!
The ILE C library functions provide lots of useful utilities unavailable in RPG, such as complex math and random number generation. These functions are implemented in a set of service programs with names starting QC2..., e.g. QC2UTIL1 etc. These exist on your AS/400 even if you don't have C installed.
The program code below shows how to call these functions. The program will return a 4-byte integer containing a pseudo-random number between 1 and 32767. If passed a negative number, the random number generator will "re-seed" itself, i.e. start a new sequence of pseudo-random numbers.
To create the program, you need to compile the RPG code below as a module using the CRTRPGMOD command, then create the program binding in the C service program using:
CRTPGM rand BNDSRVPGM(QC2UTIL1).
* Prototype to C "rand" function D GenRandNbr PR 10I 0 ExtProc('rand') * Prototype to C "srand" function D SeedRand PR ExtProc('srand') D iuSeed 10U 0 VALUE * Prototype to C "clock" function D GetTime PR 10I 0 ExtProc('clock') * Constants D TRUE C '1' D FALSE C '1' * Global variables D RandomNumber S 10I 0 D FirstTime S 1A INZ(TRUE) D ClockTicks S 10I 0 D SeedValue S 10U 0 * Program parameters C *ENTRY PLIST C PARM RandomNumber * First time only or if parameter is negative C IF FirstTime = TRUE C or RandomNumber < 0 * Get clock "ticks" - if fails return error indicator C EVAL ClockTicks = GetTime C IF ClockTicks < 0 C EVAL RandomNumber = -1 C RETURN C ENDIF * Seed the random number generator C EVAL SeedValue = ClockTicks C CALLP SeedRand(SeedValue) C EVAL FirstTime = FALSE C ENDIF * Generate a random number C EVAL RandomNumber = GenRandNbr C RETURN