关于stl的一个现象,大家讨论一下

Smile_Tiger 2009-08-24 06:23:11
代码如下:

#include "stdafx.h"
#include <string>
#include <vector>
#include <map>

int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> v;
int debug;

if(0 > (v.size()-100))
{
debug = 1;
}
else
{
debug = 2;
}
return 0;
}

其结果为debug = 2,为什么?

在vs2005和vc6.0下是这种结果,其他版本没有试验过,其中vs2005是安装了sp1补丁的

将代码改成如下这样

#include "stdafx.h"
#include <string>
#include <vector>
#include <map>

int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> v;
int debug;

int c = (v.size()-100);
if(0 > c)
{
debug = 1;
}
else
{
debug = 2;
}
return 0;
}

其结果为debug = 1
...全文
71 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
leizhe 2009-08-24
  • 打赏
  • 举报
回复
v.size()-100
v.size()是unsigned的 无符号数 0 所以说它的最小范围就到0了 在减100操作会溢出

fallening 2009-08-24
  • 打赏
  • 举报
回复
呵呵,unsigned v.s. signed
Smile_Tiger 2009-08-24
  • 打赏
  • 举报
回复
我晕,我犯低级错误了
xingzhe2001 2009-08-24
  • 打赏
  • 举报
回复
v.size()-100
v.size()是unsigned的,v.size()-100 = 0xfffff*可能是这样的,肯定有 0<0xfffff*所以debug=2。

第二种强转成int,那就变成-100,所以-100 < 0, debug=1
  • 打赏
  • 举报
回复
int main()
{
vector<int> v;
cout<<typeid(v.size()-100).name()<<endl;
}

输出unsigned int 而不是 int
  • 打赏
  • 举报
回复
size返回的是无符号数字
只会比0大

后面的代码你改成有符号了,是一个负数自然比0小了。
Smile_Tiger 2009-08-24
  • 打赏
  • 举报
回复
附第一个代码的反汇编

00411605 mov eax,0CCCCCCCCh
0041160A rep stos dword ptr es:[edi]
0041160C mov eax,dword ptr [___security_cookie (41A098h)]
00411611 xor eax,ebp
00411613 push eax
00411614 lea eax,[ebp-0Ch]
00411617 mov dword ptr fs:[00000000h],eax
std::vector <int> v;
0041161D lea ecx,[ebp-24h]
00411620 call std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (411028h)
00411625 mov dword ptr [ebp-4],0
int debug;

if(0 > (v.size()-100))
0041162C lea ecx,[ebp-24h]
0041162F call std::vector<int,std::allocator<int> >::size (4111A4h)
00411634 sub eax,64h
00411637 jmp wmain+62h (411642h)
{
debug = 1;
00411639 mov dword ptr [ebp-30h],1
}
else
00411640 jmp wmain+69h (411649h)
{
debug = 2;
00411642 mov dword ptr [ebp-30h],2
}
return 0;

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧