0

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!

tmighty
  • 8,222
  • 19
  • 78
  • 182
  • Why do you cast (should be (int) by that way) them? Since they are the same type it does not matter. – Araw Jan 08 '14 at 12:56
  • What is this loop intended to achieve? (I'm guessing that `iFrameOffset` is initialy greater than `uStartFrame`?) – jrok Jan 08 '14 at 13:03

3 Answers3

2
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.

Zeta
  • 95,453
  • 12
  • 173
  • 214
1

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.

mockinterface
  • 13,017
  • 4
  • 25
  • 45
0

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.

mousomer
  • 2,022
  • 2
  • 17
  • 23