[英]C++ unsigned long and <
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. uStartFrame和iFrameOffset都是无符号的,所以<语句有点困难。 However, I thought that I fixed it using int(). 但是,我认为我使用int()修复了它。 But the loop runs infinitively, so I guess it doesn't work. 但是循环会无限期地运行,所以我想它是行不通的。
Can somebody help? 有人可以帮忙吗?
Thank you! 谢谢!
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
. 如果uStartFrame
为0
,则没有可以满足uStartFrame == x + 1
的无unsigned long
变量x
。
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: 但是这种C风格的转换不是真正的C ++风格,在您的情况下, static_cast
是更可取的:
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. 除此之外,在编写int()(x)
您定义了一个返回整数且不接受任何参数的函数,然后使用uStartFrame-iFrameOffset作为参数调用它。 It shouldn't even compile, well at least gcc 4.8 rightfully complains about this. 它甚至不应该编译,至少gcc 4.8正确地对此抱怨。
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)的函数,这可能解释了循环永远运行的原因。
You're casting the test (uStartFrame-iFrameOffset) into int, not the iFrameOffset. 您正在将测试(uStartFrame-iFrameOffset)转换为int,而不是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. 因此,如果iFrameOffset很大(最大可能为2 ^ 64-1-或更大,具体取决于系统),则可能需要2 ^ 64个循环才能结束。
This could be as much as a giga seconds. 这可能多达千兆秒。 So, you should rethink this loop. 因此,您应该重新考虑这个循环。 It's not a goo idea. 这不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.