RND bug when used with array's elements ?

Previous topic - Next topic

dbots

Hi all,
I am very new to GLBasic and impressed with its features.
I have been trying to write some demo programs and now I found this, please check and reply if I do something wrong :

When I use the code :
DIMDATA arr[], 10,20,30,40,50
WHILE TRUE
   PRINT arr[RND(5)], 100,100
   SHOWSCREEN
WEND

then program hungs almost immediately, but when I change the code to :
DIMDATA arr[], 10,20,30,40,50
WHILE TRUE
   PRINT RND(5), 100,100
   SHOWSCREEN
WEND

then program runs forever without hung

So, it seems to me that calling RND inside an array to call an element if it, make the problem.

If someone could help, I would be grateful. Thanks

kanonet

Its no bug here, just a little mistake that you made:

Code (glbasic) Select
DIMDATA arr[], 10,20,30,40,50
This creates an array, size it to five elements and fill, its basically the same like this:
Code (glbasic) Select
DIM arr[5]
arr[0]=10
arr[1]=20
arr[2]=30
arr[3]=40
arr[4]=50


Code (glbasic) Select
RND(5)This can generate 'random' numbers, your result may be one of the following: 0,1,2,3,4,5

So now imagine what happens when RND() gives you the random number 5.
Since there is no array element arr[5] (look again above), your program crashes. Change your line to arr[RND(4)] and everything works fine.

BTW if you enable the debugger you get better information when you make an mistake (this happens to all of us way more often than we want lol). In this case you would have gotten an "array out of bounds" error which means that you tried to call an array with an element that does not exist.
Lenovo Thinkpad T430u: Intel i5-3317U, 8GB DDR3, NVidia GeForce 620M, Micron RealSSD C400 @Win7 x64

dbots

Wow, that makes me feel like a dump  :giveup:
I thought that rnd(x) would give results 0..x-1, as I have used for years in C++
Anyway, thank you very much kanonet, for your reply