Fun with compliers
cbailey
Posts: 15
So today I re-learned the important lesson of not referencing the zero memory location of an array. Boiled down here is my code:
If you run this you will notice the second test will fail unexpectedly for it is the same as the first test with its arguments switched.
If you adjust the code to make the FOR loop read "FOR(i=1;i<=10;i++)", then both tests will succeed as expected.
Does anyone know why the compiler would behave in this manner? Is there a fix for this or should I just never forget the lesson I re-learned (again) today?
DEFINE_DEVICE dvTP = 10001:1:0 dvDEBUG = 33333:1:0 DEFINE_VARIABLE INTEGER numbers[10] = {1,2,3,4,5,6,7,8,9,10}; DEFINE_FUNCTION INTEGER isInSet(INTEGER nInput){ LOCAL_VAR INTEGER i; FOR(i=0;i<=10;i++){ IF(nInput == numbers[i]){ RETURN 1; } } RETURN 0; } DEFINE_EVENT BUTTON_EVENT[dvTP,1]{ PUSH:{ IF( isInSet(1) AND (2 > 1) ){ SEND_COMMAND dvDEBUG, "'Test version 1 succeeds!'"; } ELSE{ SEND_COMMAND dvDEBUG, "'Test version 1 fails.'"; } //-------------------------------------------------- IF( (2 > 1) AND isInSet(1) ){ SEND_COMMAND dvDEBUG, "'Test version 2 succeeds!'"; } ELSE{ SEND_COMMAND dvDEBUG, "'Test version 2 fails.'"; } } }
If you run this you will notice the second test will fail unexpectedly for it is the same as the first test with its arguments switched.
If you adjust the code to make the FOR loop read "FOR(i=1;i<=10;i++)", then both tests will succeed as expected.
Does anyone know why the compiler would behave in this manner? Is there a fix for this or should I just never forget the lesson I re-learned (again) today?
0
Comments
Did you try reversing the tests (so that you do 2 before 1) to see if this has an impact?
In principle there should not be a difference in this case but accessing element 0 of an array probably gives an UNDEFINED behaviour... and then all bets are off as to what can happen. Some CPU vendors do have a serious statement about UNDEFINED stuff (AMD for example).
I am mentioning the first question because in my experience, it seems to me repeatedly accessing the 0th element that causes problems, not just once.
Fred
It seems that for some reason the compiler doesn't like version 2.
The fix, well, don't access the 0th element of an array. That actually does add something to the system log, so it's easy to catch.
Fred