为什么有时人们更喜欢Strtoll而不是Strtol,即使他们只想将字符串转换为INT32

Why sometimes people prefer strtoll to strtol even they only want to convert a string to an int32?

本文关键字:只想 他们 字符串 INT32 转换 Strtol 更喜欢 Strtoll 为什么      更新时间:2023-10-16

这是我从Google的Gflags源代码

中读取的代码段
case FV_INT32: {
  const int64 r = strto64(value, &end, base);
  if (errno || end != value + strlen(value))  return false;  // bad parse
  if (static_cast<int32>(r) != r)  // worked, but number out of range
    return false;
  SET_VALUE_AS(int32, static_cast<int32>(r));
  return true;
}

和宏定义strto64

// Work properly if either strtoll or strtoq is on this system
#ifdef HAVE_STRTOLL
# define strto64  strtoll
# define strtou64  strtoull
#elif HAVE_STRTOQ
# define strto64  strtoq
# define strtou64  strtouq
#else
// Neither strtoll nor strtoq are defined.  I hope strtol works!
# define strto64 strtol
# define strtou64 strtoul
#endif

显然,作者更喜欢Strtoll而不是Strtol。根据这两个功能的人页面, 一个返回 long long int ,另一个返回 long int 。如果您只想要INT32,他们都可以,对吗?

那么,这两个功能有什么区别?为什么首选Strtoll?

您的问题实际上是:"当标志为 FV_INT32时,在此处使用strto64?":

由于此检查,此代码似乎更喜欢strto64

if (static_cast<int32>(r) != r)

因此,它首先尝试尽可能多地吞噬数字,因此strto64。有了可以舒适地检查适合32位的

之后。

关于strtolllong long保证至少64位宽。因此,对于strto64

更有意义

在支持long long int的系统上,它至少是64位整数。另一方面,long int的保证是至少是一个32位整数。在某些系统/使用某些编译器上,long int是一个64位整数。在其他方面,只有32位。Google标头希望long int在不提供strtollstrtoq的系统上确实是64位,因为否则无法将字符串转换为long long int

相关文章: