Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top