这个避免有符号/无符号比较的 C 转换是否有意义?
我正在审查一个 C++ 项目,并有效地看到以下内容:
std::vector<SomeType> objects;
//then later
int size = (int)objects.size();
for( int i = 0; i < size; ++i ) {
process( objects[i] );
}
这是我所看到的。 std::vector::size()
返回 size_t
,其大小可以与 int
的大小无关。即使 sizeof(int) == sizeof(size_t)
int
有符号,也不能容纳 size_t
的所有可能值。因此上面的代码只能处理很长向量的下半部分并且包含一个错误。正确的方法是使用 size_t
作为 size
变量和循环索引。
那我很好奇作者为什么要写这个?
我唯一的猜测是,首先他省略了 (int)
转换,编译器发出了类似 Visual C++ C4018 警告:
warning C4018: '<' : signed/unsigned mismatch
因此作者认为避免编译器警告的最佳方法是将 size_t
强制转换为int
从而使编译器关闭。
C 演员阵容还有其他可能的合理原因吗?
I'm reviewing a C++ project and see effectively the following:
std::vector<SomeType> objects;
//then later
int size = (int)objects.size();
for( int i = 0; i < size; ++i ) {
process( objects[i] );
}
Here's what I see. std::vector::size()
returns size_t
that can be of some size not related to the size of int
. Even if sizeof(int) == sizeof(size_t)
int
is signed and can't hold all possible values of size_t
. So the code above could only process the lower part of a very long vector and contains a bug. The right way would be to use size_t
for both the size
variable and the loop index.
That said I'm curious of why the author might have written this?
My only guess is that first he omitted the (int)
cast and the compiler emitted something like Visual C++ C4018 warning:
warning C4018: '<' : signed/unsigned mismatch
so the author though that the best way to avoid the compiler warning would be to simply cast the size_t
to int
thus making the compiler shut up.
Is there any other possible sane reason for that C cast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这可能就是原因。另外,向量可能永远不会太长,以至于有截断大小的风险(应用程序开发人员会知道这一点)。
而且......也许在程序的某些部分,他实际上将“size”与其他 int 类型的东西进行了比较,因此将 size 设置为“size_t”类型将在一个地方修复它,但在其他地方破坏它。
No, that is probably the reason. Plus the fact that the vector would probably never be so long that it would risk truncating the size (the app. developer would know that).
And... maybe in some parts of the program he actually compared "size" with something else that was int-typed, so making size a "size_t" type would fix it in one place, but break it somewhere else.
我想说的是,在 C 和 C++ 中大量使用 C 强制转换只是为了让编译器关闭,而很少或根本没有努力去尝试理解它告诉你的内容。悲伤,但却是事实。
I would say that the overwhelming use of C casts in both C and C++ is simply to make the compiler shut up, with little or no effort given to trying to understand what it is telling you. Sad, but true.
明显的答案是使用:
或者迂腐地正确:
OTOH,除非您确定需要自己编写循环,否则通常最好使用算法:
The obvious answer would be to use:
or to be pedantically correct:
OTOH, unless you're sure you need to write the loop yourself, you're generally better off using an algorithm: