Chinaunix首页 | 论坛 | 博客
  • 博客访问: 11238
  • 博文数量: 5
  • 博客积分: 150
  • 博客等级: 入伍新兵
  • 技术积分: 60
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-22 23:21
文章分类

全部博文(5)

文章存档

2012年(3)

2011年(2)

我的朋友
最近访客

分类: C/C++

2012-04-15 20:55:15

之前在编写代码时,遇到了一个比较傻X的问题
如:
string tmpstr = "Hello Jack";
string::size_type pos = tmpstr.find("Ana");
if (pos >= 0)
{
cout << "Find";
}
else
{
cout << "Not Find";
}
printf("%d", pos);
发现打印居然是“Find”,因而很怀疑返回值,所以就用printf将pos值用%d进行打印,pos = -1。
-1 >= 0 这未必也太奇怪了?
将find 函数的返回含义进行了搜索,以下是具体说明:
//这是定义 static const size_t npos = -1;

Maximum value for size_t

npos is a static member constant value with the greatest possible value for an element of type size_t.

This value, when used as the value for a count parameter n in string's member functions, roughly indicates "as many as possible".

When used in some pos parameters that allow for out-of-range values, npos indicates the end of the string.

As a return value it is usually used to indicate failure.

This constant is actually defined with a value of -1 (for any trait), which because size_t is an unsigned integral type, becomes the largest possible representable value for this type.

注意红色的注释,将值定义位-1的原因是 sizt_t 是一个无符号数,它的值将被确保为一个大于任何有效小标的值。

之所以显示值是-1,并且还进入了if(pos >= 0)的判断,完全是因为程序里使用了printf("%d")的形式进行打印,这只是一个显示问题,如果换成 %u 就可以知道这个值就是0xffffffff,它当然 >= 0
并且程序中的这种判断完全是错误的,pos >= 0 ,这里存在着两种数据类型,在比较时将进行隐式转换,因而将是不安全的判断,正确的做法即是对同类型返回值进行比较 改为 if(string::npos == pos)
阅读(558) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~