这是我从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位的
关于strtoll
:long long
保证至少64位宽。因此,对于strto64
。
在支持long long int
的系统上,它至少是64位整数。另一方面,long int
的保证是至少是一个32位整数。在某些系统/使用某些编译器上,long int
是一个64位整数。在其他方面,只有32位。Google标头希望long int
在不提供strtoll
或strtoq
的系统上确实是64位,因为否则无法将字符串转换为long long int
。