3

I'm currently developping a vision system which is controlled/moonitored via a computer application that I'm writting in C/C++. If you are wondering why I,m writting in C/C++ its basically that my vision sensor (LMI Gocator 2490) has functions developped in C and that I'm using opencv (C++) to analyse its data. Long story short, I've had 1 informatics course which was in C and I'm bad at C++.

I'm wondering if there is a simple way, using or writting a function for example, to retrieve an array index that loops back to its begining instead of trying to read write in an index that isn't part of the array which also causes mem access violation. For example:

long a[4];

for (size_t i = 0; i < sizeof(a) / sizeof(long); i++)
{
    if (a[i] && a[i + 1]) //Define some conditions regarding a[i] and a[i+1]
    {
        //Process code
    }
}

So here, its easy to understand that when i will reach the value of 3, I will get mem access violation. What I would like to do, is to have some sort of mecanism which would return a array index that "looped" back to begining. In the case shown above, i+1 where i = 3 would be 0. If I were to put i+2, I would like to get 1, and so on...

This might be silly but it would save me the pain of writting 4 times the same logic in some switch/case statement inside a for-loop which then I'd need to apply modifications in all the 4 logics when debugging... Thank's!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214

1 Answers1

2

use modulus to wrap when reaching the upper bound

long a[4];
size_t sz = sizeof(a) / sizeof(long);

for (size_t i = 0; i < sz; i++)
{
    if (a[i] && a[(i + 1) % sz]) //Define some conditions regarding a[i] and a[i+1]
    {
        //Process code
    }
}

maybe not super-optimal performance wise, though (well, with a value of 4, the compiler can trade modulus for mask so it would be okay).

In the general case, avoid a division, and check if overruns then choose 0 if it does

for (size_t i = 0; i < sz; i++)
{
    size_t j = i < sz-1 ? i+1 : 0;
    if (a[i] && a[j]) //Define some conditions regarding a[i] and a[i+1]
    {
        //Process code
    }
}

(the code will work in C and C++)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • So obvious! In my case I do not have much performance issues so I'm not too worried about it. Thank you very much this will save me a whole bunch of headache :) – lfbaillargeon Nov 21 '21 at 17:47
  • I'd test this out before making that optimization; a branch is probably slower, though it's super-friendly to the branch-predictor. – Neil Nov 21 '21 at 17:52
  • yes, if performance matters, it may depend of the cpu used too. – Jean-François Fabre Nov 21 '21 at 18:07