Friday, March 19, 2021

A diabolical for-loop

Older people sometimes think that experience is knowledge. Sometimes it is, and sometimes it isn’t. In my experience.

Look at this:


Ooops now, sorry, that's it for those of you who are not technically minded. You can stop reading now, just after you consider this post sent to me by my daughter. Who must have thought, for some reason that I would appreciate the sentiment:


 Bye. Now for those remaining this...


...caused me some grief. It is the last part of a for loop:

    for (int e = 0 ; e < ikNumDegSymbols ; e = e++) {
        if (eIn == kDegsDescs[e].e) {
            return kDegsDescs[e].pszDesc;
        }
    }

What is strange is that I normally use e++, or i++ or whatever....

    for (int e = 0 ; e < ikNumDegSymbols ; e++) {

I must have been tired or dreaming when I used e = e++. But it has worked for years, this unnoticed glitch, in this one for-loop.

It worked until it didn't, one day the behaviour changed, suddenly the for loop never exited, and debugging revealed that e was stuck at was some random value, 23567 for example. At most it should have done 3 loops.

I asked some programmer friends, and they enlightened me. In the C++ language the behaviour of e=e++ is undefined! I'd never even considered that to be a possibility. Uninitialized variables are one thing, an increment and assignment being undefined is another.

Undefined behaviour means that the compiler can do WTF it wants. And an upgrade to the compiler had changed how it interpreted e = e++. I have no idea what it thinks of that operation now, seems almost like an unitialised variable.

One programmer in particular, Alessio Nava, much younger than me, said he always used ++e, the behaviour of which is defined. So now I always use ++e.

Oh well, older people sometimes think that experience is knowledge. Sometimes it is, and sometimes it isn’t. In my experience.