C++ unsigned long and <

163 views Asked by At

I have the following code:

while( int()(uStartFrame - iFrameOffset) < 1)
{
    iFrameOffset--;
}

uStartFrame and iFrameOffset are both unsigned long, so the < statement is a little difficult, I think. However, I thought that I fixed it using int(). But the loop runs infinitively, so I guess it doesn't work.

Can somebody help?

Thank you!

3

There are 3 answers

3
Zeta On BEST ANSWER
while( uStartFrame < iFrameOffset + 1)
{
    iFrameOffset--;
}

Or even better

if(uStartFrame < iFrameOffset + 1)
    iFrameOffset = uStartFrame - 1;

The last line also shows the possible error. If uStartFrame is 0, then there's no unsigned long variable x that can fulfil uStartFrame == x + 1.

0
mockinterface On

The cast is wrong, you should cast it like this,

(int)(uStartFrame - iFrameOffset) < 1

but this C-style cast is not really C++ style, in your case a static_cast is preferable:

static_cast<int>(uStartFrame - iFrameOffset) < 1
static_cast<unsigned long>(uStartFrame - iFrameOffset) < 1

Apart from that, when you write int()(x) you define a function that returns an integer and accepts no parameters, and then invoke it with uStartFrame - iFrameOffset as an argument. It shouldn't even compile, well at least gcc 4.8 rightfully complains about this.

Your compiler obviously does compile it and maybe even wrongly treats it as a function that returns an un-initialized integer, most likely 0, and that possible explains why your loop runs forever.

0
mousomer On

You're casting the test (uStartFrame-iFrameOffset) into int, not the iFrameOffset. So, if the iFrameOffset is big (max could be 2^64-1 - or bigger depending on system), then you might need 2^64 loops to get to the end.

This could be as much as a giga seconds. So, you should rethink this loop. It's not a goo idea.